Cod sursa(job #1282129)

Utilizator Ionut228Ionut Calofir Ionut228 Data 3 decembrie 2014 23:02:18
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>

using namespace std;

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

int N, M;
int AIB[100001];

void update(int pos, int val)
{
    for (; pos <= N; pos += pos & -pos)
        AIB[pos] += val;
}

int query(int pos)
{
    int sum = 0;
    for (; pos >= 1; pos -= pos & -pos)
        sum += AIB[pos];

    return sum;
}

int search(int val)
{
    int i, step;

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

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

    return -1;
}

int main()
{
    fin >> N >> M;
    for (int i = 1, x; i <= N; ++i)
    {
        fin >> x;
        update(i, x);
    }

    int type, pos, val, pos1, pos2;
    while (M--)
    {
        fin >> type;
        if (type == 0)
        {
            fin >> pos >> val;
            update(pos, val);
        }
        else if (type == 1)
        {
            fin >> pos1 >> pos2;
            fout << query(pos2) - query(pos1 - 1) << '\n';
        }
        else
        {
            fin >> pos;
            fout << search(pos) << '\n';
        }
    }

    fin.close();
    fout.close();
    return 0;
}