1 #include <stdio.h> 2 #include <string.h> 3 4 int f[1001], g[1001]; 5 6 int find(int x) //并查集的查找,找到共同的父亲 7 { 8 if (f[x] != x) 9 f[x] = find(f[x]); 10 return f[x]; 11 } 12 13 int main() 14 { 15 int a, b, tt = 1; 16 while (scanf("%d%d", &a, &b) != EOF) 17 { 18 int i, flag = 0, t = 0; 19 if (a<0 && b<0) 20 break; 21 for (i = 0; i <= 1000; i++) 22 f[i] = i; 23 24 //合并 25 if (find(a) == find(b)) 26 flag = 1; 27 else 28 f[find(b)] = find(a); 29 30 while (scanf("%d%d", &a, &b)) 31 { 32 if (a == 0 && b == 0) 33 break; 34 int aa, bb; 35 aa = find(a); 36 bb = find(b); 37 //合并 38 if (aa == bb || bb != b) //成环就不是树,后面的是检查是否有两个父节点 39 flag = 1; 40 else 41 f[bb] = aa; 42 } 43 44 memset(g, 0, sizeof(g)); 45 for (i = 1; i <= 1000; i++) //保证只有一个根,不然就是森林了 46 if (f[i] != i) 47 g[find(i)]++; 48 for (i = 1; i <= 1000; i++) //检查是否只有一个头结点就是了 49 if (g[i]>0) 50 t++; 51 if (t>1) 52 flag = 1; 53 if (flag == 1) 54 printf("Case %d is not a tree. ", tt++); 55 else 56 printf("Case %d is a tree. ", tt++); 57 } 58 return 0; 59 }