链接:https://www.luogu.com.cn/problem/P2294
带权并查集裸题:(已知二者反推第三个)
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
#define maxx 1010
#define maxn 50010
int fa[maxn],va[maxn];
int Find(int x)
{
if(x!=fa[x])
{
int t=fa[x];
fa[x]=Find(fa[x]);
va[x]+=va[t];
}
return fa[x];
}
void Union(int x,int y,int s)
{
int fx=Find(x);
int fy=Find(y);
if(fx!=fy)
{
fa[fx]=fy;
va[fx]=s+va[y]-va[x];
}
}
int main()
{
int w;
cin>>w;
while(w--)
{
for(int i=0; i<=maxn-10; i++)
{
fa[i]=i;
va[i]=0;
}
int flag=1;
int n,m;
cin>>n>>m;
while(m--)
{
int x,y,s;
cin>>x>>y>>s;
--x;
if(!flag) continue;
int fx=Find(x);
int fy=Find(y);
if(fx==fy)
{
if(va[x]-va[y]!=s)
flag=0;
}
else
{
fa[fx]=fy;
va[fx]=s+va[y]-va[x];
}
}
if(flag)
cout<<"true"<<endl;
else
cout<<"false"<<endl;
}
return 0;}