-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSquare_Root_Decomposition.cpp
More file actions
74 lines (74 loc) · 1.58 KB
/
Copy pathSquare_Root_Decomposition.cpp
File metadata and controls
74 lines (74 loc) · 1.58 KB
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
template <typename T>
struct sqrt_decomposition
{
int n, len;
vector<T> arr, block;
sqrt_decomposition(int size)
{
n = size;
len = sqrt(n) + 1;
arr.resize(n, 0);
block.resize(len, 0);
}
sqrt_decomposition(vector<T> &a)
{
n = a.size();
len = sqrt(n) + 1;
arr = a;
block.resize(len, 0);
for (int i = 0; i < n; ++i)
{
block[i / len] += arr[i];
}
}
void update(int idx, T val)
{
block[idx / len] -= arr[idx];
arr[idx] = val;
block[idx / len] += arr[idx];
}
T query(int r)
{
if (r < 0)
return 0;
T res = 0;
for (int i = 0; i < r / len; ++i)
{
res += block[i];
}
for (int i = (r / len) * len; i <= r; ++i)
{
res += arr[i];
}
return res;
}
T query(int l, int r)
{
if (l > r)
return 0;
if(block[l / len] == block[r / len]) {
T res = 0;
for (int i = l; i <= r; ++i)
{
res += arr[i];
}
return res;
}
T res = 0;
int start_block = l / len;
int end_block = r / len;
for (int i = start_block + 1; i < end_block; ++i)
{
res += block[i];
}
for (int i = l; i < (start_block + 1) * len; ++i)
{
res += arr[i];
}
for (int i = end_block * len; i <= r; ++i)
{
res += arr[i];
}
return res;
}
};