Cod sursa(job #1740401)

Utilizator AplayLazar Laurentiu Aplay Data 11 august 2016 16:01:05
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <bits/stdc++.h>

#define NMAX 100001

using namespace std;

int N, M, aib[NMAX];

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

int read(int index) {
    int result = 0;

    while(index) {
        result += aib[index];
        index -= (index & -index);
    }

    return result;
}

int findd(int value) {
    int index = 0, pow, tIndex;

    for (pow = 1; pow <= N; pow <<= 1);

    while (pow && index <= N) {
        if (index + pow <= N) {
            tIndex = index + pow;
            if (value == aib[tIndex]) return tIndex;
            else {
                if (value > aib[tIndex]) {
                    value -= aib[tIndex];
                    index = tIndex;
                }
            }
        }
        pow >>= 1;
    }

    if (value) return -1;
    return index;
}

int main() {
    int op, x, y;

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

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

    for (int it = 0; it < M; ++it) {
        scanf("%d%", &op);
        switch(op) {
        case 0:
            scanf("%d%d", &x, &y);
            update(x, y);
            break;
        case 1:
            scanf("%d%d", &x, &y);
            printf("%d\n", read(y) - read(x - 1));
            break;
        default:
            scanf("%d%", &x);
            printf("%d\n", findd(x));
            break;
        }
    }

    fclose(stdin);
    fclose(stdout);

    return 0;
}