Cod sursa(job #2844955)

Utilizator Langa_bLanga Radu Langa_b Data 6 februarie 2022 15:33:51
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 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() {

    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;
}