-
Notifications
You must be signed in to change notification settings - Fork 1
/
sets.cpp
80 lines (72 loc) · 1.3 KB
/
sets.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
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#include <unordered_map>
#define MAX_N 1000001
using namespace std;
typedef long long lld;
int numComponents;
struct Node
{
int parent;
int rank;
};
unordered_map<int,Node> DSU;
inline void MakeSet(int x)
{
DSU[x].parent = x;
DSU[x].rank = 0;
}
inline int Find(int x)
{
if (DSU[x].parent == x) return x;
DSU[x].parent = Find(DSU[x].parent);
return DSU[x].parent;
}
inline void Union(int x, int y)
{
int xRoot = Find(x);
int yRoot = Find(y);
if (xRoot == yRoot) return;
numComponents--;
if (DSU[xRoot].rank < DSU[yRoot].rank)
{
DSU[xRoot].parent = yRoot;
}
else if (DSU[xRoot].rank > DSU[yRoot].rank)
{
DSU[yRoot].parent = xRoot;
}
else
{
DSU[yRoot].parent = xRoot;
DSU[xRoot].rank++;
}
}
int main()
{
numComponents = 4, m = 8;
MakeSet(1);
MakeSet(2);
MakeSet(3);
MakeSet(4);
Union(1, 2);
Union(2, 1);
Union(2, 3);
Union(1, 3);
Union(1,2);
int res=Find(2);
printf("%d",res);
printf("%d\n",numComponents);
return 0;
}