【并查集】hdu 1325 Is It A Tree?

注意以下4种情况:

0 0              可以
1 1 0 0       不可以
1 2 1 2 0 0 不可以
1 2 2 1 0 0 不可以

 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 const int MAXN=100000+5;
 5 
 6 int a,b,mycase=1;
 7 bool ok=true;
 8 int father[MAXN];//记录父节点
 9 int temp[MAXN];//判断是否为森林(用并查集)
10 bool vis[MAXN];
11 
12 void init(){
13     ok=true;
14     for(int i=0;i<MAXN;i++){
15         father[i]=i;
16         temp[i]=i;
17         vis[i]=0;
18     }
19 }
20 int main()
21 {
22     init();
23     while( scanf("%d %d",&a,&b)!=EOF && a>-1 && b>-1 ){
24 
25         if(ok==false && a && b)continue;
26 
27         if(a==0 && b==0){
28             int root=0;//根节点的个数
29             for(int i=0;i<MAXN;i++){
30                 if(vis[i] && temp[i]==i)
31                     root++;
32             }
33             if(root>1)ok=false;
34 
35             if(ok)printf("Case %d is a tree.\n",mycase++ );
36             else printf("Case %d is not a tree.\n",mycase++ );
37             
38             init();
39             continue;
40         }
41 
42         if(a!=b && father[b]==b && father[a]!=b){
43             father[b]=a;
44             temp[b]=a;
45             vis[a]=vis[b]=true;
46         }
47         else ok=false;
48 
49     }
50 
51     return 0;
52 }

 

posted @ 2015-04-19 11:00  纸牌  阅读(152)  评论(0编辑  收藏  举报