http://acm.hdu.edu.cn/showproblem.php?pid=1116
有向图寻找欧拉路径:
1.连通图
2.所有的点出度入度相等或有且只有一个点出度比入度大1(出发点),一个点入度比出度大1(终止点)。
有向图寻找欧拉回路:
1.连通图
2.所有的点出度等于入度。
本题是词语接龙的模型,等价于在有向图中判断是否存在欧拉路径。使用并查集判断图是否连通。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
char str[1010];
int father[30],vis[30],n,in[30],out[30];
void init(){
for(int i=0; i<30; i++){
father[i] = i;
vis[i] = 0;
out[i] = 0;
in[i] = 0;
}
}
int find(int x){
if(x == father[x]) return x;
return find(father[x]);
}
int main(){
// freopen("in.txt", "r", stdin);
int cas;
scanf("%d",&cas);
while(cas--){
init();
scanf("%d",&n);
for(int i=0; i<n; i++){
scanf("%s",str);
int x = str[0] - 'a',y = str[strlen(str) - 1] - 'a';
father[x] = father[y] = find(x);
vis[x] = vis[y] = 1;
out[x]++,in[y]++;
}
int r = 0;
for(int i=0; i<30; i++)
if(vis[i] && i == father[i]) r++;
if(r > 1){cout << "The door cannot be opened." << endl; continue;}
int x = 0, y = 0, z = 0, flag = 1;
for(int i=0; i<30; i++){
if(vis[i] && in[i] != out[i]){
if(in[i] - out[i] == 1) x++;
else if(out[i] - in[i] == 1) y++;
else z++;
}
}
if(z) cout << "The door cannot be opened." << endl;
else if((!x && !y) || (x == 1 && y == 1)) cout << "Ordering is possible." << endl;
else cout << "The door cannot be opened." << endl;
}
return 0;
}