Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 4633 | Accepted: 1676 |
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
The door cannot be opened. Ordering is possible. The door cannot be opened.
Source
#include<stdio.h>
#include<string.h>
#define MAX_SIZE 1008
#define WORD_SIZE 26
char word[MAX_SIZE];//word
int in[WORD_SIZE],out[WORD_SIZE];//indegree,outdegree
bool con[WORD_SIZE][WORD_SIZE];//connected
bool visited[WORD_SIZE];//flag
int N,cnt;
void Init(){//initial in[],out[]
int i,j;
for(cnt=i=0;i<WORD_SIZE;i++){
in[i]=out[i]=0;
visited[i]=false;
for(j=0;j<WORD_SIZE;j++)
con[i][j]=false;
}
}
void DFS(int u){//check weak connected
visited[u]=true;
cnt--;
for(int v=0;v<WORD_SIZE;v++)
if(!visited[v]&&con[u][v])
DFS(v);
}
int main(){
int i,cas,len,first,cnt1,cnt2,cnt3;
scanf("%d",&cas);
while(cas--){
scanf("%d",&N);
Init();
cnt1=cnt2=cnt3=0;
for(i=0;i<N;i++){//get inputs
scanf("%s",word);
len=strlen(word);
in[word[len-1]-'a']++;
out[word[0]-'a']++;
con[word[len-1]-'a'][word[0]-'a']=true;
con[word[0]-'a'][word[len-1]-'a']=true;
}
for(first=-1,i=0;i<WORD_SIZE;i++)
if(in[i]||out[i]){
if(first<0)first=i;//get the first
cnt++;//record num of node
if(in[i]-out[i]==1)//find in[]=out[]+1
cnt1++;
if(out[i]-in[i]==1)//find out[]=in[]+1
cnt2++;
if(out[i]==in[i])//find out[]=in[]
cnt3++;
}
len=cnt;
DFS(first);
if(cnt!=0)puts("The door cannot be opened.");
else if(cnt1==1&&cnt2==1&&len==cnt3+2||len==cnt3)
puts("Ordering is possible.");
else puts("The door cannot be opened.");
}
}