forked from Ashishgup1/Competitive-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SQRT Decomposition.cpp
147 lines (132 loc) · 2.24 KB
/
SQRT Decomposition.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const int SZ=sqrt(N);
struct sqrtDecomposition
{
int L, R;
int col[SZ], contrib[SZ];
bool lazy=0;
int extra=0;
int sumBlock=0;
int lazyValue=0;
void init(int l, int r)
{
for(int i=l;i<=r;i++)
{
col[i-l]=a[i];
contrib[i]=0;
}
L=l, R=r;
extra=0;
sumBlock=0;
lazyValue=0;
}
void semiUpdate(int l, int r, int val)
{
if(l>r)
return;
if(lazy)
{
for(int i=L;i<=R;i++)
{
contrib[i-L]+=extra;
col[i-L]=lazyValue;
}
lazy=0;
extra=0;
}
for(int i=l;i<=r;i++)
{
sumBlock+=abs(val-col[i-L]);
contrib[i-L]+=abs(val-col[i-L]);
col[i-L]=val;
}
}
void fullUpdate(int val)
{
if(lazy)
{
sumBlock+=(abs(val-lazyValue)*(R-L+1));
extra+=abs(val-lazyValue);
}
else
{
for(int i=L;i<=R;i++)
{
contrib[i-L]+=abs(col[i-L]-val);
sumBlock+=abs(col[i-L]-val);
col[i-L]=val;
}
}
lazy=1;
lazyValue=val;
}
void update(int l, int r, int val)
{
if(l<=L && r>=R)
fullUpdate(val);
else
semiUpdate(max(l, L), min(r, R), val);
}
int semiQuery(int l, int r)
{
if(l>r)
return 0;
if(lazy)
{
for(int i=L;i<=R;i++)
{
contrib[i-L]+=extra;
col[i-L]=lazyValue;
}
lazy=0;
extra=0;
}
int answer=0;
for(int i=l;i<=r;i++)
answer+=contrib[i-L];
return answer;
}
int fullQuery()
{
return sumBlock;
}
int query(int l, int r)
{
if(l<=L && r>=R)
return fullQuery();
else
return semiQuery(max(l, L), min(r, R));
}
};
sqrtDecomposition blocks[SZ+5];
void init()
{
int blcks=n/SZ + 1;
int curL=1, curR=SZ;
for(int i=1;i<=blcks;i++)
{
curR=min(curR, n);
blocks[i].init(curL, curR);
curL+=SZ;
curR+=SZ;
}
}
void update(int l, int r, int x)
{
int left=(l-1)/SZ + 1;
int right=(r-1)/SZ + 1;
for(int i=left;i<=right;i++)
blocks[i].update(l, r, x);
}
int query(int l, int r)
{
int left=(l-1)/SZ + 1;
int right=(r-1)/SZ + 1;
int answer=0;
for(int i=left;i<=right;i++)
answer+=blocks[i].query(l, r);
return answer;
}
//Problem 1: https://codeforces.com/contest/444/problem/C
//Solution 1: https://codeforces.com/contest/444/submission/48887630
//Problem 2 (Updating indices of a particular set): https://codeforces.com/contest/348/problem/C
//Solution 2: https://codeforces.com/contest/348/submission/48511250