The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes Each edge description will consist of a pair of integers; the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero and less than 10000.
For each test case display the line "Case k is a tree." or the line "Case k is not a tree.", where k corresponds to the test case number (they are sequentially numbered starting with 1).
6 8 5 3 5 2 6 4 5 6 0 0 8 1 7 3 6 2 8 9 7 5 7 4 7 8 7 6 0 0 3 8 6 8 6 4 5 3 5 6 5 2 0 0 -1 -1
Case 1 is a tree. Case 2 is a tree. Case 3 is not a tree.
#include<stdbool.h> #include <stdio.h> const int maxnode = 10000; int father[maxnode]; int indegree[maxnode]; bool vis[maxnode]; int height[maxnode]; void initial(int m){ for(int i = 0; i < m; i++){ father[i] = i; indegree[i] = 0; height[i] = 0; vis[i] = false; } } int Find(int x){ if (x != father[x]) father[x] = Find(father[x]); return father[x]; } void Union(int a, int b){ a = Find(a); b = Find(b); if(a != b){ if (height[a] < height[b]) father[a] = b; else if (height[a] > height[b]) father[b] = a; else{ father[b] = a; height[a]++; } } } bool istree(){ int com=0; int root=0; bool flag = true; for (int i = 0; i < maxnode; i++){ if (!vis[i]) continue; if(i == father[i]) com++; if(indegree[i] == 0) root++; else if (indegree[i] > 1) flag = false; if (com != 1 || root != 1) flag = false; if (com == 0 && root == 0) flag = true; } return flag; } int main() { int a, b, k = 0; initial(maxnode); while (scanf("%d %d", &a, &b) != EOF) { // 注意 while 处理多个 case // 64 位输出请用 printf("%lld") to if(a == -1 && b == -1) break; if(a == 0 && b == 0){ k+=1; if (istree()) printf("Case %d is a tree.\n", k); else printf("Case %d is not a tree.\n", k); initial(maxnode); } else{ Union(a, b); indegree[b]++; vis[a] = true; vis[b] = true; } } return 0; }
#include<stdio.h> void chushihua(int a[]){ int i; for(i=0;i<10000;i++) a[i]=0; } int main(){ int bing[10000]={0}; int a,b,sum=0,i,j=1,tag=1,tag2=0,tag3=0; while(1){ scanf("%d %d",&a,&b); if(a==-1&&b==-1){ break; } if(a==0&&b==0){ if(tag2==0){ printf("Case %d is a tree.\n",j); j++; sum=0; tag2=0; tag3=0; tag=1; chushihua(bing); continue; } for(i=0;i<10000;i++){ if(bing[i]==-1)sum++; if(sum>1&&tag==1){ printf("Case %d is not a tree.\n",j); break; } } if(sum==0&&tag==1) printf("Case %d is not a tree.\n",j); if(sum==1&&tag==1) printf("Case %d is a tree.\n",j); j++; sum=0; tag2=0; tag3=0; tag=1; chushihua(bing); } else{ tag2=1; if(bing[b]==0||bing[b]==-1) { bing[b]=a; if(b==a&&tag3==0){ printf("Case %d is not a tree.\n",j); tag3=1; tag=0; } } else { if(tag3==0) { printf("Case %d is not a tree.\n",j); tag3=1; tag=0; } } if(bing[a]==0||bing[a]==-1) bing[a]=-1; } } }