1
0
Fork 0
cp-templates/trees/quick_union.cc

29 lines
590 B
C++
Raw Normal View History

2024-03-07 18:52:59 +08:00
class quick_union {
private:
vector<size_t> c, sz;
2024-03-07 18:52:59 +08:00
public:
quick_union(size_t n) : c(n), sz(n) {
2024-03-07 18:52:59 +08:00
iota(c.begin(), c.end(), 0);
sz.assign(n, 1);
2024-03-07 18:52:59 +08:00
}
size_t query(size_t i) {
if (c[i] != i) c[i] = query(c[i]);
return c[i];
}
void merge(size_t i, size_t j) {
if (connected(i, j)) return;
sz[query(j)] += sz[query(i)];
2024-03-07 18:52:59 +08:00
c[query(i)] = query(j);
}
bool connected(size_t i, size_t j) {
return query(i) == query(j);
}
size_t query_size(size_t i) {
return sz[query(i)];
}
};