-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathex.1.16.cpp
66 lines (55 loc) · 1.61 KB
/
ex.1.16.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
// ex.1.16
// en: Show how to modify Program 1.3 to implement fullpath
// compression, where we complete each union operation by making every
// node that we touch point to the root of the new tree.
// ru: Покажите как необходимо изменить программу 1.3, чтобы
// реализовать полное сжатие пути, при котором после каждой операции
// объединение все обработанные узлы указывают на корень нового
// дерева.
#include <array>
#include <iostream>
static const int N = 1000;
int main() {
std::array<int, N> id;
std::array<int, N> sz;
for (int i = 0; i < N; ++i) {
id[i] = i;
sz[i] = 1;
}
int p, q;
while (std::cin >> p >> q) {
// find
int i, j;
for (i = p; i != id[i]; i = id[i])
;
for (j = q; j != id[j]; j = id[j])
;
if (i == j) continue;
// check size of tree & join with smallest
int root;
if (sz[i] < sz[j]) {
id[i] = j;
sz[j] += sz[i];
root = j;
} else {
id[j] = i;
sz[i] += sz[j];
root = i;
}
// path compression
i = p;
while (i != id[i]) {
int parent = id[i];
id[i] = root;
i = parent;
}
j = q;
while (j != id[j]) {
int parent = id[j];
id[j] = root;
j = parent;
}
std::cout << ' ' << p << ' ' << q << '\n';
}
return 0;
}