This documentation is automatically generated by online-judge-tools/verification-helper
View the Project on GitHub ruthen71/rcpl
#define PROBLEM "https://judge.yosupo.jp/problem/unionfind" #include <bits/stdc++.h> #include "data_structure/unionfind.hpp" int main() { int N, Q; std::cin >> N >> Q; UnionFind uf(N); while (Q--) { int t, u, v; std::cin >> t >> u >> v; if (t == 0) { uf.merge(u, v); } else { std::cout << uf.same(u, v) << '\n'; } } return 0; }
#line 1 "verify/lc_data_structure/lc_unionfind.test.cpp" #define PROBLEM "https://judge.yosupo.jp/problem/unionfind" #include <bits/stdc++.h> #line 2 "data_structure/unionfind.hpp" struct UnionFind { int n; std::vector<int> parents; UnionFind() {} UnionFind(int n) : n(n), parents(n, -1) {} int leader(int x) { return parents[x] < 0 ? x : parents[x] = leader(parents[x]); } bool merge(int x, int y) { x = leader(x), y = leader(y); if (x == y) return false; if (parents[x] > parents[y]) std::swap(x, y); parents[x] += parents[y]; parents[y] = x; return true; } bool same(int x, int y) { return leader(x) == leader(y); } int size(int x) { return -parents[leader(x)]; } std::vector<std::vector<int>> groups() { std::vector<int> leader_buf(n), group_size(n); for (int i = 0; i < n; i++) { leader_buf[i] = leader(i); group_size[leader_buf[i]]++; } std::vector<std::vector<int>> result(n); for (int i = 0; i < n; i++) { result[i].reserve(group_size[i]); } for (int i = 0; i < n; i++) { result[leader_buf[i]].push_back(i); } result.erase(std::remove_if(result.begin(), result.end(), [&](const std::vector<int>& v) { return v.empty(); }), result.end()); return result; } void init(int n) { parents.assign(n, -1); } // reset }; #line 6 "verify/lc_data_structure/lc_unionfind.test.cpp" int main() { int N, Q; std::cin >> N >> Q; UnionFind uf(N); while (Q--) { int t, u, v; std::cin >> t >> u >> v; if (t == 0) { uf.merge(u, v); } else { std::cout << uf.same(u, v) << '\n'; } } return 0; }