forked from Ashishgup1/Competitive-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DSU (Disjoint Set Union).cpp
99 lines (78 loc) · 1.11 KB
/
DSU (Disjoint Set Union).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
Without Struct:
int connected;
int root[N], sz[N];
void init()
{
for(int i=1;i<=n;i++)
{
root[i]=i;
sz[i]=1;
}
connected=n;
}
int rt(int k)
{
while(k!=root[k])
{
root[k]=root[root[k]];
k=root[k];
}
return k;
}
void merge(int u, int v)
{
int rt1=rt(u);
int rt2=rt(v);
if(rt1==rt2)
return;
connected--;
if(sz[rt1]>sz[rt2])
swap(rt1, rt2);
sz[rt2]+=sz[rt1];
sz[rt1]=0;
root[rt1]=root[rt2];
}
---
Struct Implementation:
struct DSU
{
int connected;
int par[N], sz[N];
DSU() {}
DSU(int n)
{
for(int i=1;i<=n;i++)
{
par[i]=i;
sz[i]=1;
}
connected=n;
}
int getPar(int k)
{
while(k!=par[k])
{
par[k]=par[par[k]];
k=par[k];
}
return k;
}
int getSize(int k)
{
return sz[getPar(k)];
}
void unite(int u, int v)
{
int par1=getPar(u), par2=getPar(v);
if(par1==par2)
return;
connected--;
if(sz[par1]>sz[par2])
swap(par1, par2);
sz[par2]+=sz[par1];
sz[par1]=0;
par[par1]=par[par2];
}
};
//Problem 1 (DSU + Divide and Conquer): https://codeforces.com/contest/813/problem/F
//Solution 1: https://codeforces.com/contest/813/submission/48548930