結果

問題 No.1054 Union add query
ユーザー wk
提出日時 2020-05-16 14:16:18
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 746 ms / 2,000 ms
コード長 2,049 bytes
コンパイル時間 1,665 ms
コンパイル使用メモリ 171,212 KB
実行使用メモリ 9,088 KB
最終ジャッジ日時 2024-09-22 08:05:08
合計ジャッジ時間 7,442 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 8
権限があれば一括ダウンロードができます

ソースコード

diff #
プレゼンテーションモードにする

#include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; (i) < (n); (i)++)
using namespace std;
long modpow(long a, long n, long mod) {
long res = 1;
while (n > 0) {
if (n & 1) res = res * a % mod;
a = a * a % mod;
n >>= 1;
}
return res;
}
// a^{-1} mod
long modinv(long a, long mod) {
return modpow(a, mod - 2, mod);
}
int GCD(int a, int b){
if(b == 0) return a;
if(a < b) return GCD(b, a);
else return GCD(b, a%b);
}
struct UnionFind {
vector<int> par;
vector<int> rank;
UnionFind(int n = 1){
init(n);
}
void init(int n = 1){
par.resize(n);
rank.resize(n);
REP(i, n) par[i] = i, rank[i] = 0;
}
int root(int x){
if(par[x] == x) return x;
else return root(par[x]);
}
bool issame(int x, int y){
return root(x) == root(y);
}
void merge(int x, int y){
x = root(x); y = root(y);
if(x == y) return;
if(rank[x] < rank[y]) swap(x, y);
if(rank[x] == rank[y]) rank[x]++;
par[y] = x;
return;
}
};
int main()
{
int N, Q; cin >> N >> Q;
UnionFind uf(N);
int num[500005];
REP(i, N) num[i] = 0;
REP(i, Q){
//REP(i, N) cout << num[i] << " ";
//cout << endl;
int T, A, B; cin >> T >> A >> B;
if(T==1){
int nea = uf.root(A-1);
int neb = uf.root(B-1);
if(nea != neb){
uf.merge(A-1, B-1);
if(uf.root(A-1) == nea){
num[neb] -= num[nea];
}else{
num[nea] -= num[neb];
}
}
}else if(T==2){
num[uf.root(A-1)] += B;
}else{
int sum = 0;
int first = A-1;
for(;;){
sum += num[first];
if(first == uf.par[first]) break;
first = uf.par[first];
}
cout << sum << endl;
}
}
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0