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<bits/stdc++.h>
using namespace std;
struct pp
{
int l,r;//计算每个字母的入度和出度;
};
pp z[26];
int pa[26];
int root(int x)
{
return pa[x]==x?x:pa[x]=root(pa[x]);
}
void mer(int x,int y)
{
int rx=root(x),ry=root(y);
if(rx!=ry)
pa[rx]=ry;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n,l=0,r=0,flag=1,s=0;
cin>>n;
string c;
memset(z,0,sizeof(z));
for(int i=0;i<26;i++)
pa[i]=i;
for(int i=0;i<n;i++)
{
cin>>c;
int a=c[0]-'a',b=c[c.size()-1]-'a';
z[a].l++;
z[b].r++;
mer(a,b);
}
for(int i=0;i<26;i++)
if((z[i].l||z[i].r)&&pa[i]==i)
s++;
if(s>1)
{
cout<<"The door cannot be opened.\n";
continue;
}
for(int i=0;i<26;i++)
{
if(z[i].l==z[i].r) continue;
else if(z[i].l-z[i].r==1)l++;
else if(z[i].r-z[i].l==1)r++;
else
{
flag=0;
break;
}
if(l>1||r>1)
{
flag=0;
break;
}
}
if(l!=r)
flag=0;
if(flag)
cout<<"Ordering is possible.\n";
else
cout<<"The door cannot be opened.\n";
}
return 0;
}
9007



被折叠的 条评论
为什么被折叠?



