diff options
| author | Gloria Mundi <gloria@gloria-mundi.eu> | 2024-11-16 01:24:14 +0100 |
|---|---|---|
| committer | Gloria Mundi <gloria@gloria-mundi.eu> | 2024-11-16 01:24:14 +0100 |
| commit | 98567ec798aa8ca2cfbcb85c774dd470f30e30d4 (patch) | |
| tree | 5113d5cc24d1ad5f93810b6442ce584a36950dc8 /content/datastructures/unionFind.cpp | |
| parent | ad3856a6b766087df0036de0b556f4700a6498c9 (diff) | |
| parent | 8d11c6c8213f46f0fa19826917c255edd5d43cb1 (diff) | |
mzuenni tests
Diffstat (limited to 'content/datastructures/unionFind.cpp')
| -rw-r--r-- | content/datastructures/unionFind.cpp | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/content/datastructures/unionFind.cpp b/content/datastructures/unionFind.cpp new file mode 100644 index 0000000..dd5a569 --- /dev/null +++ b/content/datastructures/unionFind.cpp @@ -0,0 +1,26 @@ +// unions[i] >= 0 => unions[i] = parent +// unions[i] < 0 => unions[i] = -size +vector<int> unions; + +void init(int n) { //Initialisieren + unions.assign(n, -1); +} + +int findSet(int a) { // Pfadkompression + if (unions[a] < 0) return a; + return unions[a] = findSet(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; +} + +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[findSet(a)]; +} |
