-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetArray.cpp
More file actions
78 lines (59 loc) · 1.99 KB
/
SetArray.cpp
File metadata and controls
78 lines (59 loc) · 1.99 KB
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
// C++ code
#include <iostream>
#include <iomanip> // for std::setw()
int FindSetCollapsing(int *subset, int i){
int root;
for (root = i; subset[root] >= 0; root = subset[root]); // 找到root
while (i != root) { // 進行collapsing
int parent = subset[i];
subset[i] = root;
i = parent;
}
return root;
}
void UnionSet(int *subset, int x, int y){
int xroot = FindSetCollapsing(subset, x),
yroot = FindSetCollapsing(subset, y);
// 用rank比較, 負越多表示set越多element, 所以是值比較小的element比較多
// xroot, yroot的subset[]一定都是負值
// x比較多element或是一樣多的時候, 以x作為root
if (subset[xroot] <= subset[yroot]) {
subset[xroot] += subset[yroot];
subset[yroot] = xroot;
}
else { // subset[xroot] > subset[yroot], 表示y比較多element
subset[yroot] += subset[xroot];
subset[xroot] = yroot;
}
}
void PrintArray(int *array, int size){
for (int i = 0; i < size; i++){
std::cout << std::setw(3) << i;
}
std::cout << std::endl;
for (int i = 0; i < size; i++){
std::cout << std::setw(3) << array[i];
}
std::cout << std::endl;
}
int main(){
const int size = 6;
int array[size] = {-1, -1, -1, -1, -1, -1};
PrintArray(array, size);
UnionSet(array, 1, 2);
std::cout << "After union(1,2):\n";
PrintArray(array, size);
UnionSet(array, 0, 2);
std::cout << "After union(0,2):\n";
PrintArray(array, size);
UnionSet(array, 3, 5);
std::cout << "After union(3,5):\n";
PrintArray(array, size);
UnionSet(array, 2, 5);
std::cout << "After union(2,5):\n";
PrintArray(array, size);
std::cout << "element(5) belongs to Set(" << FindSetCollapsing(array, 5) << ").\n";
std::cout << "After collapsing:\n";
PrintArray(array, size);
return 0;
}