-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathkruskal.cpp
More file actions
98 lines (84 loc) · 2.61 KB
/
kruskal.cpp
File metadata and controls
98 lines (84 loc) · 2.61 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
92
93
94
95
96
97
98
/*
scp, The sequential clique percolation algorithm.
Copyright (C) 2011 Aalto University
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#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;
}