hdu 1325
此题与hdu 1272类似。
但此题需注意以下几点:
1.当输入两个负数时退出,不是当输出-1 -1 (这点不注意将一直超时T_T)
2.对树的判断除了不成环,还需注意一个问题:此图为有向图:当b的根不是他自己或a时,b 这个节点有两个跟,同样不成数。
if(f1 == f2 || f2 != b) flag = 1;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<string.h> 3 #define N 110000 4 int f[N],vis[N]; 5 int flag = 0; 6 int Maxx = 0; 7 int num = 1; 8 int Max(int a,int b) 9 { 10 return a>b?a:b; 11 } 12 void star1() 13 { 14 int i; 15 for(i = 0;i < N;i ++) 16 { 17 f[i] = i; 18 } 19 memset(vis,0,sizeof(vis)); 20 flag = 0; 21 Maxx = 0; 22 } 23 int root(int i) 24 { 25 if(f[i] == i) 26 return i; 27 else 28 return root(f[i]); 29 } 30 void U(int a,int b) 31 { 32 int f1,f2; 33 f1 = root(a); 34 f2 = root(b); 35 if(f1!= f2) 36 f[f2] = f1; 37 if(f1 == f2 || f2 != b) 38 flag = 1; 39 } 40 int main() 41 { 42 int n,m,i,j,k; 43 int a,b; 44 star1(); 45 while(~scanf("%d %d",&a,&b)&& a>=0 && b>=0) 46 { 47 if(a==0 && b ==0) 48 { 49 k = 0; 50 for(i = 1;i <= Maxx;i ++) 51 { 52 if(vis[i] && f[i] == i) 53 k ++; 54 } 55 if(k <= 1 && flag == 0) 56 { 57 printf("Case %d is a tree. ",num++); 58 } 59 else 60 { 61 printf("Case %d is not a tree. ",num++); 62 } 63 star1(); 64 } 65 else 66 { 67 Maxx = Max(Maxx,Max(a,b)); 68 vis[a] = vis[b] = 1; 69 U(a,b); 70 } 71 } 72 return 0; 73 }