summaryrefslogtreecommitdiff
path: root/content/datastructures
diff options
context:
space:
mode:
Diffstat (limited to 'content/datastructures')
-rw-r--r--content/datastructures/datastructures.tex9
-rw-r--r--content/datastructures/unionFind.cpp42
2 files changed, 26 insertions, 25 deletions
diff --git a/content/datastructures/datastructures.tex b/content/datastructures/datastructures.tex
index c4bd312..1c51475 100644
--- a/content/datastructures/datastructures.tex
+++ b/content/datastructures/datastructures.tex
@@ -123,11 +123,12 @@
\begin{algorithm}{Union-Find}
\begin{methods}
- \method{init}{legt $n$ einzelne Unions an}{n}
- \method{findSet}{findet den Repräsentanten}{\log(n)}
- \method{unionSets}{vereint 2 Mengen}{\log(n)}
+ \method{UnionFind}{legt $n$ einzelne Elemente an}{n}
+ \method{find}{findet den Repräsentanten}{\log(n)}
+ \method{link}{vereint 2 Mengen}{\log(n)}
\method{size}{zählt Elemente in Menge, die $a$ enthält}{\log(n)}
- \method{m\*findSet + n\*unionSets}{Folge von Befehlen}{n+m\*\alpha(n)}
+ \method{add}{fügt neues einzelnes Element ein}{1}
+ \method{m\*find + n\*link}{Folge von Befehlen}{n+m\*\alpha(n)}
\end{methods}
\sourcecode{datastructures/unionFind.cpp}
\end{algorithm}
diff --git a/content/datastructures/unionFind.cpp b/content/datastructures/unionFind.cpp
index dd5a569..36a4b45 100644
--- a/content/datastructures/unionFind.cpp
+++ b/content/datastructures/unionFind.cpp
@@ -1,26 +1,26 @@
-// unions[i] >= 0 => unions[i] = parent
-// unions[i] < 0 => unions[i] = -size
-vector<int> unions;
+struct UnionFind {
+ vector<int> unions; // unions[i] = parent or unions[i] = -size
-void init(int n) { //Initialisieren
- unions.assign(n, -1);
-}
+ UnionFind(int n): unions(n, -1) {}
-int findSet(int a) { // Pfadkompression
- if (unions[a] < 0) return a;
- return unions[a] = findSet(unions[a]);
-}
+ int find(int a) {
+ return unions[a] < 0 ? a : unions[a] = find(unions[a]);
+ }
-void linkSets(int a, int b) { // Union by size.
- if (unions[b] > unions[a]) swap(a, b);
- unions[b] += unions[a];
- unions[a] = b;
-}
+ bool link(int a, int b) {
+ if ((a = find(a)) == (b = find(b))) return false;
+ if (unions[b] > unions[a]) swap(a, b);
+ unions[b] += unions[a];
+ unions[a] = b;
+ return true;
+ }
-void unionSets(int a, int b) { // Diese Funktion aufrufen.
- if (findSet(a) != findSet(b)) linkSets(findSet(a), findSet(b));
-}
+ int size(int a) {
+ return -unions[find(a)];
+ }
-int size(int a) {
- return -unions[findSet(a)];
-}
+ int add() {
+ unions.push_back(-1);
+ return ssize(unions) - 1;
+ }
+};