結果
問題 | No.2290 UnUnion Find |
ユーザー |
![]() |
提出日時 | 2023-05-15 21:27:42 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 441 ms / 2,000 ms |
コード長 | 2,001 bytes |
コンパイル時間 | 1,436 ms |
コンパイル使用メモリ | 130,756 KB |
最終ジャッジ日時 | 2025-02-13 00:41:20 |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 46 |
ソースコード
#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include <functional> #include <cmath> #include <string> #include <queue> #include <map> #include <bitset> #include <set> #include <stack> #include <numeric> #include <unordered_map> #include <random> using namespace std; using ll = long long; using vi = vector<int>; using vvi = vector<vi>; using vl = vector<ll>; using vvl = vector<vl>; using vb = vector<bool>; using vvb = vector<vb>; using vd = vector<double>; using vs = vector<string>; using pii = pair<int, int>; using pll = pair<ll, ll>; using pdd = pair<double, double>; using vpii = vector<pii>; using vpll = vector<pll>; using vpdd = vector<pdd>; const int inf = (1 << 30) - 1; const ll INF = 1LL << 60; const int MOD = 1000000007; //const int MOD = 998244353; struct UnionFind { vector<int> par; vector<int> sizes; UnionFind(int n) : par(n), sizes(n, 1) { for (int i = 0; i < n; i++) par[i] = i; } int root(int x) { if (x == par[x]) return x; return par[x] = root(par[x]); } void unite(int x, int y) { x = root(x); y = root(y); if (x == y) return; if (sizes[x] < sizes[y]) swap(x, y); par[y] = x; sizes[x] += sizes[y]; } bool same(int x, int y) { return root(x) == root(y); } int size(int x) { return sizes[root(x)]; } }; int main() { int n, q; cin >> n >> q; UnionFind uf(n); set<int> node; for (int i = 0; i < n; i++) node.insert(i); for (int i = 0; i < q; i++) { int t, u, v; cin >> t; if (t == 1) { cin >> u >> v; u--; v--; if (!uf.same(u, v)) { int r1 = uf.root(u); int r2 = uf.root(v); uf.unite(u, v); if (uf.root(r1) != r1) node.erase(r1); if (uf.root(r2) != r2) node.erase(r2); } } else { cin >> v; v--; int r = uf.root(v); if (*node.begin() == r) { if (node.size() == 1) { cout << -1 << endl; } else { cout << *(next(node.begin())) + 1 << endl; } } else { cout << *node.begin() + 1 << endl; } } } return 0; }