-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquickunionunionfind.cpp
83 lines (76 loc) · 1.76 KB
/
quickunionunionfind.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
#include "quickunionunionfind.h"
#include "iostream"
#include "vector"
int QuickUnionUnionFind::Qroot(int i)
{
while(i != id.at(i))
{
id.at(i) = id.at(id.at(i));
i = id[i];
}
return i;
}
QuickUnionUnionFind::QuickUnionUnionFind(int N)
{
id.resize(N);
sz.resize(N);
for(int i = 0; i< id.size();i++)
{
id.at(i) = i;
sz.at(i) = 1;
}
}
bool QuickUnionUnionFind::Qconnected(int p, int q)
{
return Qroot(p) == Qroot(q);
}
void QuickUnionUnionFind::disconnectCell(int p)
{
std::vector<int> otherConnectedCells;
int newroot = 0;
bool rerouted = false;
for(int i = 0; i < id.size();i++)
{
if(Qroot(i) == Qroot(p) && i != p)
{
otherConnectedCells.push_back(i);
if(id.at(i) == p && !rerouted)
{
id.at(i) == i;
newroot = i;
rerouted = true;
}
if(id.at(i) == p && rerouted)
{
id.at(i) = newroot;
}
}
}
std::cout << p << "is connected to " << otherConnectedCells.size() << " other cells" << std::endl;
}
void QuickUnionUnionFind::Qunion(int p, int q)
{
int i = Qroot(p);
int j = Qroot(q);
if(i == j)//p and q are already connected, root is the same
{
return;
}
if(sz.at(i) < sz.at(j))//is the size of the tree at size(0) smaller then size at the root of q?
{
id.at(i) = j;
sz.at(j) += sz.at(i);
}
else
{
id.at(j) = i;
sz.at(i) += sz.at(j);
}
// std::cout << "all indexes in id:"<<std::endl;
// for(int i = 0;i < id.size();i++)
// {
// std::cout << id.at(i) << " ";
// if(i % 9 == 0)
// std::cout << std::endl;
// }
}