题目:http://poj.org/problem?id=2513
参考博客:http://blog.csdn.net/lyy289065406/article/details/6647445
http://www.cnblogs.com/LK1994/p/3263462.html
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cstdlib> 5 #include<stack> 6 #include<queue> 7 #include<iomanip> 8 #include<cmath> 9 #include<map> 10 #include<vector> 11 #include<algorithm> 12 #define N 500010 13 using namespace std; 14 15 int degree[N],bin[N],id = 1; 16 17 struct tree 18 { 19 int flag,id; 20 struct tree* next[26]; 21 }*root; 22 struct tree* creat() 23 { 24 struct tree *p=(struct tree*)malloc(sizeof(struct tree)); 25 p->flag =0; 26 for(int i = 0; i < 26; i++) 27 p->next[i] = NULL; 28 return p; 29 } 30 31 int find(int x) 32 { 33 if(bin[x] != x) 34 bin[x] = find(bin[x]); 35 return bin[x]; 36 } 37 38 int hash(char s[]) 39 { 40 struct tree *p = root; 41 for(int i = 0; s[i]; i++) 42 { 43 if(p->next[s[i]-'a'] == NULL) 44 p->next[s[i]-'a'] = creat(); 45 p = p->next[s[i]-'a']; 46 } 47 if(p->flag != 1) 48 { 49 p->flag = 1; 50 p->id = id++; 51 } 52 return p->id; 53 } 54 55 int check() 56 { 57 int sum = 0; 58 int x = find(1); 59 for(int i = 2; i < id; i++) 60 if(find(i) != x) 61 return 0; 62 for(int i = 1; i < id; i++) 63 { 64 if(degree[i]%2) 65 sum++; 66 } 67 if(sum == 0 || sum == 2) 68 return 1; 69 return 0; 70 } 71 72 int main() 73 { 74 int u,v,x,y; 75 char s1[15],s2[15]; 76 memset(degree,0,sizeof(degree)); 77 for(int i=1; i<=500000; i++) 78 bin[i]=i; 79 root=creat(); 80 while(scanf("%s %s",s1,s2)!=EOF) 81 { 82 u =hash(s1); v =hash(s2); 83 degree[u]++; degree[v]++; 84 x=find(u); 85 y=find(v); 86 if(x!=y) 87 bin[x]=y; 88 } 89 if(check()) printf("Possible "); 90 else printf("Impossible "); 91 return 0; 92 }