http://acm.hdu.edu.cn/showproblem.php?pid=3038
好牛的并查集
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <cstring> 3 using namespace std; 4 5 const int N=200010; 6 int set[N],sum[N]; 7 int find(int x) 8 { 9 if(x==set[x]) return x; 10 int t=find(set[x]); 11 sum[x]+=sum[set[x]]; 12 return set[x]=t; 13 } 14 int main() 15 { 16 int n,m; 17 while(~scanf("%d%d",&n,&m)) 18 { 19 memset(sum,0,sizeof(sum)); 20 for(int i=0;i<=n;i++) set[i]=i; 21 int cnt=0; 22 while(m--) 23 { 24 int a,b,s; 25 scanf("%d%d%d",&a,&b,&s); a--; 26 int fa=find(a), fb=find(b); 27 if(fa==fb) 28 { 29 if(sum[b]-sum[a]!=s) cnt++; 30 } 31 else 32 { 33 set[fb]=fa; 34 sum[fb]=s+sum[a]-sum[b]; 35 } 36 } 37 printf("%d\n",cnt); 38 } 39 return 0; 40 }