Play on Words
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 3814 Accepted Submission(s): 1227
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.".
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<utility>
#include<vector>
using namespace std;
vector<pair<int,int> >edge;
int set[30];
int used[30];
int in[30],out[30];
void init()
{
for(int i=0; i<=26; i++)
{
set[i]=i;
}
memset(used,0,sizeof(used));
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
edge.clear();
}
int find(int a)
{
int temp,root=a,b=a;
while(set[root]!=root)
{
root=set[root];
}
while(b!=root)
{
temp=set[b];
set[b]=root;
b=temp;
}
return root;
}
bool merge(int x,int y)
{
x=find(x);
y=find(y);
if(x==y)
{
return false;
}
set[x]=y;
return true;
}
bool euler()
{
int start=0,end=0,tempst=-1;
for(int i=0; i<edge.size(); i++)
{
merge(find(edge[i].first),find(edge[i].second));
}
for(int i=0; i<=26; i++)
{
if(used[i])
{
if(tempst==-1)
{
tempst=i;//定起點
}
if(find(i)!=find(tempst))
{
return false;//是否構成歐拉回路
}
if(fabs(in[i]-out[i])>=2)
{
return false;//出度與入度是否相等
}
if(in[i]-out[i]==1)
{
end++;
if(end>1)//終點
{
return false;
}
}
if(out[i]-in[i]==1)
{
start++;
if(start>1)//起點
{
return false;
}
}
}
}
return true;
}
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
init();
char a[1100];
for(int i=0; i<n; i++)
{
int x,y;
scanf("%s",a);
x=a[0]-'a';
y=a[strlen(a)-1]-'a';
used[x]=used[y]=1;
in[y]++;
out[x]++;
edge.push_back(make_pair(y,x));
}
if(!euler())
{
printf("The door cannot be opened.\n");
}
else
{
printf("Ordering is possible.\n");
}
}
return 0;
}