HDU 1116 Play on Words

本文介绍了一个利用欧拉回路和并查集解决的问题实例,具体讨论了如何通过这两种算法来判断图的连通性和路径的可行性,最终实现对一系列字符串路径的有效验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

欧拉回路+并查集(判断图是否连通,被这坑了。。)

#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<stack>
#include<vector>
#include<queue>
#include<map>

using namespace std;

int p[30];

int find(int x){
    return x==p[x]?x:(p[x]=find(p[x]));
}

int main()
{
#ifndef ONLINE_JUDGE
 	freopen("a.in","r",stdin);
#endif
    int t;
    cin>>t;
    while(t--){
        int n,out[30],in[30],cnt=0,flag=false,c1=0,c2=0,c3=0;
        bool vis[30];
        fill(vis,vis+30,false);
        fill(out,out+30,0);
        fill(in,in+30,0);
        for(int i=0;i<30;i++) p[i]=i;
        cin>>n;
        int tn=n;
        while(n--){
            string word;
            cin>>word;
            int x=word[0]-'a';
            in[x]++;
            vis[x]=true;
            int y=word[word.size()-1]-'a';
            out[y]++;
            vis[y]=true;
            int tx=find(x),ty=find(y);
            p[tx]=p[ty];
        }
        for(int i=0;i<30;i++){
            if(vis[i]) c3++;
            if(abs(in[i]-out[i])==1) c1++;
            else if(vis[i]&&out[i]==in[i]) c2++;
        }
        for(int i=0;i<30;i++)
            if(vis[i]&&find(i)==i)
                cnt++;
        if(cnt>1){
            puts("The door cannot be opened.");
            continue;
        }
        if((c2==c3)||(c1==2&&c2==c3-2)) puts("Ordering is possible.");
        else puts("The door cannot be opened.");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值