Cod sursa(job #1513679)

Utilizator TimitocArdelean Andrei Timotei Timitoc Data 29 octombrie 2015 20:37:17
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <cstdio>
#define MAXN 100050

using namespace std;

int n, m, aib[MAXN];

inline int power(int x) // 2^k
{
    return (x^(x-1)) & x;
}

void update(int ind, int val)
{
    for (int i = ind; i <= n; i += power(i)) {
        aib[i] += val;
    }
}

int sum(int ind)
{
    int rez = 0;
    for (int i = ind; i >= 1; i -= power(i)) {
        rez += aib[i];
    }
    return rez;
}

int src(int val)
{
    int step, vals = 0, ind = 0;
    for (step = 1; step < n; step <<= 1);
    for (step; step; step >>= 1)
        if (ind+step <= n && vals + aib[ind+step] <= val)
            ind += step, vals += aib[ind+step];
    return ind;
}

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

    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i++) {
        int x;
        scanf("%d", &x);
        update(i, x);
    }
    for (int i = 1; i <= m; i++) {
        int x, y, z;
        scanf("%d", &x);
        if (x == 0) {
            scanf("%d %d", &y, &z);
            update(y, z);
        }
        else if (x == 1) {
            scanf("%d %d", &y, &z);
            printf("%d\n", sum(z)-sum(y-1));
        }
        else if (x == 2) {
            scanf("%d", &y);
            int ind = src(y);
            if (sum(ind) == y)
                printf("%d\n", ind);
            else
                printf("-1\n");
        }

    }

    return 0;
}