带权并查集板题
维护到根的距离
#include <iostream> #include <algorithm> #include <cstring> #include <vector> #include <queue> using namespace std; const int N =2e5+10; #define int long long int n,fa[N],dis[N]; int find(int x){ if(x==fa[x]) return x; int t =find(fa[x]) ; dis[x]+=dis[fa[x]] ; fa[x]=t ; return fa[x] ; } void join(int x,int y,int v){ int fx = find(x), fy= find(y) ; fa[fx] =fy ; dis[fx] = v+dis[y]-dis[x] ; } void sov(){ int q ,flg=1; cin>>n>>q; for(int i=1;i<=n;i++) fa[i]=i,dis[i]=0 ; while(q--){ int x,y,d ; cin>>x>>y>>d; int fx =find(x), fy =find(y) ; if(fx==fy){ if(d!=dis[x]-dis[y]) flg =0 ; } else{ join(x,y,d); } } if(flg) cout<<"YES\n";else cout<<"NO\n" ; } signed main(){ int T; cin>>T; while(T--) sov() ; }