这两道题一模一样,代码都通用....................
带权并查集和并查集偏移向量一回事儿
#include <stdio.h>
#include <iostream>
#include <queue>
#include <set>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
#define N 200050
int p[N],sum[N];
int find(int x){
if(x!=p[x]){
int t=p[x];
p[x]=find(p[x]);
sum[x]+=sum[t];
}
return p[x];
}
int main(){
int m,n;
int a,b,s,ans;
while(scanf("%d%d",&n,&m)!=EOF){
ans=0;
for(int i=0; i<=n; i++) p[i]=i,sum[i]=0;
for(int i=0; i<m; i++){
scanf("%d%d%d",&a,&b,&s);
a--;
int x=find(a);
int y=find(b);
if(x!=y){
p[x]=y;
sum[x]=sum[b]-sum[a]+s;
}else if(sum[a]-sum[b]!=s) ans++;
}//for
printf("%d\n",ans);
}
return 0;
}