Cod sursa(job #1375797)

Utilizator darrenRares Buhai darren Data 5 martie 2015 14:30:38
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <cstring>
#include <fstream>
#include <algorithm>

using namespace std;

int N, M;
int AIB[100002];

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 getpos(int sum)
{
    int now = 0, step = (1 << 16);
    for (; step; step >>= 1)
        if (now + step <= N && AIB[now + step] <= sum)
        {
            now += step;
            sum -= AIB[now];
        }

    if (sum == 0) return now;
    return -1;
}

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

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

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

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