Cod sursa(job #2186788)

Utilizator Narvik13Razvan Roatis Narvik13 Data 25 martie 2018 22:34:02
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#define MMAX 100002

using namespace std;

int n,m,aib[MMAX];

ifstream f("aib.in");
ofstream o("aib.out");

int next(int pos)
{
    return pos & (-pos);
}

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

int get_val(int pos)
{
    int sum = 0;
    while(pos > 0)
    {
        sum += aib[pos];
        pos -= next(pos);
    }
    return sum;
}

int main()
{
    int a,b;
    f >> n >> m;
    for(int i = 1; i <= n; ++i)
    {
        int val;
        f >> val;
        update(i,val);
    }

    for(int i = 1; i <= m; ++i)
    {
        int c;
        f >> c >> a;
        if(c == 0)
        {
            f >> b;
            update(a,b);
        }
        else if(c == 1)
        {
            f >> b;
            o << get_val(b) - get_val(a-1) << '\n';
        }
        else
        {
            int pow2, t;
            for(pow2 = 1; pow2 < n; pow2 <<= 1);
            for(t = 0; pow2; pow2 >>= 1)
                if(pow2+t <= n && get_val(pow2+t) <= a)
                    t += pow2;

            if(get_val(t) == a && t)
                o << t << '\n';
            else
                o << "-1\n";
        }
    }
    return 0;
}