题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3038
借鉴博客:https://blog.csdn.net/dextrad_ihacker/article/details/51016017
代码:
#include<iostream>
using namespace std;
const int maxn=200005;
int pre[maxn];
int sum[maxn];
int n,m;
void init()
{
for(int i=0;i<maxn;i++)
{
pre[i]=i;
sum[i]=0;
}
}
int find(int x)
{
if(pre[x]!=x)
{
int f=pre[x];
pre[x]=find(pre[x]);
sum[x]+=sum[f];
}
return pre[x];
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
int ans=0;
init();
int a,b,v;
while(m--)
{
cin>>a>>b>>v;
a--;
int x=find(a);
int y=find(b);
if(x!=y)
{
pre[x]=y;
sum[x]=sum[b]-sum[a]+v;
}
else
{
if(sum[a]-sum[b]!=v) ans++;
}
}
cout<<ans<<endl;
}
return 0;
}