传送门:
http://acm.hdu.edu.cn/showproblem.php?pid=1116
Play on Words
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9939 Accepted Submission(s): 3399
There is a large number of magnetic plates on every door. Every plate has one word written on it. The plates must be arranged into a sequence in such a way that every word begins with the same letter as the previous word ends. For example, the word ``acm'' can be followed by the word ``motorola''. Your task is to write a computer program that will read the list of words and determine whether it is possible to arrange all of the plates in a sequence (according to the given rule) and consequently to open the door.
If there exists such an ordering of plates, your program should print the sentence "Ordering is possible.". Otherwise, output the sentence "The door cannot be opened.".
2
acm
ibm
3
acm
malform
mouse
2
ok
ok
Ordering is possible.
The door cannot be opened.
#include<iostream>
#include<stdio.h>
#include<memory.h>
using namespace std;
#define max_v 30
int in[max_v],out[max_v];
int vis[max_v];
int pa[max_v];
int rk[max_v];
int n;
void make_set(int x)
{
pa[x]=x;
rk[x]=;
}
int find_set(int x)
{
if(x!=pa[x])
pa[x]=find_set(pa[x]);
return pa[x];
}
void union_set(int x,int y)
{
x=find_set(x);
y=find_set(y);
if(x==y)
return ;
if(rk[x]>rk[y])//按秩合并
pa[y]=x;
else
{
pa[x]=y;
if(rk[x]==rk[y])
rk[y]++;
}
}
void init()//初始化
{
memset(in,,sizeof(in));
memset(out,,sizeof(out));
memset(vis,,sizeof(vis));
for(int i=; i<max_v; i++)//并查集初始化
make_set(i);
}
int main()
{
int t;
scanf("%d",&t);
string str;
while(t--)
{
init();
scanf("%d",&n);
for(int i=; i<n; i++)
{
cin>>str;
int x=str[]-'a';
int y=str[str.length()-]-'a';
in[x]++;//入度
out[y]++;//出度
vis[x]=;//出现过的标记
vis[y]=;
union_set(x,y);//合并
}
int root=;
for(int i=; i<max_v; i++)
{
if(vis[i]==&&pa[i]==i)//判断连通性
{
root++;
if(root>=)
break;
}
}
if(root>=)//不连通
{
printf("The door cannot be opened.\n");
continue;
}
int s1=,s2=,s3=;
for(int i=; i<max_v; i++)
{
if(vis[i]&&in[i]!=out[i])
{
if(in[i]==out[i]-)//链头
s1++;
else if(in[i]==out[i]+)//链尾
s2++;
else//不是链
s3++;
}
}
if(s3)
printf("The door cannot be opened.\n");
else if((s1==&&s2==)||(s1==&&s2==))//链或者环
printf("Ordering is possible.\n");
else
printf("The door cannot be opened.\n");
}
return ;
}