結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
beet
|
| 提出日時 | 2020-05-15 21:32:37 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 283 ms / 2,000 ms |
| コード長 | 1,629 bytes |
| コンパイル時間 | 2,871 ms |
| コンパイル使用メモリ | 197,104 KB |
| 最終ジャッジ日時 | 2025-01-10 11:17:53 |
|
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 8 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
using Int = long long;
const char newl = '\n';
template <typename T>
struct WeightedUnionFind{
vector<int> rs,ps;
vector<T> ws;
WeightedUnionFind(){}
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);
}
};
//INSERT ABOVE HERE
signed main(){
cin.tie(0);
ios::sync_with_stdio(0);
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;
}
beet