Cod sursa(job #1717397)

Utilizator Burbon13Burbon13 Burbon13 Data 14 iunie 2016 19:40:01
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <cstdio>

using namespace std;

const int nmx = 100002;

int n,m;
int arb[nmx];

int pow(int nr)
{
    return nr & (-nr);
}

void update(int pos, int val)
{
    while(pos <= n)
    {
        arb[pos] += val;
        pos += pow(pos);
    }
}

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

    while(pos)
    {
        sum += arb[pos];
        pos -= pow(pos);
    }

    return sum;
}

int _search(int a)
{
    int st = 1, dr = n, mij;

    while(st <= dr)
    {
        mij = st + (dr - st) / 2;

        int val = query(mij);

        if(val == a)
            return mij;
        else if(val > a)
            dr = mij - 1;
        else
            st = mij + 1;
    }
    return -1;
}

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 nr;
        scanf("%d", &nr);
        update(i,nr);
    }

    for(int i = 1; i <= m; ++i)
    {
        int cond,a,b;
        scanf("%d", &cond);
        if(cond != 2)
            scanf("%d %d", &a ,&b);
        else
            scanf("%d", &a);

        if(cond == 0)
            update(a,b);
        else if(cond == 1)
            printf("%d\n", query(b) - query(a-1));
        else
            printf("%d\n", _search(a));
    }

    return 0;
}