結果
| 問題 | No.2290 UnUnion Find |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2026-02-17 01:17:40 |
| 言語 | C++23 (gcc 15.2.0 + boost 1.89.0) |
| 結果 |
AC
|
| 実行時間 | 469 ms / 2,000 ms |
| コード長 | 3,163 bytes |
| 記録 | |
| コンパイル時間 | 1,755 ms |
| コンパイル使用メモリ | 180,800 KB |
| 実行使用メモリ | 13,440 KB |
| 最終ジャッジ日時 | 2026-02-17 01:18:06 |
| 合計ジャッジ時間 | 24,323 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 46 |
ソースコード
#line 1 "/workspaces/algorithm/verify/yukicoder/no_2290.test.cpp"
#define PROBLEM "https://yukicoder.me/problems/no/2290"
#include <algorithm>
#include <iostream>
#include <set>
#line 1 "/workspaces/algorithm/algorithm/DataStructure/UnionFind/union_find.hpp"
#line 5 "/workspaces/algorithm/algorithm/DataStructure/UnionFind/union_find.hpp"
#include <cassert>
#include <utility>
#include <vector>
namespace algorithm {
class UnionFind {
int m_vn; // m_vn:=(要素数).
int m_gn; // m_gn:=(集合の数).
std::vector<int> m_par; // m_par[x]:=(要素xの親). 0未満の場合,要素xは代表元であり,値の絶対値は属する集合のサイズを表す.
int root_internal(int x) {
if(m_par[x] < 0) return x;
return m_par[x] = root_internal(m_par[x]); // 経路圧縮.
}
public:
UnionFind() {}
explicit UnionFind(int n) : m_vn(n), m_gn(n), m_par(n, -1) {
assert(n >= 0);
}
// 要素数を取得する.
int vn() const { return m_vn; }
// 集合の数を取得する.
int gn() const { return m_gn; }
// 要素xが属する集合の代表元を取得する.
int root(int x) {
assert(0 <= x && x < vn());
return root_internal(x);
}
// 要素xが属する集合のサイズを取得する.
int size(int x) {
assert(0 <= x and x < vn());
return -m_par[root_internal(x)];
}
// 要素x, yが同じ集合に属するか判定する.
bool is_same(int x, int y) {
assert(0 <= x and x < vn());
assert(0 <= y and y < vn());
return root_internal(x) == root_internal(y);
}
// 要素x, yが属するそれぞれの集合を合併する.
bool unite(int x, int y) {
assert(0 <= x and x < vn());
assert(0 <= y and y < vn());
x = root_internal(x), y = root_internal(y);
if(x == y) return false; // Do nothing.
if(-m_par[x] < -m_par[y]) std::swap(x, y); // Merge technique (union by size).
m_par[x] += m_par[y];
m_par[y] = x;
--m_gn;
return true;
}
void reset() {
m_gn = m_vn;
std::fill(m_par.begin(), m_par.end(), -1);
}
};
} // namespace algorithm
#line 8 "/workspaces/algorithm/verify/yukicoder/no_2290.test.cpp"
int main() {
int n;
int q;
std::cin >> n >> q;
algorithm::UnionFind uf(n);
std::set<int> st;
for(int i = 0; i < n; ++i) st.insert(st.end(), i);
while(q--) {
int t;
std::cin >> t;
if(t == 1) {
int u, v;
std::cin >> u >> v;
--u, --v;
u = uf.root(u), v = uf.root(v);
st.erase(u);
st.erase(v);
uf.unite(u, v);
st.insert(uf.root(u));
} else {
int u;
std::cin >> u;
--u;
u = uf.root(u);
auto itr = std::find_if(st.begin(), st.end(), [&](int v) { return v != u; });
if(itr == st.end()) std::cout << -1 << "\n";
else std::cout << *itr + 1 << "\n";
}
}
}