-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek2merge.cpp
84 lines (71 loc) · 2.07 KB
/
week2merge.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
79
80
81
82
83
84
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::max;
using std::vector;
struct DisjointSetsElement {
int size, parent, rank;
DisjointSetsElement(int size = 0, int parent = -1, int rank = 0):
size(size), parent(parent), rank(rank) {}
};
struct DisjointSets {
int size;
int max_table_size;
vector <DisjointSetsElement> sets;
DisjointSets(int size): size(size), max_table_size(0), sets(size) {
for (int i = 0; i < size; i++)
sets[i].parent = i;
}
int getParent(int table) {
// find parent and compress path
if(sets[table].parent != table)
sets[table].parent = getParent(sets[table].parent);
return sets[table].parent;
}
void merge(int destination, int source) {
int realDestination = getParent(destination);
int realSource = getParent(source);
if (realDestination != realSource) {
// merge two components
// use union by rank heuristic
// update max_table_size
if(sets[realDestination].rank < sets[realSource].rank) {
sets[realDestination].parent = realSource;
sets[realSource].size += sets[realDestination].size;
sets[realDestination].size = 0;
}
else {
sets[realSource].parent = realDestination;
sets[realDestination].size += sets[realSource].size;
sets[realSource].size = 0;
if(sets[realDestination].rank == sets[realSource].rank) {
sets[realDestination].rank++;
}
}
max_table_size = max(max(max_table_size, sets[realDestination].size), sets[realSource].size);
}
}
};
int main() {
int n, m;
cin >> n >> m;
DisjointSets tables(n);
for (auto &table: tables.sets) {
cin >> table.size;
tables.max_table_size = max(tables.max_table_size, table.size);
}
for (int i = 0; i < m; i++) {
int destination, source;
cin >> destination >> source;
--destination;
--source;
tables.merge(destination, source);
cout << tables.max_table_size << endl;
}
return 0;
}