并查集,用来维护一些不相交的集合,可用来:合并两个集合;查询一个元素所处的集合
思想:维护一个森林,每棵树代表一个集合,数根元素为这个集合的代表元。利用数组father[]记录每个元素的父亲节点;
模板:
struct DisjointSet {
std::vector<int>father, rank,sex;
DisjointSet(int n) :father(n), rank(n),sex(n) {
for (int i = 0; i < n; i++) {
father[i] = i; sex[i] = -1; rank[i] = 0;
}
}
int find(int v)
{
return father[v] = father[v] == v ? v : find(father[v]);
}
void merge(int x, int y)
{
int a = find(x), b = find(y);
if (rank[a] < rank[b])
{
father[a] = b;
}
else {
father[b] = a;
if (rank[b] == rank[a]) {
++rank[a];
}
}
}
};
优化:压缩路径;按rank启发式合并,即将长度短的集合合并到长度长的集合中
例题:POJ2492
参考:https://segmentfault.com/a/1190000004023326
https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=%E5%B9%B6%E6%9F%A5%E9%9B%86&rsv_pq=eaad934500011169&rsv_t=129dM0mtptUU1Njj2jFfbAYFxY7Xi7sY5IgmNn3I6%2B8u7hlbut8ITIuGs78&rqlang=cn&rsv_enter=1&rsv_sug3=28&rsv_sug1=26&rsv_sug7=100