File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ #define PROBLEM " https://judge.yosupo.jp/problem/unionfind"
2+
3+ #include " weilycoder/unionfind.hpp"
4+ #include < iostream>
5+ using namespace std ;
6+ using namespace weilycoder ;
7+
8+ int main () {
9+ cin.tie (nullptr )->sync_with_stdio (false );
10+ cin.exceptions (cin.failbit | cin.badbit );
11+ size_t n, q;
12+ cin >> n >> q;
13+ UnionFind uf (n);
14+ for (size_t _ = 0 ; _ < q; ++_) {
15+ size_t op, x, y;
16+ cin >> op >> x >> y;
17+ switch (op) {
18+ case 0 :
19+ uf.unite (x, y);
20+ break ;
21+ case 1 :
22+ cout << (uf.getf (x) == uf.getf (y) ? " 1\n " : " 0\n " );
23+ break ;
24+ }
25+ }
26+ return 0 ;
27+ }
Original file line number Diff line number Diff line change 1+ #include < algorithm>
2+ #include < numeric>
3+ #include < vector>
4+
5+ namespace weilycoder {
6+ template <typename ptr_t = size_t > struct UnionFind {
7+ std::vector<ptr_t > parent, size;
8+
9+ UnionFind (ptr_t n) : parent(n), size(n, 1 ) {
10+ std::iota (parent.begin (), parent.end (), 0 );
11+ }
12+
13+ ptr_t getf (ptr_t x) {
14+ while (x != parent[x])
15+ x = parent[x] = parent[parent[x]];
16+ return x;
17+ }
18+
19+ bool unite (ptr_t x, ptr_t y) {
20+ x = getf (x), y = getf (y);
21+ if (x == y)
22+ return false ;
23+ if (size[x] < size[y])
24+ std::swap (x, y);
25+ parent[y] = x, size[x] += size[y];
26+ return true ;
27+ }
28+ };
29+ } // namespace weilycoder
You can’t perform that action at this time.
0 commit comments