重み付きUnion-Find
Union-Findに重みをつけたしたもの
例題
code:cpp
template<class Abel> struct UnionFind {
vector<int> par;
vector<int> rank;
vector<Abel> diff_weight;
UnionFind(int n = 1, Abel SUM_UNITY = 0) {
init(n, SUM_UNITY);
}
void init(int n = 1, Abel SUM_UNITY = 0) {
par.resize(n); rank.resize(n); diff_weight.resize(n);
for (int i = 0; i < n; ++i) pari = i, ranki = 0, diff_weighti = SUM_UNITY; }
int root(int x) {
return x;
}
else {
diff_weightx += diff_weight[parx]; }
}
Abel weight(int x) {
root(x);
}
bool issame(int x, int y) {
return root(x) == root(y);
}
bool merge(int x, int y, Abel w) {
w += weight(x); w -= weight(y);
x = root(x); y = root(y);
if (x == y) return false;
if (rankx < ranky) swap(x, y), w = -w; if (rankx == ranky) ++rankx; return true;
}
Abel diff(int x, int y) {
return weight(y) - weight(x);
}
};
bool solve();
void _main(){
int testcase = 1;
// cin >> testcase;
for(;testcase--;){
if(solve()){
// O("Yes");
}
else{
// O("No");
}
}
}
bool solve(){
LL(n,q);
UnionFind<ll>uf(n);
vector<ll>ans;
rep(i,q){
LL(a,b,c);
a--,b--;
if(uf.issame(a,b)){
if(uf.diff(a,b)==c){
ans.pb(i+1);
}
}
else{
uf.merge(a,b,c);
ans.pb(i+1);
}
}
O(ans);
return true;
}