Cod sursa(job #1413858)

Utilizator Ionut228Ionut Calofir Ionut228 Data 2 aprilie 2015 10:04:39
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>

using namespace std;

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

int N, M;
int AIB[100005];

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 cauta(int val)
{
    int lt = 0, rt = N + 1, sum;

    sum = query(N);
    if (val > sum)
        return -1;

    while (rt - lt > 1)
    {
        int mid = (lt + rt) >> 1;
        sum = query(mid);

        if (sum < val)
            lt = mid;
        else
            rt = mid;
    }

    if (query(rt) != val)
        return -1;
    return rt;
}

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

    int type, a, b;
    while (M--)
    {
        fin >> type;
        if (type == 0)
        {
            fin >> a >> b;
            update(a, b);
        }
        else if (type == 1)
        {
            fin >> a >> b;
            fout << query(b) - query(a - 1) << '\n';
        }
        else
        {
            fin >> a;
            fout << cauta(a) << '\n';
        }
    }

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