水题,判断是否是一棵树,如果一个结点有多个父亲or图中有环就不是。

 1 #include <stdio.h>
 2 #include <string.h>
 3 int fa[1005],v[1005];
 4 int Find(int n)
 5 {
 6     if(fa[n] == -1)
 7         return n;
 8     fa[n] = Find(fa[n]);
 9         return fa[n];
10 }
11 int main()
12 {
13     int ca=1,a,b,i,j,f;
14     bool ok;
15     while(scanf("%d%d",&a,&b))
16     {
17         if(a==-1 && b==-1) break;
18         if(!a && !b)
19         {
20             printf("Case %d is a tree.\n",ca++);
21             continue;
22         }
23         ok = 1; i = 0;
24         memset(fa,-1,sizeof fa);
25         fa[b] = a; v[i] = b;
26         if(a == b)
27         {
28             ok = 0;
29             printf("Case %d is not a tree.\n",ca++);
30         }
31         while(scanf("%d%d",&a,&v[++i]),a&&v[i])
32         if(ok)
33         {
34             if(fa[v[i]] != -1 || Find(a)==v[i])
35             {
36                 ok = 0;
37                 printf("Case %d is not a tree.\n",ca++);
38             }
39             fa[v[i]] = a;
40         }
41         if(ok)
42         {
43             f = Find(v[0]);
44             for(j = 1; j <= i&&Find(v[j]) == f; j++);
45             if(j < i)
46                 printf("Case %d is not a tree.\n",ca++);
47             else printf("Case %d is a tree.\n",ca++);
48         }
49     }
50     return 0;
51 }