-
Notifications
You must be signed in to change notification settings - Fork 6
/
UnionFind.cpp
105 lines (95 loc) · 2 KB
/
UnionFind.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "UnionFind.h"
UnionFind::UnionFind() { }
UnionFind::~UnionFind()
{
for(std::map<int, Singleton *>::iterator iter = sets.begin();
iter != sets.end();
iter++) {
delete iter->second;
}
}
void UnionFind::MakeSet(int id)
{
if(sets.find(id) != sets.end())
{
std::cerr << "ERROR: Singleton " << id << " already exists" << std::endl;
return;
}
sets[id] = new Singleton(id);
}
int UnionFind::Find(int id)
{
if(sets.find(id) == sets.end())
MakeSet(id);
if(sets[id]->parent == id)
return id;
else
return sets[id]->parent = Find(sets[id]->parent);
}
void UnionFind::Union(int x, int y)
{
int xRoot = Find(x);
int yRoot = Find(y);
if( xRoot == yRoot)
return;
if( sets[xRoot]->rank < sets[yRoot]->rank
|| (sets[xRoot]->rank < sets[yRoot]->rank && xRoot < yRoot) )
{
sets[xRoot]->parent = yRoot;
sets[yRoot]->rank = sets[yRoot]->rank + 1;
}
else
{
sets[yRoot]->parent = xRoot;
sets[xRoot]->rank = sets[xRoot]->rank + 1;
}
}
int UnionFind::CountComponents()
{
int count = 0;
std::set<int> roots;
for(std::map<int, Singleton *>::iterator iter = sets.begin();
iter != sets.end();
iter++)
{
int root = Find(iter->first);
if( roots.find(root) == roots.end())
{
roots.insert(root);
count++;
}
}
return count;
}
void UnionFind::GetComponentRepresentatives(std::vector<int> &reps)
{
int count = 0;
std::set<int> roots;
for(std::map<int, Singleton *>::iterator iter = sets.begin();
iter != sets.end();
iter++)
{
int root = Find(iter->first);
if( roots.find(root) == roots.end())
{
roots.insert(root);
reps.push_back(root);
count++;
}
}
}
void UnionFind::GetComponentItems(int rep, std::vector<int> &items)
{
int count = 0;
for(std::map<int, Singleton *>::iterator iter = sets.begin();
iter != sets.end();
iter++)
{
int root = Find(iter->first);
if(rep == root)
{
items.push_back(iter->first);
count++;
}
}
}