-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMo's Algo.cpp
97 lines (75 loc) · 1.45 KB
/
Mo's Algo.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
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int MAX = 1e6 + 10;
int BLOCK_SIZE, ar[MAX];
ll sum, ans[MAX];
struct Node
{
int l, r, id;
Node() {};
Node(int _l, int _r, int _id)
{
l = _l;
r = _r;
id = _id;
}
bool operator<(const Node &b) const
{
if( (l / BLOCK_SIZE) != (b.l / BLOCK_SIZE) )
return (l / BLOCK_SIZE) < (b.l / BLOCK_SIZE);
return r < b.r;
}
} qr[MAX];
void add(int x)
{
sum += ar[x];
}
void del(int x)
{
sum -= ar[x];
}
int main()
{
int n, m, l, r;
scanf("%d %d", &n, &m);
BLOCK_SIZE = sqrt(n);
for(int i = 0; i < n; ++i)
scanf("%d", &ar[i]);
for(int i = 0; i < m; ++i)
{
scanf("%d %d", &l, &r);
qr[i] = Node(l, r, i);
}
sort(qr, qr+m);
int L, R, cur_L = 0, cur_R = 0;
for(int i = 0; i < m; ++i)
{
L = qr[i].l;
R = qr[i].r;
while(cur_L < L)
{
del(cur_L);
++cur_L;
}
while(cur_L > L)
{
add(cur_L-1);
cur_L--;
}
while(cur_R <= R)
{
add(cur_R);
cur_R++;
}
while(cur_R > R+1)
{
del(cur_R-1);
cur_R--;
}
ans[ qr[i].id ] = sum;
}
for(int i = 0; i < m; ++i)
printf("%lld\n", ans[i]);
return 0;
}