Cod sursa(job #1156220)

Utilizator Paula-ElenaPaula-Elena Margarit Paula-Elena Data 27 martie 2014 15:18:50
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
using namespace std;

ifstream fin("aib.in");
ofstream fout("aib.out");

const int MAXN = 100009;

int N, Q;
unsigned int aib[MAXN];

inline unsigned int query(int poz)
{
    unsigned int sum = 0;
    while ( poz != 0 )
    {
        sum += aib[poz];
        poz -= poz&-poz;
    }

    return sum;
}

inline void update(int poz,unsigned int val)
{
    while ( poz <= N )
    {
        aib[poz] += val;
        poz+=poz&-poz;
    }
}

inline int cauta(unsigned int val)
{
    unsigned int step, i;

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

    for ( i = 0; step; step>>=1)
        if ( i+step <= N && val >= aib[i+step] )
        {
            i+= step;
            val -= aib[i];
        }

    if ( val )
        return -1;
    else
        return i;
}

void citire()
{
    unsigned int tip, poz, val, st, dr;

    fin >> N >> Q;
    for (int i = 1; i <= N; ++i)
    {
        fin >> val;
        update(i, val);
    }

    for (int i = 0; i < Q; ++i)
    {
        fin >> tip;
        if ( tip == 0 )
        {
            fin >> poz >> val;
            update(poz, val);
        }
        else if ( tip == 1 )
        {
            fin >> st >> dr;
            fout << query(dr) - query(st-1) << "\n";
        }
        else
        {
            fin >> val;
            fout << cauta(val) << "\n";
        }
    }
}

int main ()
{
    citire();

    fin.close();
    fout.close();

    return 0;
}