並查集實驗室
並查集多叉樹森林結構,直觀展示按秩合併與路徑壓縮的扁平化效果。
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| parent | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
關於本工具
並查集(Disjoint Set Union,DSU)維護一組互不相交的集合,能非常快地回答一個問題:這兩個元素在同一個集合裡嗎?每個集合是一棵由父指標組成的樹,根就是集合的代表元。find(x) 沿父指標走到根;union(x, y) 把一個根掛到另一個根下面。
兩個小最佳化讓它幾乎是常數時間:按秩合併把較矮的樹掛到較高的樹下;路徑壓縮讓查詢路徑上的每個節點都直接指向根。本實驗室可以分別開關這兩項最佳化,觀察樹的形狀和“最高的樹”計數如何變化。
使用方法 並查集實驗室
- 一開始每個元素各成一個集合。輸入兩個元素點“合併”,或輸入一個元素點“查詢”。
- 觀察父指標箭頭:合併時從一個根畫出新箭頭指向另一個根;查詢會高亮通往根的路徑。
- 關閉兩項最佳化,點“構造最壞情況的鏈”得到一棵很高的樹。
- 開啟路徑壓縮並執行 find(0):整條鏈會塌縮成星形。
範例
按秩合併
union(1, 2)、union(3, 4)、union(1, 3)
兩棵樹的秩都是 1,於是一個根掛到另一個根下,後者的秩變為 2
路徑壓縮
鏈 0→1→2→3→4,執行 find(0)
返回 4;之後 0、1、2、3 都直接指向 4
五種語言的程式碼實作
同一演算法的 Python、JavaScript、Java、Go 和 C++ 實作。每段程式都完整可執行,註解中標出了它的輸出結果。
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
self.count = n # number of disjoint sets
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root: # path compression
self.parent[x], x = root, self.parent[x]
return root
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already connected
if self.rank[ra] < self.rank[rb]: # union by rank
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
self.count -= 1
return True
uf = UnionFind(6)
uf.union(0, 1)
uf.union(2, 3)
uf.union(1, 3)
print(uf.find(0) == uf.find(2)) # True
print(uf.find(0) == uf.find(4)) # False
print(uf.union(0, 3)) # False: would create a cycle
print(uf.count) # 3 ({0,1,2,3}, {4}, {5}) class UnionFind {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.rank = new Array(n).fill(0);
this.count = n; // number of disjoint sets
}
find(x) {
let root = x;
while (this.parent[root] !== root) root = this.parent[root];
while (this.parent[x] !== root) { // path compression
const next = this.parent[x];
this.parent[x] = root;
x = next;
}
return root;
}
union(a, b) {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false; // already connected
if (this.rank[ra] < this.rank[rb]) [ra, rb] = [rb, ra]; // union by rank
this.parent[rb] = ra;
if (this.rank[ra] === this.rank[rb]) this.rank[ra]++;
this.count--;
return true;
}
}
const uf = new UnionFind(6);
uf.union(0, 1);
uf.union(2, 3);
uf.union(1, 3);
console.log(uf.find(0) === uf.find(2)); // true
console.log(uf.find(0) === uf.find(4)); // false
console.log(uf.union(0, 3)); // false: would create a cycle
console.log(uf.count); // 3 ({0,1,2,3}, {4}, {5}) public class Main {
static class UnionFind {
private final int[] parent, rank;
int count; // number of disjoint sets
UnionFind(int n) {
parent = new int[n];
rank = new int[n];
count = n;
for (int i = 0; i < n; i++) parent[i] = i;
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
while (parent[x] != root) { // path compression
int next = parent[x];
parent[x] = root;
x = next;
}
return root;
}
boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already connected
if (rank[ra] < rank[rb]) { int t = ra; ra = rb; rb = t; } // union by rank
parent[rb] = ra;
if (rank[ra] == rank[rb]) rank[ra]++;
count--;
return true;
}
}
public static void main(String[] args) {
UnionFind uf = new UnionFind(6);
uf.union(0, 1);
uf.union(2, 3);
uf.union(1, 3);
System.out.println(uf.find(0) == uf.find(2)); // true
System.out.println(uf.find(0) == uf.find(4)); // false
System.out.println(uf.union(0, 3)); // false: would create a cycle
System.out.println(uf.count); // 3 ({0,1,2,3}, {4}, {5})
}
} package main
import "fmt"
type UnionFind struct {
parent, rank []int
Count int // number of disjoint sets
}
func NewUnionFind(n int) *UnionFind {
uf := &UnionFind{parent: make([]int, n), rank: make([]int, n), Count: n}
for i := range uf.parent {
uf.parent[i] = i
}
return uf
}
func (uf *UnionFind) Find(x int) int {
root := x
for uf.parent[root] != root {
root = uf.parent[root]
}
for uf.parent[x] != root { // path compression
uf.parent[x], x = root, uf.parent[x]
}
return root
}
func (uf *UnionFind) Union(a, b int) bool {
ra, rb := uf.Find(a), uf.Find(b)
if ra == rb {
return false // already connected
}
if uf.rank[ra] < uf.rank[rb] { // union by rank
ra, rb = rb, ra
}
uf.parent[rb] = ra
if uf.rank[ra] == uf.rank[rb] {
uf.rank[ra]++
}
uf.Count--
return true
}
func main() {
uf := NewUnionFind(6)
uf.Union(0, 1)
uf.Union(2, 3)
uf.Union(1, 3)
fmt.Println(uf.Find(0) == uf.Find(2)) // true
fmt.Println(uf.Find(0) == uf.Find(4)) // false
fmt.Println(uf.Union(0, 3)) // false: would create a cycle
fmt.Println(uf.Count) // 3 ({0,1,2,3}, {4}, {5})
} #include <iostream>
#include <numeric>
#include <utility>
#include <vector>
class UnionFind {
std::vector<int> parent, rank;
public:
int count; // number of disjoint sets
explicit UnionFind(int n) : parent(n), rank(n, 0), count(n) {
std::iota(parent.begin(), parent.end(), 0);
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
while (parent[x] != root) { // path compression
int next = parent[x];
parent[x] = root;
x = next;
}
return root;
}
bool unite(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already connected
if (rank[ra] < rank[rb]) std::swap(ra, rb); // union by rank
parent[rb] = ra;
if (rank[ra] == rank[rb]) rank[ra]++;
count--;
return true;
}
};
int main() {
UnionFind uf(6);
uf.unite(0, 1);
uf.unite(2, 3);
uf.unite(1, 3);
std::cout << std::boolalpha;
std::cout << (uf.find(0) == uf.find(2)) << '\n'; // true
std::cout << (uf.find(0) == uf.find(4)) << '\n'; // false
std::cout << uf.unite(0, 3) << '\n'; // false: would create a cycle
std::cout << uf.count << '\n'; // 3 ({0,1,2,3}, {4}, {5})
} LeetCode 練習題
用到這一演算法的經典題目,適合在玩過本實驗室後動手練習。連結將開啟 LeetCode。
複雜度
同時使用兩項最佳化時,對 n 個元素執行 m 次操作的總耗時為 O(m · α(n)),其中 α 是反阿克曼函式——對任何現實規模的輸入都不超過 4。不做最佳化時,單次查詢可能耗時 O(n)。
典型用途
- Kruskal 最小生成樹:只有當邊的兩端在不同集合時才加入這條邊。
- 在邊的資料流中統計連通分量,無需儲存整張圖。
- 向無向圖加邊時檢測是否成環。
- 對等價項分組:賬號合併、影像分割、滲流模擬。
常見問題
解答您關心的工具使用與資料安全相關問題。
秩到底是什麼?
樹高的一個上界。只有兩棵秩相同的樹合併時它才會增加。路徑壓縮可能讓實際高度變小,但秩不會減小。
並查集能拆分集合嗎?
不能,它只支援合併。刪除或拆分需要其他結構(如 Link-Cut Tree)或重建。
按大小合併還是按秩合併?
兩者的複雜度界相同。如果還需要知道集合的元素個數,按大小合併更方便。
使用該工具時我的資料安全嗎?
絕對安全。本工具採用 100% 純客戶端本地計算技術,所有資料與檔案均在您的本機瀏覽器記憶體中處理,絕不上傳到任何伺服器。
相關推薦工具
精選產品 tech-fun.net
探索更多獨立的實用 AI 與生產力工具
Nihongo GameBox
从五十音图基础到 JLPT N1 词汇与四字熟语,通过复古街机打字小游戏轻松锻炼假名盲打与反应力。
ResumeGPT
通过多智能体 LLM 流水线、定时职位搜寻和可复用模板,为每一个求职机会量身定制简历与求职信。
CollectMind
借助 Chrome 内置 Gemini Nano 端侧大模型,将书签变为可搜索、可总结、可对话的个人知识库,零云端上传。