综述
我们接上一节,https://blog.csdn.net/justidle/article/details/108846236,继续讨论并查集问题。我们发现使用 C++ 数组实现并查集主要问题有以下几个:
1、元素中不能支持负数。因为 C++ 规定数组的下标不能是负数。
2、代码量相对比较大。实现并查集代码量相对有点大。
使用 map 实现并查集
我们可以使用 STL 的 map 这个数据结构来实现。map 本生就是两个数据的映射关系,天生就具有并查集的特点。而且 map 可以支持负数。
数据定义
map<int, int> ds;//定义一个并查集
map<int, int> ranks;//定义树的深度
初始化
这里,我们直接将父节点初始化为自己。
/*
st 表示起点
ed 表示终点
*/
void init(int st, int ed) {
for (int i=st; i<=ed; i++) {
ds[i]=i;
ranks[i]=0;
}
}
查询
这里我们使用递归来实现。也就是如果 x 的父节点是本身,直接返回。如果不是,我们继续查询 ds[x] 的父节点。
int find_root(int x) {
return x==ds[x]?x:ds[x]=find_root(ds[x]);
}
使用递归的优点是代码简洁,但是难以阅读。当递归层次过大的时候,效率将大大降低。
合并
void union_set(int x, int y) {
int x_root=find_root(x);
int y_root=find_root(y);
if (x_root!=y_root) {
if (ranks[x_root]>ranks[y_root]) {
ds[y_root]=x_root;
} else if (ranks[x_root]<ranks[y_root]) {
ds[x_root]=y_root;
} else {
ds[x_root]=y_root;
ranks[y_root]++;
}
}
}
完整代码
template <class T>
struct _DISJOINTSET {
T _st;//起点
T _ed;//终点
map<T, T> ds;//并查集
map<T, T> ranks;
_DISJOINTSET() : _st(0), _ed(0) {}
_DISJOINTSET(T st, T ed) {
init(st, ed);
}
/*
st 表示起点
ed 表示终点
*/
void init(T st, T ed) {
if (ed<st) {
return;
}
for (T i=st; i<=ed; i++) {
ds[i]=i;
ranks[i]=0;
}
_st = st;
_ed = ed;
}
//查找x的父亲
T find_root(T x) {
return x==ds[x]?x:ds[x]=find_root(ds[x]);
}
//建立关系
void union_set(T x, T y) {
T x_root=find_root(x);
T y_root=find_root(y);
if (x_root!=y_root) {
if (ranks[x_root]>ranks[y_root]) {
ds[y_root]=x_root;
} else if (ranks[x_root]<ranks[y_root]) {
ds[x_root]=y_root;
} else {
ds[x_root]=y_root;
ranks[y_root]++;
}
}
}
//查找x和y是否在同一个父亲
bool relation(T x, T y) {
return find_root(x)==find_root(y);
}
};
模板样例
这次,我们使用洛谷的 P2078 朋友,https://www.luogu.com.cn/problem/P2078。
AC 代码
//https://www.luogu.com.cn/problem/P2078
//P2078 朋友
//使用 STL Map 实现
#include <bits/stdc++.h>
using namespace std;
map<int, int> ds;//并查集
map<int, int> ranks;
//查找x的父亲
int find_root(int x) {
return x==ds[x]?x:ds[x]=find_root(ds[x]);
}
//建立关系
void judge(int x, int y) {
int x_root=find_root(x);
int y_root=find_root(y);
if (x_root!=y_root) {
if (ranks[x_root]>ranks[y_root]) {
ds[y_root]=x_root;
} else if (ranks[x_root]<ranks[y_root]) {
ds[x_root]=y_root;
} else {
ds[x_root]=y_root;
ranks[y_root]++;
}
}
}
//查找x和y是否在同一个父亲
bool relation(int x, int y) {
return find_root(x)==find_root(y);
}
int main() {
int n,m,p,q;
cin>>n>>m>>p>>q;
//初始化并查集
for (int i=-1*m; i<=n; i++) {
ds[i]=i;//将父亲设置为自己
ranks[i]=0;
}
//读入关系
for (int i=1; i<=p+q; i++) {
int x,y;
cin>>x>>y;
judge(x, y);
}
//查找男生认识小明
int boys=0;
for (int i=1; i<=n; i++) {
if (relation(ds[i], 1)) {
boys++;
}
}
//查找女生认识小红
int girls=0;
for (int i=-1*m; i<=-1; i++) {
if (relation(ds[i], -1)) {
girls++;
}
}
cout<<min(boys, girls)<<"\n";
return 0;
}