forked from rudi8848/data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.3.join_database.cpp
More file actions
91 lines (80 loc) · 1.95 KB
/
2.3.join_database.cpp
File metadata and controls
91 lines (80 loc) · 1.95 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
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <vector>
class Database
{
public:
Database(unsigned numTables) {
//std::cout << __PRETTY_FUNCTION__ << std::endl;
_tables.resize(numTables + 1);
_rank.resize(numTables + 1);
_parent.resize(numTables + 1);
_maxSize = 0;
for (int i = 1; i < numTables + 1; ++i) {
std::cin >> _tables[i];
if (_tables[i] > _maxSize)
_maxSize = _tables[i];
makeSet(i);
}
}
~Database(){}
void join(unsigned i, unsigned j) {
//std::cout << __PRETTY_FUNCTION__ << std::endl;
unsigned i_id, j_id;
i_id = find(i);
j_id = find(j);
if (i_id == j_id)
return;
if (_rank[i_id] > _rank[j_id]) {
_parent[j_id] = i_id;
_tables[i_id] += _tables[j_id];
_tables[j_id] = 0;
}
else {
_parent[i_id] = j_id;
if (_rank[i_id] == _rank[j_id])
_rank[j_id] += 1;
_tables[j_id] += _tables[i_id];
_tables[i_id] = 0;
}
unsigned max = std::max(_tables[j_id], _tables[i_id]);
_maxSize = std::max(max, _maxSize);
}
unsigned maxSize() { return _maxSize; }
void print() {
for (int i = 1; i < _tables.size(); ++i) {
std::cout << "tables [" << _tables[i] << "]\tparent ["
<< _parent[i] << "]\trank [" << _rank[i] << "]"<< std::endl;
}
std::cout << "----------------------------" << std::endl;
}
private:
void makeSet(unsigned i) {
//std::cout << __PRETTY_FUNCTION__ << std::endl;
_parent[i] = i;
_rank[i] = 0;
}
unsigned find(unsigned i) {
//std::cout << __PRETTY_FUNCTION__ << std::endl;
while (i != _parent[i])
i = _parent[i];
return i;
}
unsigned _maxSize;
std::vector<unsigned> _tables;
std::vector<unsigned> _parent;
std::vector<unsigned> _rank;
};
int main(void) {
int numTables, numRequests;
std::cin >> numTables >> numRequests;
Database database(numTables);
//database.print();
for (int i = 0; i < numRequests; ++i) {
int dest, src;
std::cin >> dest >> src;
database.join(dest, src);
//database.print();
std::cout << database.maxSize() << std::endl;
}
return 0;
}