summaryrefslogtreecommitdiff
path: root/datastructures/unionFind.cpp
blob: 99b19fc86c3e3388872127d6a09f456084d9e9d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Laufzeit: O(n*alpha(n))
// "height" ist obere Schranke für die Höhe der Bäume. Sobald
// Pfadkompression angewendet wurde, ist die genaue Höhe nicht mehr
// effizient berechenbar.
vector<int> parent; // Initialisiere mit Index im Array.
vector<int> height; // Initialisiere mit 0.

int findSet(int n) { // Pfadkompression
	if (parent[n] != n) parent[n] = findSet(parent[n]);
	return parent[n];
}

void linkSets(int a, int b) { // Union by rank.
	if (height[a] < height[b]) parent[a] = b;
	else if (height[b] < height[a]) parent[b] = a;
	else {
		parent[a] = b;
		height[b]++;
}}

void unionSets(int a, int b) { // Diese Funktion aufrufen.
	if (findSet(a) != findSet(b)) linkSets(findSet(a), findSet(b));
}