Play on Words Description 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. 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. Sample Input 3 Sample Output The door cannot be opened. Source Central Europe 1999 |
Time Limit: 1000MS | | Memory Limit: 10000K |
Total Submissions: 15130 | | Accepted: 4856 |
题意:
给你多个单词,问你能不能将所有单词组成这样一个序列:序列的前一个单词的尾字母与后一个单词的头字母相同.
分析:
欧拉路径存在的充要条件:
1. 有向图存在欧拉回路的充要条件
所有顶点的 入度 和 出度 的和是 偶数,且该图是连通图(并查集)。
2.有向图含有欧拉通路的充要条件
起始点s 的入度=出度-1,结束点t的出度=入度-1 或两个点的入度=出度,且该图是连通图(并查集)。
有一个坑点:
单词要用cha[] 保存 用stringG++会超时,C++可以过
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<set>
#include<vector>
#include<sstream>
#include<queue>
#define ll long long
#define PI 3.1415926535897932384626
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=200010;
int start,n;
int f[30],in[30],out[30];
void init()
{
//ans.clear();
for (int i = 1; i <= 26; i++)
f[i] = i;
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
}
int find(int x)
{
return x == f[x] ? x : f[x] = find(f[x]);
}
void merge(int x, int y)
{
int t1, t2;
t1 = find(x); t2 = find(y);
if (t1 != t2) f[t2] = t1;
else return;
}
///判断是否存在欧拉通路径
///>=0:欧拉通路的起始位置
///-2:欧拉回路
///-1:无欧拉路劲
int isEluer() //判断是否存在欧拉通路径
{
int sum=0;
for(int i=0;i<26;i++) //保证是一个连通图
{
if((in[i]||out[i])&&find(i)==i)
sum++;
if(sum>=2)
return -1;
}
int ac=0,bc=0,pos=-1;
for(int i=0;i<26;i++)
{
if(in[i]==out[i]) continue;
if(in[i]==out[i]+1)
{
ac++;
continue;
}
if(in[i]==out[i]-1)
{
pos=i;
bc++;
continue;
}
return -1;
}
if(!ac&&!bc) return -2;
if(ac==1&&bc==1) return pos;
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
init();
scanf("%d",&n);
for(int i=0;i<n;i++)
{
char word[1200]; //string G++会超时G++可以过
scanf("%s",word);
int len=strlen(word);
int x,y;
x=word[0]-'a';
y=word[len-1]-'a';
merge(x,y);
in[y]++;
out[x]++;
}
int flag=isEluer();
if(flag==-1)
printf("The door cannot be opened.\n");
else
{
printf("Ordering is possible.\n");
}
}
return 0;
}