-
Notifications
You must be signed in to change notification settings - Fork 2
/
Disjoint Set Union
83 lines (68 loc) · 1.21 KB
/
Disjoint Set Union
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
//prac prob: https://codeforces.com/problemset/problem/566/D
//solution : https://codeforces.com/contest/566/submission/277054768
const int N = 1e6+7;
int p[N];
int Find_Parent(int node){
if(p[node]==node)
return node ;
return p[node]=Find_Parent(p[node]) ;
}
void Union(int u,int v){
p[Find_Parent(u)]=Find_Parent(v) ;
}
/// dsu in range.
/// this is quite rare case but interesting.
int tree[N];
void update(int idx, int x,int n)
{
if(vis[idx])
{
return;
}
vis[idx]=1;
while(idx<=n)
{
tree[idx]+=x;
idx+=(idx&-idx);
}
}
int query(int idx)
{
int sum=0;
while(idx>0)
{
sum+=tree[idx];
idx-=(idx&-idx);
}
return sum ;
}
int ask(int l,int r)
{
return query(r) - query(l) ;
}
int p[N];
int Find_Parent(int node)
{
if(p[node]==node)
return node ;
return p[node]=Find_Parent(p[node]) ;
}
void Union(int u,int v)
{
p[Find_Parent(u)]=Find_Parent(v) ;
}
void RangeUnion(int l, int r)
{
if(l>r or l==r or ask(l, r)==r-l)
{
return;
}
Union(l, r);
int md = (l+r)/2;
RangeUnion(l, md);
RangeUnion(md+1, r);
if(md+1<=r)
{
update(md+1, +1, n);
}
}