-
Notifications
You must be signed in to change notification settings - Fork 1
/
disjointset.cpp
54 lines (47 loc) · 1.36 KB
/
disjointset.cpp
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
/// File: disjointset.cpp
/// A data structure used to perform Union-Find operations as required
/// in Kruskal’s Minimum Cost Spanning Tree algorithm.
/// This data structure is used for very efficient look-up (Find) to determine which set an element
/// is in. It also provides a very efficient way to join (Union) two sets together.
#include "disjointset.h"
#include <iostream>
using namespace std;
/// Constructor which sets the size of this DisjointSet.
DisjointSet::DisjointSet(int N) {
this->N = N;
id = new int[N];
size = new int[N];
for (int i = 0; i < N; i++) {
id[i] = i;
size[i] = 1;
}
}
/// Destructor.
DisjointSet::~DisjointSet() {
delete[] size;
delete[] id;
}
/// Returns the index of the parent set of the element in the parameter.
int DisjointSet::find(int i) {
while (i != id[i]) {
id[i] = id[id[i]];
i = id[i];
}
return i;
}
/// Creates the union of two disjoint sets whose indexes are passed as parameters.
void DisjointSet::join(int p, int q) {
int i = find(p);
int j = find(q);
if (size[i] < size[j]) {
id[i] = j;
size[j] += size[i];
} else {
id[j] = i;
size[i] += size[j];
}
}
/// Returns true if the two indexes passed as parameters are in the same set.
bool DisjointSet::sameComponent(int p, int q) {
return find(p) == find(q);
}