This documentation is automatically generated by online-judge-tools/verification-helper
View the Project on GitHub beet-aizu/library
// verification-helper: PROBLEM https://yukicoder.me/problems/3592 #include<bits/stdc++.h> using namespace std; #define call_from_test #include "../../datastructure/weightedunionfind.cpp" #undef call_from_test signed main(){ cin.tie(0); ios::sync_with_stdio(0); const char newl = '\n'; int n,q; cin>>n>>q; WeightedUnionFind<int> uf(n); vector<int> vs(n,0); auto add=[&](int a,int b){ vs[uf.find(a)]+=b; }; auto query=[&](int a){ int r=uf.find(a); return uf.diff(a,r)+vs[r]; }; auto unite=[&](int a,int b){ a=uf.find(a); b=uf.find(b); if(a==b) return; int x=query(a); int y=query(b); uf.unite(a,b,x-y); }; for(int i=0;i<q;i++){ int t,a,b; cin>>t>>a>>b; if(t==1){ a--;b--; unite(a,b); } if(t==2){ a--; add(a,b); } if(t==3){ a--; cout<<query(a)<<newl; } } return 0; }
#line 1 "test/yukicoder/3592.test.cpp" // verification-helper: PROBLEM https://yukicoder.me/problems/3592 #include<bits/stdc++.h> using namespace std; #define call_from_test #line 1 "datastructure/weightedunionfind.cpp" #line 3 "datastructure/weightedunionfind.cpp" using namespace std; #endif //BEGIN CUT HERE template <typename T> struct WeightedUnionFind{ vector<int> rs,ps; vector<T> ws; WeightedUnionFind(int n):rs(n,1),ps(n),ws(n,T(0)){ iota(ps.begin(),ps.end(),0); } int find(int x){ if(x==ps[x]) return x; int t=find(ps[x]); ws[x]+=ws[ps[x]]; return ps[x]=t; } T weight(int x){ find(x); return ws[x]; } bool same(int x,int y){ return find(x)==find(y); } void unite(int x,int y,T w){ w+=weight(x); w-=weight(y); x=find(x);y=find(y); if(x==y) return; if(rs[x]<rs[y]) swap(x,y),w=-w; rs[x]+=rs[y]; ps[y]=x; ws[y]=w; } T diff(int x,int y){ return weight(y)-weight(x); } }; //END CUT HERE #ifndef call_from_test signed main(){ return 0; } #endif #line 8 "test/yukicoder/3592.test.cpp" #undef call_from_test signed main(){ cin.tie(0); ios::sync_with_stdio(0); const char newl = '\n'; int n,q; cin>>n>>q; WeightedUnionFind<int> uf(n); vector<int> vs(n,0); auto add=[&](int a,int b){ vs[uf.find(a)]+=b; }; auto query=[&](int a){ int r=uf.find(a); return uf.diff(a,r)+vs[r]; }; auto unite=[&](int a,int b){ a=uf.find(a); b=uf.find(b); if(a==b) return; int x=query(a); int y=query(b); uf.unite(a,b,x-y); }; for(int i=0;i<q;i++){ int t,a,b; cin>>t>>a>>b; if(t==1){ a--;b--; unite(a,b); } if(t==2){ a--; add(a,b); } if(t==3){ a--; cout<<query(a)<<newl; } } return 0; }