poj1182(并查集)

把两个节点的关系转换为对根节点的关系的比较

View Code
 1 #include <stdio.h>
 2 int father[50001] ,r[50001];
 3 void init(int n)
 4 {
 5     int i;
 6     for(i = 1 ; i <= n ; i++)
 7     {
 8         father[i] = i;
 9         r[i] = 0;
10     }
11 }
12 int find(int x)
13 {
14     if(x == father[x])
15     return father[x];
16     else
17     {
18          int pre = father[x];
19         father[x] = find(father[x]);
20         r[x] = (r[x]+r[pre])%3;
21     }
22     return father[x];
23 }
24 void union1(int x, int y,int d)
25 {
26     father[x] = y;
27     r[x] = d%3;
28 }
29 int main()
30 {
31     int k,d, x, y, i, j,n,num = 0;
32     scanf("%d%d", &n,  &k);
33     init(n);
34     while(k--)
35     {
36         scanf("%d%d%d", &d,&x, &y);
37         if(x>n||y>n||(d == 2&&x == y))
38         num++;
39         else
40         {
41             int pa = find(x);
42             int pb = find(y);
43             if(pa == pb)
44             {
45                 if(d ==1)
46                 {
47                     if(r[x] != r[y])
48                     num++;
49                 }
50                 else
51                 {
52                     if(r[x]!=(r[y]+1)%3)
53                      num++;
54                 }
55             }
56             else
57             union1(pa,pb,r[y]-r[x]+d+2);
58         }
59     }
60     printf("%d\n",num);
61     return 0;
62 }

 

posted @ 2012-07-05 20:51  _雨  阅读(196)  评论(0编辑  收藏  举报