Cod sursa(job #1709768)

Utilizator Emy1337Micu Emerson Emy1337 Data 28 mai 2016 13:49:31
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

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

int n,m,x,aib[100005];

void update(int poz, int valoare)
{
    while(poz <= n)
    {
        aib[poz] += valoare;
        poz += ( poz & (-poz) ) ;
    }
}

int query(int poz)
{
    int s = 0;

    while(poz>0)
    {
        s += aib[poz];
        poz -= ( poz & (-poz) );
    }

    return s;
}

int cautare_binara(int suma)
{
    int st = 0, dr = n+1, m, last = -1;

    while(st<=dr)
    {
        m = (st+dr) / 2;

        if(query(m) >= suma)
        {
            last = m;
            dr = m - 1;
        }
        else
        {
            st = m + 1;
        }
    }

    return last;
}


int main()
{
    fin>> n >> m;
    for(int i=1; i<=n; i++)
    {
        fin >> x;
        update(i,x);
    }

    while(m--)
    {
        int tip,x,y,suma;
        fin >> tip;

        if(tip == 0)
        {
            fin>> x >> y;
            update(x,y);

        }
        else if( tip == 1)
        {
            fin >> x >> y;
            fout << query(y) - query(x-1) << "\n";
        }
        else
        {
            fin >> suma;
            fout << cautare_binara(suma) << "\n";
        }
    }
}