hdu 1116 Play on Words
http://acm.hdu.edu.cn/showproblem.php?pid=1116
#include<iostream>
#include<string>
using namespace std;
int in[30],out[30],bin[30],d[30];
int findx(int x)
{
if(bin[x]==-1) bin[x]=x;
while(x!=bin[x]) x=bin[x];
return x;
}
int main()
{
int t,n,i,x,y;
string str;
cin>>t;
while(t--)
{
cin>>n;
memset(bin,-1,sizeof(bin)); memset(d,0,sizeof(d));
memset(in,0,sizeof(in)),memset(out,0,sizeof(out));
for(i=1;i<=n;i++)
{
cin>>str;
x=str[0]-'a'+1; d[x]=1;
y=str[str.size()-1]-'a'+1; d[y]=1;
in[y]++,out[x]++;
x=findx(x);
y=findx(y);
if(x!=y) bin[y]=x;
}
int cnt=0;
for(i=1;i<=26;i++)
if(d[i]&&bin[i]==i) cnt++;
if(cnt>1)
{
cout<<"The door cannot be opened."<<endl; continue;
}
for(cnt=0,i=1;i<=26;i++)
if(in[i]!=out[i]) d[cnt++]=i;
if(cnt==0) { cout<<"Ordering is possible."<<endl; continue;}
if(cnt==2)
if((in[d[0]]==out[d[0]]+1&&in[d[1]]==out[d[1]]-1)||(in[d[0]]==out[d[0]]-1&&in[d[1]]==out[d[1]]+1))
{
cout<<"Ordering is possible."<<endl; continue;
}
cout<<"The door cannot be opened."<<endl;
}
return 0;
}