-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathD.cpp
executable file
·94 lines (79 loc) · 1.54 KB
/
D.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
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
class FenwickTree {
private:
vector<long long> ft;
public:
FenwickTree(int n) : ft(n + 1) {}
int LSB(int x) {
return x & -x;
}
void update(int i, int val) {
add(i, val - rsq(i, i));
}
void add(int i, int val) {
while (i < ft.size()) {
ft[i] += val;
i += LSB(i);
}
}
long long rsq(int i) {
long long sum = 0;
while (i > 0) {
sum += ft[i];
i -= LSB(i);
}
return sum;
}
long long rsq(int l, int r) {
return rsq(r) - rsq(l - 1);
}
};
int sign(int i) {
return (i & 1) ? 1 : -1;
}
long long candies(int N, int Q, vector<int>& A) {
long long sum = 0;
vector<FenwickTree> ft(2, FenwickTree(N));
// helper function to update element at position i to val
auto update = [&](int i, int val) {
ft[0].update(i, sign(i) * val);
ft[1].update(i, sign(i) * i * val);
};
// helper function to query sum of range [l, r]
auto query = [&](int l, int r) {
long long s, ms;
s = ft[0].rsq(l, r);
ms = ft[1].rsq(l, r);
return sign(l) * (ms - (l - 1) * s);
};
// initialize fenwick trees
for (int i = 1; i <= N; i++)
update(i, A[i - 1]);
// process queries
while (Q--) {
char c;
int x, y;
cin >> c >> x >> y;
if (c == 'U')
update(x, y);
else
sum += query(x, y);
}
return sum;
}
int main() {
int T;
cin >> T;
for (int x = 1; x <= T; x++) {
int N, Q;
cin >> N >> Q;
vector<int> A(N);
for (int i = 0; i < N; i++)
cin >> A[i];
cout << "Case #" << x << ": " << candies(N, Q, A) << endl;
}
return 0;
}