<a target=_blank href="http://poj.org/problem?id=1386" target="_blank">
</a>
题目链接
解题思路:把每个单词当成是一条有向边。把首字母和尾字母当成是节点,如果该字母是一个单词的首字母,该字母的入度就加一,如果是尾字母,该字母的出度就加一。然后判断是否形成欧拉回路即可。
欧拉路径判断条件:首先该图必须是连通图。对于无向图,所有顶点的读都为偶数,对于有向图,要么所有顶点的入度等于出度,要么只有两个顶点入度和出度不同,一个入度比出度大一,一个出度比入度大一。
连通图的判断方法:对每条边的两个顶点进行合并,如果最终能合并到一个集合,说明该图为连通图。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
using namespace std;
int ru[27], ch[26], num, root[26];
char s1[1002];
int findroot(int a)
{
if(a != root[a])
root[a] = findroot(root[a]);
return root[a];
}
void merge(int a, int b)
{
root[a] = root[b] = min(findroot(a), findroot(b));
}
bool check() //返回是否是连通图
{
int i;
bool ok = true;
for(i = 0; i < 26; i++) //检验是否在一个集合
{
if(ru[i] > 0 && findroot(i) == i)
{
if(ok) ok = false;
else return false;
}
}
return true;
}
int main()
{
int n, i ,j, numue, sum, head, tail;
scanf("%d", &n);
bool ok;
for(i = 0; i < n; i++)
{
scanf("%d", &num);
sum = 0;
numue = 0;
for(j = 0; j < 26; j++)
{
ru[j] = 0;
ch[j] = 0;
root[j] = j;
}
for(j = 0; j < num; j++)
{
scanf(" %s", s1);
tail = s1[strlen(s1)-1] - 97;
head = s1[0] - 97;
ru[tail]++;
ch[head]++;
merge(findroot(head), findroot(tail));
}
ok = true;
for(j = 0; j < 26; j++)
{
if(ru[j]!=ch[j])
{
if(abs(ch[j]-ru[j]) == 1)
sum += ch[j]-ru[j]; //sum表示所有节点入度和出度之差
else ok = false; //入度和出度差不为1
numue++;<span style="white-space:pre"> </span>//numue表示入度和出度不相等的个数
}
}
if(check() && ok &&
((numue == 0) || (numue == 2 && sum == 0)) //欧拉回路的判断条件
)
{
printf("Ordering is possible.\n");
}
else
printf("The door cannot be opened.\n");
}
return 0;
}