-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisjointSet.cpp
78 lines (70 loc) · 2.2 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "disjointSet.h"
#include <iostream>
DisjointSet createDSU(int size){
DisjointSet set;
set.parents.resize(size);
set.ranks.resize(size);
set.size = size;
for (int i = 0; i < size; i++)
{
set.parents[i] = i;
set.ranks[i] = 0;
}
return set;
}
int findDSU(DisjointSet * set, int child){
// It'll return the child's representative
// Verifing if it has a parent. If they are not identical, so it has a parent.
if(child != set->parents[child]){
/** Path Compression:
* set->parents[child] = findDSU(set, set->parents[child]);
*/
/** Standard mode
* return findDSU(set, set->parents[child]);
*/
return findDSU(set, set->parents[child]);
}
return set->parents[child];
}
void printDSU(DisjointSet set){
std::cout << "Size: " << set.size << std::endl;
std::cout << " -- Ranks -- " << std::endl;
for(int i = 0; i < set.size; i++){
std::cout << set.ranks[i] << " ";
}
std::cout << std::endl;
std::cout << " -- Parents -- " << std::endl;
for(int i = 0; i < set.size; i++){
std::cout << set.parents[i] << " ";
}
std::cout << std::endl;
}
char unionDSU(DisjointSet * set, int child1, int child2){
int representative1 = findDSU(set, child1);
int representative2 = findDSU(set, child2);
/*If they arent identical, so they are in different sets*/
if(representative1 != representative2){
/** Standard version (without ranks):
* set->parents[representative1] = representative2;
*/
/** Ranks as size
* if(set->ranks[representative1] < set->ranks[representative2]){
* std::swap(representative1, representative2);
* }
* set->parents[representative2] = representative1;
* set->ranks[representative1] += set->ranks[representative2];
*/
/** Ranks as depth
* if(set->ranks[representative1] < set->ranks[representative2]){
* std::swap(representative1, representative2);
* }
* set->parents[representative2] = representative1;
* if(set->ranks[representative1] == set->ranks[representative2])
* set->ranks[representative1] += 1;
*/
set->parents[representative1] = representative2;
return 1;
}
/*it returns 1, if it made a union; otherwise, it'll return 0*/
return 0;
}