POJ1386Play on Words(欧拉回路)
题目地址。
分析:
1.图必须是连通的。
2.欧拉道路或者是欧拉回路都是可以的。
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXN 27 int hash[MAXN], in[MAXN], out[MAXN], p[MAXN]; void Init(){ int i; for(i=0; i<MAXN; i++){ hash[i] = in[i] = out[i] = 0; p[i] = i; } } int find(int x){return p[x] == x ? x : (p[x] = find(p[x]));} void Union(int u, int v){ u = find(u); v = find(v); if(u != v){ p[u] = v; } } int main(){ int t, n, i, len, ans; char s[1012]; scanf("%d", &t); while(t--){ scanf("%d", &n); Init(n); for(i=0; i<n; i++){ scanf("%s", s); len = strlen(s); int a = s[0] - 'a'; int b = s[len-1] - 'a'; hash[a] = 1; hash[b] = 1; out[a]++; //不要写反了 in[b]++; Union(a, b); } ans = 0; for(i=0; i<MAXN; i++){ //检查是否是连通图(又一个方法) if(hash[i] && i == find(i)) ans++; } if(ans > 1) {printf("The door cannot be opened.\n"); continue;} int a=0, b=0; for(i=0; i<MAXN; i++){ if(hash[i] && in[i]-out[i] == 1) a++; else if(hash[i] && out[i]-in[i] == 1) b++; else if(hash[i] && out[i] != in[i]) break; } if(i<MAXN) printf("The door cannot be opened.\n"); else if((a == 0 && b == 0) || (a == 1 && b == 1)) printf("Ordering is possible.\n"); else printf("The door cannot be opened.\n"); } return 0; }