HDU-1116-Play on Words

来源:互联网 发布:狂发短信软件 编辑:程序博客网 时间:2024/06/05 20:48

Play on Words

Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3818 Accepted Submission(s): 1229


Problem 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.

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
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
32acmibm3acmmalformmouse2okok


Sample Output
The door cannot be opened.Ordering is possible.The door cannot be opened.



题意:给你n个写着单词的盘子,判断能否按顺序摆放盘子,使每个盘子的首尾字母相同(除了第一个和最后一个盘子)。

题目链接:Play on Words

解题思路:

就是我们小时候玩的“一笔画”问题,不过这有个专业的名词--欧拉路径。

定理1:存在欧拉路径的条件:图是连通的,且存在0个或2个奇点。如果存在2个奇点,则欧拉路一定是从一个奇点出发,以另一个奇点结束。
定理2:存在欧拉回路的条件:图是连通的,且不存在奇点。(网上都解释得挺清楚的)


首先将每个字母数字化,方便处理。

记录每个字母以单词的第一个和最后一个出现的次数,为了判断它的奇点个数。

把出入度不同的顶点的字母单独取出来,只有起点和终点的出入度不同,而且差的绝对值为1.

还要用一个vis数组,来标记这个字母是否出现过,要保证所有出现的字母都是相连的,图才连通,程序上的表达就是根为本身的点只有一个!

最后还是并查集的使用----基本套模板了,第一次发现写程序可以这么死~


代码:





0 0
原创粉丝点击