-
Notifications
You must be signed in to change notification settings - Fork 0
/
1646 - Static Range Sum Queries.cpp
75 lines (60 loc) · 1.36 KB
/
1646 - Static Range Sum Queries.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
#include <bits/stdc++.h>
using namespace std;
class Solution {
protected:
int n, q;
vector<int> a;
Solution() {
cin >> n >> q;
a.assign(n, 0);
for (auto &i : a) cin >> i;
}
public:
virtual void solve() = 0;
};
class SegmentTreeSolution : public Solution {
private:
vector<long long> pref;
public:
SegmentTreeSolution() {
pref.assign(n + 1, 0);
for (int i = 1; i < n + 1; i++) pref[i] = pref[i - 1] + a[i - 1];
}
void solve() {
for (int i = 0; i < q; i++) {
int l, r;
cin >> l >> r;
cout << pref[r] - pref[l - 1] << "\n";
}
}
};
class FenwickTreeSolution : public Solution {
private:
vector<long long> bit;
int lsb(int i) { return i & -i; }
int parent(int i) { return i + lsb(i); }
long long pref(int i) { return bit[i] + (i ? pref(i - lsb(i)) : 0); }
public:
FenwickTreeSolution() {
bit.assign(n + 1, 0);
for (int i = 1; i <= n; i++) {
bit[i] += a[i - 1];
bit[parent(i)] += bit[i];
}
}
void solve() {
for (int i = 0; i < q; i++) {
int l, r;
cin >> l >> r;
cout << pref(r) - pref(l - 1) << "\n";
}
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
Solution *sol = new FenwickTreeSolution();
sol->solve();
return 0;
}