結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
🍮かんプリン
|
| 提出日時 | 2020-05-15 22:07:35 |
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 2,114 bytes |
| コンパイル時間 | 1,524 ms |
| コンパイル使用メモリ | 168,076 KB |
| 実行使用メモリ | 14,848 KB |
| 最終ジャッジ日時 | 2024-09-19 10:41:56 |
| 合計ジャッジ時間 | 6,740 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 WA * 1 |
| other | AC * 6 WA * 2 |
ソースコード
/**
* @FileName f.cpp
* @Author kanpurin
* @Created 2020.05.15 22:07:29
**/
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
int n;
vector< ll > w;
// WeightedUnionFind
// verify : https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/1/DSL_1_B
template < typename T >
struct WeightedUnionFind {
private:
vector< int > par;
vector< int > rank;
vector< T > diff_weight;
public:
WeightedUnionFind(int n) {
par.resize(n);
rank.resize(n);
diff_weight.resize(n);
for (int i = 0; i < n; ++i) par[i] = i, rank[i] = 0, diff_weight[i] = 0;
}
int root(int x) {
if (par[x] == x) {
return x;
} else {
int r = root(par[x]);
diff_weight[x] += diff_weight[par[x]];
return par[x] = r;
}
}
T weight(int x) {
root(x);
return diff_weight[x];
}
bool same(int x, int y) {
return root(x) == root(y);
}
// y - x = w
bool unite(int x, int y, T w) {
w += weight(x);
w -= weight(y);
x = root(x);
y = root(y);
if (x == y) return false;
if (rank[x] < rank[y]) swap(x, y), w = -w;
if (rank[x] == rank[y]) ++rank[x];
par[y] = x;
diff_weight[y] = w;
return true;
}
// y - x
T diff(int x, int y) {
return weight(y) - weight(x);
}
};
int main() {
int q;
cin >> n >> q;
w.resize(n, 0);
WeightedUnionFind< ll > uf(n);
for (int i = 0; i < q; i++) {
int t, a, b;
cin >> t >> a >> b;
if (t == 1) {
a--;
b--;
int ra = uf.root(a);
int rb = uf.root(b);
uf.unite(rb, ra, w[rb] - w[ra]);
if (uf.root(ra) == rb) {
w[ra] = 0;
}
else {
w[rb] = 0;
}
} else if (t == 2) {
a--;
w[uf.root(a)] += b;
} else {
a--;
cout << uf.diff(a,uf.root(a)) + w[uf.root(a)] << endl;
}
}
return 0;
}
🍮かんプリン