素集合データ構造 (Union-Find)
ランクによる結合と経路圧縮の効果を比較するツリー可視化。
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| parent | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
このツールについて
Union-Find(素集合データ構造、DSU)は、互いに重ならない集合の集まりを管理し、「この 2 つの要素は同じ集合に属するか?」という問いにとても速く答えます。各集合は親へのポインタでできた木で、その根が集合の代表元です。find(x) は根までさかのぼり、union(x, y) は一方の根をもう一方の根の下につなぎます。
2 つの小さな最適化で、ほぼ定数時間になります。ランクによる併合(union by rank)は低い木を高い木の下につなぎ、経路圧縮は find でたどった経路上のすべてのノードを直接根に向けます。このラボではそれぞれをオン/オフし、木と「最も高い木」のカウンターの変化を見られます。
使い方 素集合データ構造 (Union-Find)
- はじめは各要素がそれぞれ単独の集合です。2 つの要素を入力して Union を、1 つを入力して Find をクリックします。
- 親への矢印に注目します。union は一方の根からもう一方へ新しい矢印を引き、find は根までの経路をハイライトします。
- 両方の最適化をオフにして、「最悪ケースの鎖を作る」で高い木を作ります。
- 経路圧縮をオンにして 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 を指す
5 つの言語による実装
同じアルゴリズムを 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 以下です。最適化がなければ、1 回の find に O(n) かかることがあります。
主な用途
- クラスカル法による最小全域木:両端が異なる集合にあるときだけ辺を追加します。
- グラフを保持せずに、辺のストリームから連結成分を求めます。
- 無向グラフに辺を追加するときの閉路検出。
- 同値なものをまとめる処理:アカウントの統合、画像のセグメンテーション、パーコレーション。
よくある質問
ツールの仕様やセキュリティに関する疑問にお答えします。
ランクとは正確には何ですか?
木の高さの上限です。同じランクの木どうしを併合したときにだけ増えます。経路圧縮で実際の高さが低くなることはあっても、ランクが減ることはありません。
Union-Find で集合を分割できますか?
できません。対応しているのは併合だけです。削除や分割には、link-cut 木のような別の構造を使うか、作り直す必要があります。
サイズによる併合とランクによる併合、どちらがよいですか?
どちらも同じ計算量の上限になります。集合の大きさも必要なら、サイズ(要素数)を使うと便利です。
入力したデータやファイルは安全ですか?
完全に安全です。本ツールは100%ブラウザ内部で動作し、データがサーバーに送信されることは一切ありません。
関連ツール
注目のプロダクト tech-fun.net
便利なAI・生産性ツールとゲーム
Nihongo GameBox
Master Japanese typing, Kana, and JLPT N5–N1 vocabulary through interactive retro arcade games.
ResumeGPT
Tailors CVs and cover letters to every job opportunity with a multi-agent LLM pipeline, job tracking, and scheduled discovery.
CollectMind
Turns your bookmarks into a searchable AI knowledge base — entirely on-device, powered by Chrome's built-in Gemini Nano.