-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMO's Algorithm.cpp
More file actions
73 lines (62 loc) · 1.29 KB
/
Copy pathMO's Algorithm.cpp
File metadata and controls
73 lines (62 loc) · 1.29 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
/**
Topic Name: Mo's Algorithm
Name: Mohd. Raihan Uddin
iOS Developer at Twinbit limited
**/
#include <bits/stdc++.h>
using namespace std;
const int Max = 1000006;
int k, arr[Max], ans[Max], sum = 0;
struct Query
{
int index, L, R;
bool operator < (const Query &other) const
{
int block_own = L/k;
int block_other = other.L/k;
if(block_own == block_other)
return R < other.R;
return block_own < block_other;
}
} query[Max];
void add(int index)
{
sum+=arr[index];
}
void remove(int index)
{
sum-=arr[index];
}
int main()
{
int n;
cin>>n;
k = sqrt(n);
for(int i=0;i<n;i++){
cin >> arr[i];
}
int q;
cin >> q;
for(int i = 0; i < q; i++)
{
cin >> query[i].L >> query[i].R;
query[i].index = i;
}
sort(query, query+q);
for(int i = 0; i < q; i++)
{
cout<< query[i].L << " " << query[i].R << " " << query[i].index <<endl;
}
int L=0, R=-1;
for(int i=0;i<q;i++){
while(R<query[i].R) add(++R);
while(L<query[i].L) remove(L++);
while(R>query[i].R) remove(R--);
while(L>query[i].L) add(--L);
ans[query[i].index] = sum;
}
for(int i=0;i<q;i++){
cout << ans[i] << "\n";
}
return 0;
}