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.
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
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.
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
The door cannot be opened. Ordering is possible. The door cannot be opened.
题解:不用管每个单词中间的字母,只需要 首尾 字母,其他部分看 注释 就能理解;
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int d[27], start; //d[]用于记录出度和入度;
bool f[27], a[27][27]; //f[]和a[][]用于判断连通性,一个是把经过的点做下标记,另一个是存放两个点是否连通;
void dfs(int x) //判断连通性;
{
f[x]=false;
for(int i=0; i<26; i++)
if(a[x][i] && f[i]) dfs(i);
}
bool check()
{
int x=0,y=0,z=0;
for(int i=0; i<26; i++)
{
if(d[i]==1)
{
start=i;//起点;
x++;
}
if(d[i]==-1) y++;//终点;
if(d[i]==0) z++;
}
if(z!=26)
{
if((x+y+z)!=26) return false;
if(!(x==1 && y==1)) return false;
}
dfs(start);
for(int i=0; i<26; i++)
if(f[i]) return false;
return true;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
memset(d,0,sizeof(d));
memset(f,false,sizeof(d));
memset(a,false,sizeof(a));
for(int i=0; i<n; i++)
{
char s[1500];
scanf("%s",s);
int len=strlen(s);
int x=s[0]-'a';
int y=s[len-1]-'a';
d[x]++;
d[y]--;
start=x;
f[x]=true;
f[y]=true;
a[x][y]=true;
a[y][x]=true;
}
if(check()) cout<<"Ordering is possible."<<endl;
else cout<<"The door cannot be opened."<<endl;
}
return 0;
}