Cod sursa(job #1963512)

Utilizator razvan99hHorhat Razvan razvan99h Data 12 aprilie 2017 16:23:35
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#define DM 100005
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");

int aib[DM], n, m, x, a, b;

void update(int pos, int val)
{
    for(; pos <= n; pos += (pos & (-pos)))
        aib[pos] += val;
}
int query(int pos)
{
    int rez = 0;
    for(; pos > 0; pos -= (pos & (-pos)))
        rez += aib[pos];
    return rez;
}
int sum(int a, int b)
{
    return (query(b) - query(a - 1));
}
int caut_bin(int val)
{
    int pos = 0, step = 1;
    for(; step < n; step <<= 1) ;
    for(; step > 0; step >>= 1)
        if(pos + step <= n)
            if(aib[pos + step] <= val)
            {
                pos += step;
                val -= aib[pos];
                if(val == 0) return pos;
            }
    return -1;
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        fin >> x;
        update(i, x);
    }
    for(int i = 1; i <= m; i++)
    {
        fin >> x;
        if(x == 0)
        {
            fin >> a >> b;
            update(a, b);
        }
        if(x == 1)
        {
            fin >> a >> b;
            fout << sum(a, b) << '\n';
        }
        if(x == 2)
        {
            fin >> a;
            fout << caut_bin(a) << '\n';
        }
    }
    return 0;
}