简单并查集模板

本文介绍了一种数据结构——并查集的基本实现方法,并通过一个简单的C++代码示例展示了如何初始化并查集、查找元素所属集合及合并集合。并查集能够高效地解决元素之间的连通性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

感觉对并查集比较形象的一个举例是《啊哈!算法!》里的点击打开链接

并查集的主要功能在于合并+查找,可以把复杂的从属关系变得简单。具体应用有很多,在各大OJ都有题,以后总结

下面是最简单的并查集

#include <iostream>
#include <cstdio> 
#include <algorithm>
using namespace std;
int f[1000];
void Init(int n){
	int i;
	for(i=0;i<n;i++){
		f[i]=i;
	}
}
int find(int x){	///查找——找到最开始的祖先 
	if(f[x]!=x)
		f[x]=find(f[x]);///压缩路径 
	return f[x];
}
void Union(int x,int y){///合并 ——根据信息合并
	int r1,r2;
	r1=find(x);
	r2=find(y);
	if(r1!=r2){
		f[r2]=r1;
	} 
	
}
int main() {
	int i,j,k,n,m;
	int ans=0;
	scanf("%d",&n); 
	Init(n);
	scanf("%d",&m);
	int x,y;
	for(i=0;i<m;i++){
		scanf("%d %d",&x,&y); 
		Union(x,y);
	} 
	for(i=0;i<n;i++){
		if(f[i]==i)
		ans++;
	}
	printf("%d\n",ans);
	system("pause");
	return 0;
}
/*
input: 
10 9
1 2
3 4
5 2
4 6
2 6
8 7
9 7
1 6
2 3

output:
3 
*/ 


### 可持久化并查集的实现 可持久化并查集是一种支持历史版本查询的并查集数据结构。它允许我们在任意时刻回溯到某个特定的历史状态,并在此基础上继续操作。以下是其基本原理和两种语言(C++ 和 Python)中的实现。 #### 基本原理 传统的并查集通过路径压缩优化,能够高效地完成查找与合并操作。然而,传统并查集不支持撤销或恢复到之前的某一状态。为了实现可持久化的特性,可以通过记录每次修改的操作日志或者利用树状数组/线段树等辅助数据结构来保存父节点的变化过程[^1]。 --- ### C++ 实现 在 C++ 中,我们通常借助向量 `vector` 来模拟动态数组的行为,用于存储每个版本的状态变化。下面是一个简单的可持久化并查集模板: ```cpp #include <bits/stdc++.h> using namespace std; struct PersistentUnionFind { struct Node { int parent; vector<int> history; // 记录parent随时间的变化 Node() : parent(-1), history({-1}) {} }; vector<Node> nodes; int version_count = 0; PersistentUnionFind(int n) : nodes(n + 1) {} // 查找根节点以及对应的版本号 pair<int, int> find_root_with_version(int u, int current_version) const { while (u >= 0 && current_version >= nodes[u].history.size()) { --current_version; } if (nodes[u].parent == -1 || current_version < nodes[u].history.size()) { return {u, current_version}; } else { return find_root_with_version(nodes[u].parent, current_version); } } void unite(int u, int v) { auto [root_u, ver_u] = find_root_with_version(u, version_count); auto [root_v, ver_v] = find_root_with_version(v, version_count); if (root_u != root_v) { ++version_count; if (-nodes[root_u].parent > -nodes[root_v].parent) { nodes[root_v].parent = root_u; nodes[root_v].history.push_back(version_count); // 更新v的父亲为u } else { nodes[root_u].parent = root_v; nodes[root_u].history.push_back(version_count); // 更新u的父亲为v } } } bool same_set(int u, int v, int query_version) const { auto [root_u, _] = find_root_with_version(u, query_version); auto [root_v, __] = find_root_with_version(v, query_version); return root_u == root_v; } }; int main() { int n = 5; // 初始化大小 PersistentUnionFind uf(n); uf.unite(1, 2); uf.unite(3, 4); uf.unite(2, 3); cout << (uf.same_set(1, 4, 3) ? "Yes" : "No") << endl; // 输出 Yes } ``` 此代码实现了带有版本控制功能的并查集,其中 `unite` 方法会更新两个集合的关系,而 `same_set` 则可以在给定的时间点检查两元素是否属于同一集合[^1]。 --- ### Python 实现 Python 的字典非常适合用来构建稀疏映射关系,因此我们可以用字典代替 C++ 中的静态数组。下面是 Python 版本的可持久化并查集实现: ```python class PersistentUnionFind: class Node: def __init__(self): self.parent = None self.rank = 0 self.history = [] # 存储历史更改 def __init__(self, size): self.nodes = [self.Node() for _ in range(size)] self.version = 0 def find(self, x, target_version=None): node = self.nodes[x] versions_to_check = list(range(len(node.history))) if not target_version else [target_version] for idx in reversed(versions_to_check): # 回退至最近的有效版本 p = node.history[idx][1] if idx < len(node.history) and node.history[idx][0] <= target_version else node.parent if p is None or (target_version is not None and idx < len(node.history)): break x = p node = self.nodes[p] return x def union(self, x, y): root_x = self.find(x) root_y = self.find(y) if root_x != root_y: rank_x = self.nodes[root_x].rank rank_y = self.nodes[root_y].rank if rank_x > rank_y: self.nodes[root_y].parent = root_x self.nodes[root_y].history.append((self.version, root_x)) elif rank_x < rank_y: self.nodes[root_x].parent = root_y self.nodes[root_x].history.append((self.version, root_y)) else: self.nodes[root_y].parent = root_x self.nodes[root_y].history.append((self.version, root_x)) self.nodes[root_x].rank += 1 self.version += 1 def connected(self, x, y, at_time=None): return self.find(x, at_time) == self.find(y, at_time) # 测试代码 if __name__ == "__main__": N = 5 uf = PersistentUnionFind(N) uf.union(1, 2) uf.union(3, 4) uf.union(2, 3) print("Are 1 and 4 connected?", uf.connected(1, 4)) # True print("Were 1 and 4 connected before last operation?", uf.connected(1, 4, uf.version - 1)) # False ``` 在这个实现中,`union` 函数负责连接两个子集,同时维护历史记录;`find` 函数则可以根据指定的时间戳返回对应版本的结果[^1]。 --- ### 总结 以上展示了如何分别用 C++ 和 Python 构建可持久化并查集的方法。这两种实现都依赖于额外的空间开销以追踪每一次变动的历史信息,从而能够在不同时间点上执行查询操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值