-
Notifications
You must be signed in to change notification settings - Fork 0
/
kruskal.cpp
79 lines (69 loc) · 1.86 KB
/
kruskal.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
#include "kruskal.h"
#include <iostream>
KruskalTree::KruskalTree() : largestComponentSize(1) {}
size_t KruskalTree::add()
{
size_t vecSize = table.size();
table.push_back(vecSize);
commSizes.push_back(1);
return vecSize;
}
size_t KruskalTree::add(const size_t root)
{
if (root <= table.size())
{
table.push_back(root);
findRoot(table[table.size() - 1]);
commSizes.push_back(1);
}
else
add();
return table.size() - 1;
}
void KruskalTree::connect(const size_t first, const size_t second)
{
if (first < table.size() && second < table.size() && !inSameSet(first, second)) // After the call inSameSet table[first] and table[second] point to their real roots
{
commSizes[table[second]] += commSizes[table[first]];
if (commSizes[table[second]] > largestComponentSize)
largestComponentSize = commSizes[table[second]];
table[table[first]] = table[table[second]];
}
}
bool KruskalTree::inSameSet(const size_t first, const size_t second)
{
if (findRoot(first) == findRoot(second))
return true;
else
return false;
}
size_t KruskalTree::findRoot(const size_t source)
{
size_t root = table[source];
while (root != table[root])
{
root = table[root];
}
size_t currentRoot = source;
while (currentRoot != root)
{
size_t oldRoot = table[currentRoot];
table[currentRoot] = root;
currentRoot = oldRoot;
}
return root;
}
size_t KruskalTree::size(const size_t source)
{
return commSizes[findRoot(source)];
}
size_t KruskalTree::getLargestComponentSize() const
{
return largestComponentSize;
}
void KruskalTree::printTree(std::ostream & file) const
{
for (int i = 0; i < table.size(); i++)
file << i << ": " << table[i] << " s: " << commSizes[i] << std::endl;
file << std::endl;
}