OJ-Problems-Source/.ACM-Templates/TXTs/并查集.txt

22 lines
768 B
Plaintext
Raw Normal View History

2016-11-22 09:38:35 +08:00
//<2F><><EFBFBD>鼯 + ·<><C2B7>ѹ<EFBFBD><D1B9> O(logn)
int fa[N];
void init(int n) { for (int i = 0; i <= n; i++) { fa[i] = i; } }
int findfa(int n) { return n == fa[n] ? n : fa[n] = findfa(fa[n]); }
inline void unite(int x, int y) {
x = findfa(x); y = findfa(y);
if (x != y) { fa[y] = x; }
}
//<2F><><EFBFBD>鼯 + ·<><C2B7>ѹ<EFBFBD><D1B9> + <20><><EFBFBD><EFBFBD>ʽ<EFBFBD>ϲ<EFBFBD> O(alpha(n))
int fa[N], rnk[N];
void init(int n) { for (int i = 0; i <= n; i++) { fa[i] = i; rnk[i] = 0; } }
int findfa(int n) { return n == fa[n] ? n : fa[n] = findfa(fa[n]); }
inline void unite(int x, int y) {
x = findfa(x); y = findfa(y);
if (x != y) {
if (rnk[x] > rnk[y]) { fa[y] = x; }
else { fa[x] = y; if (rnk[x] == rnk[y]) { rnk[y]++; } }
}
}
//<2F><><EFBFBD><EFBFBD>·<EFBFBD><C2B7>ѹ<EFBFBD><D1B9>
int findfa(int n) { while (fa[n] != n) { fa[n] = fa[fa[n]]; n = fa[n]; } return n; }