带权并查集
/*************************************************************************
> File Name: hdu_3038.cpp
> Author: dulun
> Mail: dulun@xiyoulinux.org
> Created Time: 2016年03月28日 星期一 22时03分52秒
************************************************************************/
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#define LL long long
using namespace std;
const int N = 500086;
int p[N];
int sum[N];
int find(int x)
{
if(x != p[x])
{
int f = p[x];
// printf("p[%d] = %d\n", x, p[x]);
p[x] = find(p[x]);
sum[x] += sum[f];
// printf("sum[%d] = %d\n", x, sum[x]);
}
return p[x];
}
int main()
{
int n, m;
while(scanf("%d%d", &n, &m) != EOF)
{
for(int i = 0; i <= n; i++) p[i] = i, sum[i] = 0;
int ans = 0;
while(m--)
{
int l, r, s;
scanf("%d%d%d", &l, &r, &s);
l--;
int pl = find(l), pr = find(r);
if(pl == pr)
{
// printf("l = %d r = %d \n", l, r);
// printf("pl = %d pr = %d\n", pl, pr);
if(sum[l] - sum[r] != s) ans++;
}
else
{
p[pl] = pr;
sum[pl] = sum[r] - sum[l] + s;
// printf("sum[%d] = %d\n", pl, sum[pl]);
}
}
// printf("ans = %d\n", ans);
printf("%d\n", ans);
}
}