Catenyms
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9914 | Accepted: 2588 |
Description
dog.gopher
gopher.rat
rat.tiger
aloha.aloha
arachnid.dog
Input
Output
Sample Input
2
6
aloha
arachnid
dog
gopher
rat
tiger
3
oak
maple
elm
Sample Output
aloha.arachnid.dog.gopher.rat.tiger
***
Source
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; struct EDGE { char s[25]; int x, y; }e[1005]; bool has[30], vis[1005]; int in[30], out[30], fa[30], ans[1005]; int n, st, len; bool cmp(EDGE a, EDGE b) { return strcmp(a.s, b.s) < 0; } int abs(int x) { return x > 0 ? x : -x; } int change(char ch) { return int(ch - 'a' + 1); } void UF_set() { for(int i = 0; i < 200; i++) fa[i] = i; } int Find(int x) { return fa[x] == x ? x : fa[x] = Find(fa[x]); } void Union(int a, int b) { int r1 = Find(a); int r2 = Find(b); if(r1 != r2) fa[r1] = r2; } bool exist() { int t = -1; for(int i = 1; i <= 26; i++) { if(has[i]) { if(t == -1) t = Find(i); if(t != Find(i)) return false; } } int sum = 0, tmp = 100; for(int i = 1; i <= 26; i++) { if(has[i]) { tmp = min(tmp, i); if(in[i] != out[i]) { if(abs(in[i] - out[i]) > 1) return false; if(out[i] > in[i]) st = i; sum ++; } } } if(sum > 2) return false; if(sum == 0) st = tmp; return true; } void DFS(int now) { for(int i = 0; i < n; i++) { if(!vis[i] && e[i].x == now) { vis[i] = true; DFS(e[i].y); ans[len++] = i; } } } int main() { int T; scanf("%d", &T); while(T--) { st = 0; UF_set(); memset(has, false, sizeof(has)); memset(in, 0, sizeof(in)); memset(out, 0, sizeof(out)); scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%s", e[i].s); e[i].x = change(e[i].s[0]); e[i].y = change(e[i].s[(int)strlen(e[i].s) - 1]); has[e[i].x] = true; has[e[i].y] = true; in[e[i].y] ++; out[e[i].x] ++; Union(e[i].x, e[i].y); } sort(e, e + n, cmp); if(exist()) { len = 0; memset(vis, false, sizeof(vis)); DFS(st); for(int i = len - 1; i > 0; i--) printf("%s.", e[ans[i]].s); printf("%s\n", e[ans[0]].s); } else printf("***\n"); } }
原文地址:http://blog.csdn.net/tc_to_top/article/details/43347537