Play on WordsTime Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 9653 Accepted Submission(s): 3313 Problem Description Some of the secret doors contain a very interesting word puzzle. The team of archaeologists has to solve it to open that doors. Because there is no other way to open the doors, the puzzle is very important for us.
Input The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing a single integer number Nthat indicates the number of plates (1 <= N <= 100000). Then exactly Nlines follow, each containing a single word. Each word contains at least two and at most 1000 lowercase characters, that means only letters 'a' through 'z' will appear in the word. The same word may appear several times in the list.
Output Your program has to determine whether it is possible to arrange all the plates in a sequence such that the first letter of each word is equal to the last letter of the previous word. All the plates from the list must be used, each exactly once. The words mentioned several times must be used that number of times.
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. |
解题思路:
将每个单词的首尾字母看做一条有向连线,用并查集判断该图是否连通,若不连通则直接输出“The door cannot be opened.”。
反之,则根据有向图的每个顶点出入度相等 或 有且仅有一个顶点出度=入度+1,另一个入度=出度+1,判断是否能够形成欧拉路径,如果可以则输出“Ordering is possible. ”,反之“The door cannot be opened.”。
代码:
#include<bits/stdc++.h>
using namespace std;
int pre[30],in[30],out[30],v[30];
int find(int x)
{
int r=x;
while(pre[r]!=r){
r=pre[r];
}
return r;
}
void join(int x,int y)
{
int i=find(x),j=find(y);
if(i!=j){
pre[j]=i;
}
}
int main()
{
int repeat;
scanf("%d",&repeat);
while(repeat--){
int n,x,y,root=0,num2=0,num3=0,flag=0;
char s[1005];
scanf("%d",&n);
memset(v,0,sizeof(v));
memset(pre,0,sizeof(pre));
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
for(int i=0;i<30;i++)pre[i]=i;
while(n--){
scanf("%s",s);
x=s[0]-'a';
y=s[strlen(s)-1]-'a';
out[x]++;
in[y]++;
join(x,y);
v[x]=1;v[y]=1;
}
for(int i=0;i<30;i++){
if(v[i] && pre[i]==i)root++;
}
if(root>1)printf("The door cannot be opened.\n");
else{
for(int i=0;i<30;i++){
if(v[i]){
if(in[i]!=out[i]){
if(in[i]==out[i]-1)num2++;
else if(in[i]==out[i]+1)num3++;
else flag=1;
}
}
}
if((!flag && num2==0 && num3==0) || (!flag && num2==1 && num3==1))
printf("Ordering is possible.\n");
else printf("The door cannot be opened.\n");
}
}
return 0;
}