Cod sursa(job #2171755)

Utilizator DanielRusuDaniel Rusu DanielRusu Data 15 martie 2018 13:25:26
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <cstdio>

using namespace std;

#define DIM 100004

int N, M;
int aib[DIM];

void update(int pos, int value) {
    for(;pos <= N; pos += pos & (-pos)) {
        aib[pos] += value;
    }
}

int query(int pos) {
    int ans = 0;

    for(;pos;pos -= pos & (-pos)) {
        ans += aib[pos];
    }

    return ans;
}

int bin_search(int x) {
    int pw = 1;
    while(pw <= N) {
        pw <<= 1;
    }
    pw >>= 1;
    int pos = 0;
    while(pw) {
        if(pos + pw <= N) {
            if(query(pos + pw) <= x) {
                pos += pw;
            }
        }

        pw >>= 1;
    }

    return pos;
}

int main() {
    freopen("aib.in","r",stdin);
    freopen("aib.out","w",stdout);

    scanf("%d %d\n", &N, &M);
    for(int i = 1; i <= N; ++i) {
        int x;
        scanf("%d", &x);
        update(i, x);
    }

    while(M--) {
        int tip;
        scanf("%d", &tip);
        if(tip == 0) {
            int pos, value;
            scanf("%d %d\n", &pos, &value);
            update(pos, value);
        }
        if(tip == 1) {
            int x, y;
            scanf("%d %d\n", &x, &y);
            cout << query(y) - query(x - 1) << '\n';
        }
        if(tip == 2) {
            int x;
            scanf("%d\n", &x);
            int pos = bin_search(x);
            if(query(pos) != x || pos == 0) {
                cout << -1 << '\n';
            }
            else {
                cout << pos << '\n';
            }
        }
    }

    return 0;
}