結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2020-05-24 15:00:21 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 569 ms / 2,000 ms |
| コード長 | 2,680 bytes |
| コンパイル時間 | 1,854 ms |
| コンパイル使用メモリ | 176,792 KB |
| 実行使用メモリ | 38,912 KB |
| 最終ジャッジ日時 | 2024-10-11 07:16:26 |
| 合計ジャッジ時間 | 6,941 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 8 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < (int)n; ++i)
#define FOR(i, a, b) for(int i = a; i < (int)b; ++i)
#define rrep(i, n) for(int i = ((int)n - 1); i >= 0; --i)
using ll = long long;
using ld = long double;
const ll INF = 1e18;
const int Inf = 1e9;
const double EPS = 1e-9;
const int MOD = 1e9 + 7;
vector<vector<int> > g;
class DisjointSet {
public:
vector<int> rank, p, size, sum;
DisjointSet() {}
DisjointSet(int s) {
rank.resize(s, 0);
p.resize(s, 0);
size.resize(s, 0);
sum.resize(s, 0);
rep (i, s) init(i);
}
void init(int x) {
p[x] = x;
rank[x] = 0;
size[x] = 1;
}
bool isSame(int x, int y) {
return root(x) == root(y);
}
void makeset(int x, int y) {
if (isSame(x, y)) return;
link(root(x), root(y));
}
void link(int x, int y) {
if (rank[x] > rank[y]) {
p[y] = x;
size[x] += size[y];
int diff = sum[y] - sum[x];
sum[y] = 0;
for (auto z : g[y]) {
sum[z] += diff;
g[x].push_back(z);
}
g[y].clear();
} else {
p[x] = y;
size[y] += size[x];
if (rank[x] == rank[y]) {
rank[y]++;
}
int diff = sum[x] - sum[y];
sum[x] = 0;
for (auto z : g[x]) {
sum[z] += diff;
g[y].push_back(z);
}
g[x].clear();
}
}
int root(int x) {
if (x != p[x]) {
p[x] = root(p[x]);
}
return p[x];
}
int getSize(int x) {
return size[root(x)];
}
void add(int x, int v) {
int p = root(x);
sum[p] += v;
}
};
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(0);
int n, q;
cin >> n >> q;
g.resize(n);
DisjointSet dj = DisjointSet(n);
rep (i, n) g[i].push_back(i);
rep (i, q) {
int t, a, b;
cin >> t >> a >> b;
if (t == 1) {
dj.makeset(a - 1, b - 1);
} else if (t == 2) {
dj.add(a - 1, b);
} else {
a--;
int p = dj.root(a);
if (p == a) cout << dj.sum[a] << endl;
else cout << dj.sum[a] + dj.sum[p] << endl;
}
}
return 0;
}