题意:字母若一首一尾相同,可相互连接,问是否能连成一串。
思路:若可连接,每个点的入度和出度相同,则为欧拉回路,仅有两个点(一个入度比出度多一,一个出度比入度多一),则为欧拉路。两者皆成立。
#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.
*/