POJ 2492 A Bug's Life(并查集)

题目链接

居然没更新flag就交了,错了两次。。3个题,都是一个类型。

 1 #include <cstring>
 2 #include <cstdio>
 3 #include <string>
 4 #include <iostream>
 5 #include <algorithm>
 6 #include <vector>
 7 using namespace std;
 8 int o[5001];
 9 int flag[5001];
10 int find(int x)
11 {
12     if(x == o[x]) return x;
13     int t = find(o[x]);
14     flag[x] = (flag[x] + flag[o[x]])%2;
15     return o[x] = t;
16 }
17 int main()
18 {
19     int n,m,i,T,cas = 1,x,y,tx,ty,z;
20     scanf("%d",&T);
21     while(cas <= T)
22     {
23         scanf("%d%d",&n,&m);
24         for(i = 1; i <= n; i ++)
25         {
26             o[i] = i;
27             flag[i] = 0;
28         }
29         z = 1;
30         for(i = 0; i < m; i ++)
31         {
32             scanf("%d%d",&x,&y);
33             if(z)
34             {
35                 tx = find(x);
36                 ty = find(y);
37                 if(tx != ty)
38                 {
39                     o[tx] = ty;
40                     flag[tx] = (flag[y] - flag[x] + 3)%2;
41                 }
42                 else if(tx == ty)
43                 {
44                     if(flag[x] == flag[y])
45                     z = 0;
46                 }
47             }
48         }
49         printf("Scenario #%d:
",cas++);
50         if(z)
51         printf("No suspicious bugs found!
");
52         else
53         printf("Suspicious bugs found!
");
54         if(cas <= T) printf("
");
55     }
56     return 0;
57 }
原文地址:https://www.cnblogs.com/naix-x/p/3140917.html