Cod sursa(job #1192975)

Utilizator darrenRares Buhai darren Data 30 mai 2014 13:06:42
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <algorithm>

using namespace std;

int N, M;
int AIB[100002];

void update(int pos, int val)
{
    for (; pos <= 100000; 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 minpos(int sum)
{
    int step = (1 << 16), pnow = 0;
    for (; step; step >>= 1)
        if (pnow + step <= N && AIB[pnow + step] < sum)
        {
            pnow += step;
            sum -= AIB[pnow];
        }
    return pnow + 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, type; i <= M; ++i)
    {
        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 << minpos(a) << '\n';
        }
    }

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