Description
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.
Input
Output
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.".
Sample Input
3
2
acm
ibm
3
acm
malform
mouse
2
ok
ok
Sample Output
Ordering is possible.
The door cannot be opened.
////////////////////////////////////////////////////////////////
# include<stdio.h>
# include<string.h>
int set[27],head[27],tail[27],mark[27];
int find(int x)
{
if(set[x]!=x)
set[x]=find(set[x]);
return set[x];
}
void Combain(int x,int y)
{
int fx,fy;
fx=find(x);
fy=find(y);
if(fx==fy)
return ;
else if(fx<fy)
set[fy]=fx;
else
set[fx]=fy;
}
int main()
{
int i,t,n,len,flag;
int a[27];
char s[1003];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<26;i++)
{
set[i]=i;
head[i]=0;
tail[i]=0;
mark[i]=0;
}
while(n--)
{
scanf("%s",s);
len=strlen(s)-1;
head[s[0]-'a']++;
tail[s[len]-'a']++;
mark[s[0]-'a']=1;
mark[s[len]-'a']=1;
Combain(s[0]-'a',s[len]-'a');
}
flag=0;
for(i=0;i<26;i++)
{
if(mark[i]&&set[i]==i)
flag++;
if(flag>=2)
break;
}
if(flag>=2)
printf("The door cannot be opened.\n");
else
{
flag=0;
for(i=0;i<26;i++)
{
if(mark[i]&&head[i]!=tail[i])
a[flag++]=i;
}
if(flag==0)
printf("Ordering is possible.\n");
else if(flag>2)
printf("The door cannot be opened.\n");
else if(flag==2)
{
if(head[a[0]]-tail[a[0]]==1&&tail[a[1]]-head[a[1]]==1||tail[a[0]]-head[a[0]]==1&&head[a[1]]-tail[a[1]]==1)
printf("Ordering is possible.\n");
else
printf("The door cannot be opened.\n");
}
}
}
return 0;
}