Pagini recente » Cod sursa (job #3360774) | Cod sursa (job #3360761)
#include <iostream>
#include <vector>
#define lsb(x) (x & (-x))
using namespace std;
struct Fenwick {
vector<long long> bit;
Fenwick(int n) {
bit.resize(n + 1);
}
void update(int k, int add)
{
for(int i = k; i < bit.size(); i += lsb(i))
{
bit[i] += add;
}
}
long long query(int x)
{
if (x >= bit.size()) {
return -1;
}
long long sum = 0;
for(int i = x; i > 0; i -= lsb(i)){
sum += bit[i];
}
return sum;
}
int bin_search(long long s, bool strict = false) {
int ans = 0;
long long sum_ans = 0;
for (int pas = (1 << 18); pas > 0; pas /= 2) {
if (ans + pas >= bit.size()) { continue; }
if (sum_ans + bit[ans + pas] + strict <= s) {
ans += pas;
sum_ans += bit[ans];
}
}
return ans;
}
};
int main() {
#ifndef LOCAL
freopen("aib.in", "r", stdin);
freopen("aib.out", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int n, q; cin >> n >> q;
Fenwick fwt(n);
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
fwt.update(i, x);
}
for (int i = 1; i <= q; i++) {
int type; cin >> type;
if (type == 0) {
int a, b; cin >> a >> b;
fwt.update(a, b);
} else if (type == 1) {
int a, b; cin >> a >> b;
cout << fwt.query(b) - fwt.query(a - 1) << "\n";
} else {
long long s; cin >> s;
int pos = fwt.bin_search(s, /* strict= */ true) + 1;
if (fwt.query(pos) == s) {
cout << pos << "\n";
} else {
cout << "-1\n";
}
}
}
return 0;
}