hdu 3038 并查集

题目:给出一些询问,[l,r]的和为s,问有多少个是错的

 1 //并查集 ,,sum[a]表示a与父亲这条路径上的和
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <algorithm>
 6 
 7 using namespace std;
 8 
 9 const int maxn = 2e5 + 5;
10 int fa[maxn], sum[maxn];
11 int n, m, l, r, s;
12 int findFa(int x){
13     if (x != fa[x]){
14         int t = fa[x];
15         fa[x] = findFa(fa[x]);
16         sum[x] += sum[t];
17     }
18     return fa[x];
19 }
20 int main(){
21     while (~scanf("%d%d", &n, &m)){
22         for (int i = 0; i <= n; ++i){
23             fa[i] = i;
24             sum[i] = 0;
25         }
26         int ans = 0;
27         while (m--){
28             scanf("%d%d%d", &l, &r, &s);
29             l --;
30             int pa = findFa(l), pb = findFa(r);
31             if (pa == pb){
32                 if (sum[r] - sum[l] != s) ans++;
33             }
34             else {
35                 fa[pb] = pa;
36                 sum[pb] = sum[l] - sum[r] + s;
37             }
38         }
39         printf("%d\n", ans);
40     }
41     return 0;
42 }

 

posted @ 2013-11-10 13:57  Missa  阅读(462)  评论(0编辑  收藏  举报