HDU 1272 小希的迷宫(并查集)

题目链接

这个题交了18次。。。做欧拉图的时候想起这个题,我在判是否是具有相同的根的时候判错了。。。这个题的注意方向就 连通(具有相同的根),并且不能存在合并的时候具有相同根的,这样意味着,就两条路了,然后再注意0 0的时候特殊数据(看DISCUSS)。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #define N 100010
 5 int p[N+1],z,o[N+1];
 6 int find(int x)
 7 {
 8     int r = x,t;
 9     while(p[x]!=x)
10         x = p[x];
11     while(r != x)
12     {
13         t = p[r];
14         p[r] = x;
15         r = t;
16     }
17     return x;
18 }
19 void merge(int x,int y)
20 {
21     int x1,y1;
22     y1 = find(y);
23     x1 = find(x);
24     if(x1 != y1)
25         p[x1] = y1;
26     else if(x1 == y1&&x != y)
27     {
28         z = 1;
29     }
30 }
31 int main()
32 {
33     int n,m,i,j,max;
34     while(scanf("%d%d",&n,&m)!=EOF)
35     {
36         z = 0;max = 0;
37         memset(o,0,sizeof(o));
38         if(n==-1&&m==-1)break;
39         if(n == 0&&m == 0)
40         printf("Yes\n");
41         else
42         {
43             o[n] = o[m] = 1;
44             if(max < n)
45             max = n;
46             if(max < m)
47             max = m;
48         for(i = 0;i <= N-1;i ++)
49         {
50             p[i] = i;
51         }
52          merge(n,m);
53         for(;;)
54         {
55             scanf("%d%d",&i,&j);
56             if(i == 0 &&j == 0)
57             break;
58             merge(i,j);
59             o[i] = o[j] = 1;
60             if(max < i)
61             max = i;
62             if(max < j)
63             max = j;
64         }
65         for(i = 1;i <= max;i ++)
66         {
67             if(find(i) != find(n)&& o[i] == 1)
68             {
69                 z = 1;
70                 break;
71             }
72         }
73         if(z)
74         printf("No\n");
75         else
76         printf("Yes\n");
77         }
78     }
79     return 0;
80 }
posted @ 2012-06-23 11:04  Naix_x  阅读(194)  评论(0编辑  收藏  举报