【解题报告】【HDOJ1272】【并查集】小希的迷宫

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1272

 

判断条件

1.无环

2.连通

(其实就是构造树的条件)

 

注意:要考虑树时空的情况,0 0也是树,空树。

 

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 int root[100001];
 4 int used[100001];
 5 int find(int x)
 6 {
 7     int t;
 8     if(root[x]==x)
 9         return x;
10     t=find(root[x]);
11     root[x]=t;
12     return t;
13 }
14 int notloop(int x,int y)
15 {
16     int a,b;
17     a=find(x);
18     b=find(y);
19     if(a==b) return 0;
20     else return 1;
21 }
22 int main()
23 {
24     int a,b,sum,fx,fy,i,flag;
25     //freopen("1.txt","r",stdin);
26     while(scanf("%d%d",&a,&b)!=EOF&&(a!=-1||b!=-1))
27     {
28         
29         flag=1;
30         if(a==0&&b==0) {printf("Yes\n"); continue;}//当树为空时
31         for(i=1;i<100001;i++) root[i]=i; 
32         memset(used,0,sizeof(used));
33         while(a&&b)
34         {
35             used[a]=1;
36             used[b]=1;
37             
38             if(notloop(a,b))
39             {
40                 fx=find(a);
41                 fy=find(b);
42                 root[fx]=fy;
43             }
44             else
45             {
46                 flag=0; //当出现环时
47             }
48             scanf("%d%d",&a,&b); 
49         }
50         if(!flag) {printf("No\n");continue;}
51         
52         sum=0;
53         for(i=1;i<100001;i++) 
54         {
55             if(used[i])
56             {
57                 root[i]=find(root[i]);
58                 sum++;
59             }
60         }
61         for(i=1;i<100001;i++)
62             if(used[i])
63                 if(root[i]!=i)  
64                     sum--;
65                 if(sum==1) printf("Yes\n");//当连通时
66                 else printf("No\n");//当不连通的
67     }
68     return 0;
69 }

 

 

posted on 2012-07-21 16:49  coding封神  阅读(130)  评论(0编辑  收藏  举报

导航