Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 8571 | Accepted: 2997 |
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. 题意:给出n个单词,问所有的单词能否首尾相连(能相连的单词的首和尾必须是相同的); 思路:一道判断有向图欧拉路的题目;
可以将每个单词的首和尾看作节点,判断图的连通性可以用并查集,每输入一个单词将其首和尾加入集合中,最后任取一个节点判断其他所有节点和该节点是否有共同的祖先,若是,则是连通的,否则不连通;
在连通性的前提下,若所有节点的入读等于出度 或者 一个节点的入度比出度大1 一个节点的入度比出度小1,说明有欧拉路,否则没有欧拉路;
因为手误,贡献一次WA;
#include<stdio.h>
#include<string.h> int set[],indegree[],outdegree[],vis[];
int count; void init()
{
for(int i = ; i < ; i++)
set[i] = i;
} int find(int x)
{
if(set[x] != x)
set[x] = find(set[x]);
return set[x];
} int check()
{
int x,i;
int flag = ;
for(i = ; i < ; i++)
{
if(vis[i])
{
if(flag == )
{
x = find(i);
flag = ;
}
else
{
if(find(i) != x)
break;
}
}
}
if(i < )
return ;//图是不连通的,直接返回; int c1 = , c2 = , c3 = ;
for(int i = ; i < ; i++)
{
if(vis[i])
{
if(indegree[i] == outdegree[i])
c1++;
else if(indegree[i]-outdegree[i] == )
c2++;
else if(outdegree[i]-indegree[i] == )
c3++;
}
}
if((c2 == && c3 == && c1 == count-) ||(c1 == count))
return ;
else return ;
} int main()
{
int test,n;
char s[];
scanf("%d",&test);
while(test--)
{
memset(indegree,,sizeof(indegree));
memset(outdegree,,sizeof(outdegree));
memset(vis,,sizeof(vis));
init();
count = ; scanf("%d",&n);
for(int i = ; i <= n; i++)
{
scanf("%s",s);
int len = strlen(s);
int u = s[]-'a';
if(!vis[u])
{
vis[u] = ;
count++;
}
int v = s[len-]-'a';
if(!vis[v])
{
vis[v] = ;
count++;
} indegree[u]++;
outdegree[v]++;
int tu = find(u);
int tv = find(v);
if(tu != tv)
set[tu] = tv;
} if(check())
printf("Ordering is possible.\n");
else printf("The door cannot be opened.\n");
}
return ;
}
欧拉路:图G,若存在一条路,经过G中每条边有且仅有一次,称这条路为欧拉路,如果存在一条回路经过G每条边有且仅有一次,
称这条回路为欧拉回路。具有欧拉回路的图成为欧拉图。
判断欧拉路是否存在的方法
有向图:图连通,有一个顶点出度大入度1,有一个顶点入度大出度1,其余都是出度=入度。
无向图:图连通,只有两个顶点是奇数度,其余都是偶数度的。
判断欧拉回路是否存在的方法
有向图:图连通,所有的顶点出度=入度。
无向图:图连通,所有顶点都是偶数度。
其中判断图的连通性用并查集。