Cod sursa(job #1413176)

Utilizator rares96cheseliRares Cheseli rares96cheseli Data 1 aprilie 2015 18:36:44
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
using namespace std;
ifstream f("aib.in");
ofstream g("aib.out");

int N, M, aib[100005], x, tip, y, sol, aux;

int lsb(int x) { return -x&x; }

void update(int poz, int val)
{
    while (poz<=N)
        aib[poz]+=val, poz+=lsb(poz);
}

int query(int poz)
{
    int rez=0;
    while (poz)
        rez+=aib[poz], poz-=lsb(poz);
    return rez;
}

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

    while (M--)
    {
        f>>tip>>x;
        if (tip==0) f>>y, update(x, y);
            else if (tip==1) f>>y, g<<query(y)-query(x-1)<<'\n';
                else
                {
                    sol=N;
                    for (int i=(1<<20); i; i>>=1)
                        if (sol-i>0 && query(sol-i)>=x)
                            sol-=i;

                    if (query(sol)!=x) g<<-1<<'\n';
                        else g<<sol<<'\n';
                }
    }
    return 0;
}