2024-03-07 10:52:59 +00:00
|
|
|
class quick_union {
|
|
|
|
private:
|
2024-04-24 04:23:13 +01:00
|
|
|
vector<size_t> c, sz;
|
2024-03-07 10:52:59 +00:00
|
|
|
public:
|
2024-04-24 04:23:13 +01:00
|
|
|
quick_union(size_t n) : c(n), sz(n) {
|
2024-03-07 10:52:59 +00:00
|
|
|
iota(c.begin(), c.end(), 0);
|
2024-04-24 04:23:13 +01:00
|
|
|
sz.assign(n, 1);
|
2024-03-07 10:52:59 +00: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) {
|
2024-04-24 05:33:14 +01:00
|
|
|
if (connected(i, j)) return;
|
2024-04-24 04:23:13 +01:00
|
|
|
sz[query(j)] += sz[query(i)];
|
2024-03-07 10:52:59 +00:00
|
|
|
c[query(i)] = query(j);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool connected(size_t i, size_t j) {
|
|
|
|
return query(i) == query(j);
|
|
|
|
}
|
|
|
|
|
2024-04-24 04:23:13 +01:00
|
|
|
size_t query_size(size_t i) {
|
|
|
|
return sz[query(i)];
|
|
|
|
}
|
|
|
|
};
|