码迷,mamicode.com
首页 > 其他好文 > 详细

【HDU】How Many Answers Are Wrong(带权并查集)

时间:2015-05-04 22:04:26      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

num[i]代表i到根节点的值

这道题一开始竟然以为是线段树= =!后来发现线段树无法进行子区间的维护

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 222222;
int fa[maxn],num[maxn];
int find_father(int u){
    if(fa[u] == u)
        return fa[u];
    else{
        int temp  = fa[u];
        fa[u] = find_father(fa[u]);
        num[u] += num[temp];
        return fa[u];
    }
}
int main(){
    int n,m;
    while(scanf("%d%d",&n,&m) != EOF){
        memset(num,0,sizeof(num));
        int cnt = 0;
        for(int i = 0; i <= n; i++) fa[i] = i;
        for(int i = 0; i < m; i++){
            int x,y,z;
            scanf("%d%d%d",&x,&y,&z);
            x --;
            int l = find_father(x),r = find_father(y);
            if(l == r){
                int e = num[y] - num[x];
                if(e != z){
                    cnt ++;
                }
            }
            else{
                fa[r] = l;
                num[r] = z + num[x] - num[y];
            }
        }
        printf("%d\n",cnt);
    }
    return 0;
}


【HDU】How Many Answers Are Wrong(带权并查集)

标签:

原文地址:http://blog.csdn.net/u013451221/article/details/45486865

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!