题解:加权并查集或差分约束
一开始并查集竟然打错了QWQ
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100009;
int T;
int n,m;
int father[maxn];
int ky[maxn];
int Getf(int x){
if(father[x]==x)return x;
int ff=father[x];
father[x]=Getf(father[x]);
ky[x]+=ky[ff];
return father[x];
}
int main(){
scanf("%d",&T);
while(T--){
int fla=1;
scanf("%d%d",&n,&m);
for(int i=0;i<=n;++i)father[i]=i;
for(int i=0;i<=n;++i)ky[i]=0;
while(m--){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
--x;
if(Getf(x)==Getf(y)){
if(ky[y]-ky[x]!=z)fla=0;
}else{
int fx=Getf(x);
int fy=Getf(y);
father[fx]=fy;
ky[fx]=ky[y]-ky[x]-z;
}
}
if(fla)printf("true\n");
else printf("false\n");
}
return 0;
}