-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathRSQ.cpp
78 lines (69 loc) · 1.35 KB
/
RSQ.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
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+5 , M = (N<<2), OO = 1000000007;
const double EPS = 0.00001;
#define lft(x) (x<<1)
#define rit(x) ((x<<1)|1)
#define med(l, r) ((l+r)>>1)
int n, q, t, a, b;
int A[N];
int tr[N<<2];
void build(int p, int l, int r){ //O(n*log(n))
if(l==r)
tr[p] = A[l];
else{
build(lft(p), l, med(l, r));
build(rit(p), med(l, r)+1, r);
tr[p] = tr[lft(p)] + tr[rit(p)];
}
}
void update(int p, int l, int r, int idx, int val){ //O(log(n))
if(l>r || l>idx || r<idx) return;
if(l==r)
tr[p] = val;
else{
update(lft(p), l, med(l, r), idx, val);
update(rit(p), med(l, r)+1, r, idx, val);
tr[p] = tr[lft(p)] + tr[rit(p)];
}
}
int sum(int p, int l, int r, int i, int j){ //O(log(n))
if(l>r || l>j || r<i) return 0;
if(l>=i && r<=j) return tr[p];
else{
int q1 = sum(lft(p), l, med(l, r), i, j);
int q2 = sum(rit(p), med(l, r)+1, r, i, j);
return q1 + q2;
}
}
int main(){
// freopen("i.in", "rt", stdin);
// freopen("o.out", "wt", stdout);
cin.sync_with_stdio(0);
cin >> n;
for(int i = 0 ; i < n ; ++i)
cin >> A[i];
cin >> q;
build(1, 0, n-1);
while(q--){
cin >> t >> a >> b;
if(t){
printf("The sum from %d to %d is %d\n", a, b, sum(1, 0, n-1, a, b));
}else{
update(1, 0, n-1, a, b);
}
}
return 0;
}
/*
Sample Input:
5
5 4 3 6 5
6
1 0 4
0 3 -10
1 0 4
1 0 0
0 0 2
1 0 2
*/