[HDU3038]How Many Answers Are Wrong(并查集)

传送门

 

某题类似,只不过奇偶换成了和。

 

——代码

 1 #include <cstdio>
 2 #include <iostream>
 3 #define N 1000001
 4 
 5 int n, m, ans;
 6 int f[N], d[N];
 7 
 8 inline int read()
 9 {
10     int x = 0, f = 1;
11     char ch = getchar();
12     for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1;
13     for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
14     return x * f;
15 }
16 
17 inline int find(int x)
18 {
19     if(x ^ f[x])
20     {
21         int fx = f[x];
22         f[x] = find(f[x]);
23         d[x] += d[fx];
24     }
25     return f[x];
26 }
27 
28 int main()
29 {
30     int i, x, y, z, fx, fy;
31     while(~scanf("%d %d", &n, &m))
32     {
33         ans = 0;
34         for(i = 0; i <= n; i++) f[i] = i, d[i] = 0;
35         for(i = 1; i <= m; i++)
36         {
37             x = read() - 1;
38             y = read();
39             z = read();
40             fx = find(x);
41             fy = find(y);
42             if(fx == fy)
43             {
44                 if((d[x] - d[y]) ^ z) ans++;
45             }
46             else
47             {
48                 d[fx] = d[y] - d[x] + z;
49                 f[fx] = fy;
50             }
51         }
52         printf("%d\n", ans);
53     }
54     return 0;
55 }
View Code

 

posted @ 2017-06-15 10:41  zht467  阅读(91)  评论(0编辑  收藏  举报