数据: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 okSample Output
The door cannot be opened. Ordering is possible. The door cannot be opened.
题意:输入一些英文单词,根据该单词的首尾字母,判断所有单词能不能连成一串,。同样如果有多个重复的单词时,也必须满足这样的条件才能通过,否则都是不可能的情况
分析:其实每个单词有用的成分只有首尾字母,把单词的首尾字母提取出来,抽象成两个顶点,建立两个顶点之间的联系,放入一个集合(这就用到了并查集),然后题就转化成了所有边能不能形成一条连通图,用欧拉回路判断该图是不是就好了
欧拉路:图连通,存在一个顶点的入度比出度大1,一个顶点的出度比入度大1,其他顶点入度与出度相等
注:欧拉路分为欧拉回路和欧拉通路;
欧拉通路:满足从一点出发经过每一条边且只经过一次,能把所有的边都经过的路
欧拉回路:欧拉通路并且最后回到原点的路;
一、无向图
每个顶点的度数都是偶数,则存在欧拉回路。二、有向图(所有边都是单向的)
每个节顶点的入度都等于出度,则存在欧拉回路。
code:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const int N=1010;
int father[30];
int in[30],out[30];
char str[N];
int book[30];
int find(int x)
{
if(x==father[x])
return x;
else
{
int temp=find(father[x]);
father[x]=temp;
return temp;
}
}
void join(int a,int b)
{
int x=find(a);
int y=find(b);
if(x!=y)
father[y]=x;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
for(int i=0; i<=30; i++)
father[i]=i;
mem(book,0);
mem(in,0),mem(out,0);
int n;
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
scanf("%s",str);
int l=strlen(str);
join(str[0]-'a',str[l-1]-'a');///合并顶点
in[str[0]-'a']++;///入度+1
out[str[l-1]-'a']++;///出度+1
book[str[0]-'a']=1;
book[str[l-1]-'a']=1;
}
int ans=0,res=0;///res 记录出入度不相等的数量
int a=0,b=0;///a 出比入度大一 b入比出度大一
for(int i=0; i<=30; i++)
{
if(book[i]&&father[i]==i)
ans++;///判断是否连通
}///不连通直接输出
if(ans>1)printf("The door cannot be opened.\n");
else
{
for(int i=0; i<=30; i++)
{
if(book[i]&&in[i]!=out[i])res++;
if(book[i]&&in[i]-out[i]==1)b++;
if(book[i]&&out[i]-in[i]==1)a++;
}///存在欧拉回路
///存在欧拉路径
if(res==0)printf("Ordering is possible.\n");
else if(a==1&&b==1&&res==2)printf("Ordering is possible.\n");
else printf("The door cannot be opened.\n");
}
}
return 0;
}
emm.....温故而知新