Cod sursa(job #1447095)

Utilizator EpictetStamatin Cristian Epictet Data 3 iunie 2015 17:18:46
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
using namespace std;
ifstream fin ("aib.in");
ofstream fout ("aib.out");
unsigned int N, M, tip, a, b, AIB[100010];

unsigned int zeros(unsigned int x)
{
    return ((x ^ (x - 1)) & x);
}

void Update(unsigned int poz, unsigned int val)
{
    while (poz <= N)
    {
        AIB[poz] += val;
        poz += zeros(poz);
    }
}

unsigned int Query(unsigned int poz, unsigned int sum = 0)
{
    while (poz)
    {
        sum += AIB[poz];
        poz -= zeros(poz);
    }

    return sum;
}

int Binary_Search(int val)
{
    unsigned int i, step;

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

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

    return -1;
}

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

    for (int i = 1; i <= M; i++) {
        fin >> tip;

        if (tip == 0)
        {
            fin >> a >> b;
            Update(a, b);
        }
        else if (tip == 1)
        {
            fin >> a >> b;
            fout << Query(b) - Query(a - 1) << '\n';
        }
        else
        {
            fin >> a;
            fout << Binary_Search(a) << '\n';
        }
    }

    fout.close();
    return 0;
}