-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfenwick.cpp
80 lines (50 loc) · 1.07 KB
/
fenwick.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
#include <bits/stdc++.h>
#define FIN "aib.in"
#define FOUT "aib.out"
using namespace std;
int N, M, fen[ 100005 ];
void update(int x, int val) {
for( ;x<=N; x+=x^(x-1)&x) {
fen[x] += val;
}
}
int query(int x) {
int ans;
for(ans = 0; x; x-=x^(x-1)&x) {
ans += fen[x];
}
return ans;
}
int search(int x) {
int log, index;
for(log = 1; log < N; log <<= 1);
for(index = 0; log; log>>=1) {
if(index+log<=N && fen[index+log]<=x)
index += log, x-=fen[index];
}
return (!x ? index : -1);
}
int main(void)
{
int i, v, tip, a, b;
freopen(FIN, "r", stdin);
//freopen(FOUT, "w", stdout);
scanf("%d %d", &N, &M);
for(int i = 1; i <= N; ++i) {
cin>>v;
update(i,v);
}
for( ; M; M--) {
cin>>tip;
if(tip == 0) {
cin>>a>>b;
update(a,b);
} else if(tip == 1) {
cin>>a>>b;
cout<<query(b)-query(a-1)<<endl;
} else if(tip == 2) {
cin>>a;
printf("%d\n", (!a ? -1 : search(a)));
}
}
}