結果
| 問題 |
No.2290 UnUnion Find
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2023-05-06 00:02:34 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 178 ms / 2,000 ms |
| コード長 | 1,808 bytes |
| コンパイル時間 | 854 ms |
| コンパイル使用メモリ | 86,088 KB |
| 最終ジャッジ日時 | 2025-02-12 20:15:47 |
|
ジャッジサーバーID (参考情報) |
judge5 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 46 |
ソースコード
#include <iostream>
#include <vector>
#include <set>
using namespace std;
struct UnionFindTree {
vector<int> parent;
int cnt;
set<int> roots;
UnionFindTree(int n) {
parent.assign(n, -1);
cnt = n;
for (int i = 0; i < n; i++) {
roots.insert(i);
}
}
int findRoot(int a) {
if (parent[a] < 0) {
return a;
}
int r = findRoot(parent[a]);
if (roots.count(a) && a != r) {
roots.erase(a);
}
parent[a] = r;
return r;
}
bool unite(int a, int b) {
int x = findRoot(a), y = findRoot(b);
if (x == y) {
return false;
}
if (size(x) < size(y)) {
swap(x, y);
}
roots.erase(y);
parent[x] += parent[y];
parent[y] = x;
cnt--;
return true;
}
bool sameRoot(int a, int b) {
return findRoot(a) == findRoot(b);
}
int size(int a) {
return -parent[findRoot(a)];
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, q;
cin >> n >> q;
UnionFindTree uf(n);
int typ, u, v;
for (int i = 0; i < q; i++) {
cin >> typ;
switch (typ) {
case 1:
cin >> u >> v;
u--, v--;
uf.unite(u, v);
break;
case 2:
cin >> v;
v--;
int r = uf.findRoot(v);
int ans = -1;
for (auto it = uf.roots.begin(); it != uf.roots.end(); it++) {
int v2 = *it;
if (r != v2) {
ans = v2 + 1;
break;
}
}
cout << ans << "\n";
break;
}
}
return 0;
}