-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathsqrtdecomposition.cpp
More file actions
90 lines (80 loc) · 1.61 KB
/
sqrtdecomposition.cpp
File metadata and controls
90 lines (80 loc) · 1.61 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//sqrt decomposition(sum queries)
#include <bits/stdc++.h>
#include<cmath>
#define pb push_back
#define ll long long
#define ull unsigned long long
#define deb(x) cerr<<#x<<" "<<x<<"\n"
using namespace std;
int n;
vector<int> b;
vector<int> a;
int len;
// query ranges are form 0 to n-1
int solve(int l, int r){
int sum =0 ;
for(int i = l ; i<=r ;){
if(i%len == 0 && i+len-1 <=r){
sum += b[i/len];
i += len;
}
else{
sum += a[i];
++i;
}
}
return sum;
}
//another way to anwer queries but it is more efficient this way as we are not doing so many divisions
int solve2(int l , int r){
int c_l = l/len;
int c_r = r/len;
int ans = 0;
if(c_l == c_r){
for(int i= l;i<=r;i++){
ans += a[i];
}
}
else{
for(int i = l,end = (c_l+1)*len-1;i<=end;i++){
ans += a[i];
}
for(int i= c_l+1;i<=c_r-1;++i){
ans += b[i];
}
for(int i=c_r*len;i<=r;++i){
ans += a[i];
}
}
return ans;
}
int main(){
//fast;
cin >> n;
//plus 1 is important by the fact that sqrt(9) - > 3 and sqrt(15) -> 3 as it will be turncated so we need to store one additional element in each block more than sqrt(n)
len = (int)sqrt(n+.0)+1;
deb(len);
b.resize(len);
a.resize(n);
for(int i =0 ; i<n;i++){
cin >> a[i];
}
for(int i = 0 ; i< n;i++){
b[i/len] += a[i];
}
//to check it looks
// it generally contains property of blocks of size sqrt(n) 0 to s-1 i.e s=(sqrt(n))
// the last block may contain fewer elements
for(int i =0 ; i < len;i++){
deb(b[i]);
}
//anwering queries
int query;
cin >> query;
while(query -- ){
int l , r;
cin >> l >> r;
cout<<solve2(l,r)<<"\n";
}
return 0;
}