And lookup template
Learned from lc user "Code Caprice".
int n; // 并查集边的数量
vector<int> father; //在函数里使用father.resize(n)
// 并查集初始化
void init() {
for (int i = 0; i < n; ++i) {
father[i] = i;
}
}
// 并查集里寻根的过程
int find(int u) {
return u == father[u] ? u : father[u] = find(father[u]);
}
// 将v->u 这条边加入并查集
void join(int u, int v) {
u = find(u);
v = find(v);
if (u == v) return ;
father[v] = u;
}
// 判断 u 和 v是否找到同一个根
bool same(int u, int v) {
u = find(u);
v = find(v);
return u == v;
}
lc topic:
547. The number of provinces – simple union search
721. Account merger – use union search to merge data
1584. The minimum cost of linking all points – use union search to assist judgment