-
Notifications
You must be signed in to change notification settings - Fork 1
/
UnionFind.h
81 lines (69 loc) · 1.67 KB
/
UnionFind.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#pragma once
#include<iostream>
#include<utility>
class UnionFind
{
private:
int elements;
int *UnionFindArray;
public:
UnionFind() = delete;
UnionFind(int elements);
~UnionFind();
int root(int element);
void join( int x, int y );
void printStructureArray();
void printSet(int x);
};
UnionFind::UnionFind(int elements)
{
this->elements = elements;
UnionFindArray = new int[elements];
for (int i = 0; i < elements; i++)
UnionFindArray[i] = -1;
}
UnionFind::~UnionFind()
{
delete[]UnionFindArray;
}
int UnionFind::root(int element){
int root = element;
/* Find root */
while(UnionFindArray[root] >= 0)
root = UnionFindArray[root];
/* Compress path to root */
while(UnionFindArray[element] >= 0) {
int tmp = UnionFindArray[element];
UnionFindArray[element] = root;
element = tmp;
}
return root;
}
void UnionFind::join( int x, int y ) {
x = root(x);
y = root(y);
if(x != y) {
if(UnionFindArray[x] < UnionFindArray[y]) {
UnionFindArray[x] += UnionFindArray[y];
UnionFindArray[y] = x;
}
else {
UnionFindArray[y] += UnionFindArray[x];
UnionFindArray[x] = y;
}
}
}
void UnionFind::printStructureArray(){
using namespace std;
for (int i = 0; i < elements; i++)
cout << UnionFindArray[i] << " ";
cout << endl;
}
void UnionFind::printSet(int element){
using namespace std;
int r = root(element);
cout << "Set containing " << element << ": " << endl;
for (int i = 0; i < elements; i++)
if(root(i) == r) cout << i << " ";
cout << endl;
}