Cod sursa(job #3266767)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 10 ianuarie 2025 11:26:41
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
using namespace std;

int n, m, c, x;
int a, b;
int pos;
int aib[100005];

void update(int i, int x) {
    for (int j=i;j<=n;j+=(j&-j)) {
        aib[j] += x;
    }
}

void create() {
    for (int i=1;i<=n;i++) {
        cin >> x;
        update(i, x);
    }
}

int query(int i) {
    int s = 0;
    for (int j=i;j>=1;j-=(j&-j)) {
        s += aib[j];
    }
    return s;
}

int pmin(int x) {
    int mask, p = 0;
    for (mask=1;mask*2<=n;mask*=2);
    for (;mask;mask/=2) {
        if (p + mask <= n) {
            if (x >= aib[p+mask]) {
                x -= aib[p+mask];
                p += mask;
                if (x == 0) {
                    return p;
                }
            }
        }
    }
    return -1;
}

void solve() {
    cin >> c;
    if (c == 0) {
        cin >> a >> x;
        update(a, x);
    }
    else if (c == 1) {
        cin >> a >> b;
        cout << query(b) - query(a-1) << '\n';
    }
    else {
        cin >> x;
        cout << pmin(x) << '\n';
    }
}

int main() {
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);
    cin >> n >> m;
    create();
    for(;m;m--) {
        solve();
    }
    return 0;
}