POJ 1386 Play on Words [欧拉路]

题意:字母若一首一尾相同,可相互连接,问是否能连成一串。

思路:若可连接,每个点的入度和出度相同,则为欧拉回路,仅有两个点(一个入度比出度多一,一个出度比入度多一),则为欧拉路。两者皆成立。

#include <iostream>
#include <string.h>
using namespace std;
int in[30],out[30],father[30];
bool is[30];
int find(int x){
    if(father[x]!=x)
        father[x]=find(father[x]);
    return father[x];
}
int main(){
    int t,n,a,b;
    char c[1002];
    bool f;
    cin>>t;
    while(t--){
        int x=0,y=0;
        f=true;
        memset(in,0,sizeof(in));
        memset(out,0,sizeof(out));
        memset(is,0,sizeof(is));
        for(int i=0;i<26;i++)
            father[i]=i;
        cin>>n;
        while(n--){
            cin>>c;
            a=c[0]-'a';
            b=c[strlen(c)-1]-'a';
            in[a]++;
            out[b]++;
            is[a]=1;
            is[b]=1;
            a=find(a);
            b=find(b);
            if(a!=b) father[b]=a;
        }
        int ii;
        for(int i=0;i<26;i++)
            if(is[i]){
                ii=find(i);
                break;
            }
        for(int i=0;i<26;i++){
            if(is[i]&&ii!=find(i)){
                f=false;
                break;
            }
        }
        if(f){
            for(int i=0;i<26;i++){
                if(in[i]!=out[i]){
                    if(in[i]-out[i]==1) x++;
                    else if(out[i]-in[i]==1) y++;
                    else{
                        f=false;
                        break;
                    }
                }
            }
            if(f&&((x==1&&y==1)||(x==0&&y==0))) cout<<"Ordering is possible."<<endl;
            else cout<<"The door cannot be opened."<<endl;
        }
        else cout<<"The door cannot be opened."<<endl;
    }
    return 0;
}
/*测试:
Sample Input
3
2
acm
ibm
3
acm
malform
mouse
2
ok
ok
Sample Output
The door cannot be opened.
Ordering is possible.
The door cannot be opened.
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值