http://acm.hdu.edu.cn/showproblem.php?pid=3047
并查集 记录各点到根的距离
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <cstring> 3 using namespace std; 4 5 const int N=50010,md=300; 6 int set[N],sum[N]; 7 int find(int x) 8 { 9 if(set[x]==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=1;i<=n;i++) set[i]=i; 21 int cnt=0; 22 while(m--) 23 { 24 int a,b,x; 25 scanf("%d%d%d",&a,&b,&x); 26 int fa=find(a), fb=find(b); 27 if(fa==fb) 28 { 29 int t=(sum[b]-sum[a])%md; 30 if(t<0) t+=md; 31 if(t!=x) cnt++; 32 } 33 else 34 { 35 set[fb]=fa; 36 sum[fb]=x+sum[a]-sum[b]; 37 } 38 } 39 printf("%d\n",cnt); 40 } 41 return 0; 42 }