-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdsets.cpp
More file actions
41 lines (37 loc) · 748 Bytes
/
dsets.cpp
File metadata and controls
41 lines (37 loc) · 748 Bytes
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
/* Your code here! */
#include "dsets.h"
void DisjointSets::addelements(int num)
{
for(int i = 0; i < num; i++)
{
nodes.push_back(-1);
}
}
int DisjointSets::find(int elem)
{
if(nodes.size() <= 0 || (size_t)elem >= nodes.size()) return 0;
else if(nodes[elem] < 0) return elem;
else
{
nodes[elem] = find(nodes[elem]);
return nodes[elem];
}
}
void DisjointSets::setunion(int a, int b)
{
if(a == b || nodes.size() == 0 || (size_t)a >= nodes.size() || (size_t)b >= nodes.size()) return;
int rootA = find(a);
int rootB = find(b);
if(nodes[rootA] <= nodes[rootB])
{
int temp = nodes[rootB];
nodes[rootB] = rootA;
nodes[rootA] += temp;
}
else
{
int temp = nodes[rootA];
nodes[rootA] = rootB;
nodes[rootB] += temp;
}
}