Cod sursa(job #898803)

Utilizator vladtarniceruVlad Tarniceru vladtarniceru Data 28 februarie 2013 11:48:05
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream fin("aib.in");
ofstream fout("aib.out");
int N, M, A[100100];
int aib[100100];

inline void update(int poz, int val)
{
    for (int i = poz; i <= N; i = (i | (i - 1)) + 1) aib[i] += val;
}

inline int query(int poz)
{
    int ret = 0;
    for (int i = poz; i >= 1; i = i & (i - 1)) ret = ret + aib[i];
    return ret;
}

int main()
{
    fin >> N >> M;
    for (int i = 1; i <= N; i++)
    {
        fin >> A[i];
        update(i, A[i]);
    }
    for (; M--; )
    {
        int q;
        fin >> q;
        if (q == 0)
        {
            int x, y;
            fin >> x >> y;
            update(x, y);
        }
        else
        if (q == 1)
        {
            int x, y;
            fin >> x >> y;
            fout << query(y) - query(x - 1) << '\n';
        }
        else
        {
            int x;
            fin >> x;
            int i = 0, cnt = 1 << 20, sum = x;
            for (; cnt > 0; cnt >>= 1)
                if (i + cnt <= N)
                    if (sum - aib[i + cnt] >= 0)
                        i += cnt, sum -= aib[i];
            if (sum == 0)
                fout << i << '\n';
            else
                fout << "-1\n";
        }
    }
    fout.close();
    return 0;
}