Cod sursa(job #1891395)

Utilizator BlueCodeMihalache Catalin Alexandru BlueCode Data 23 februarie 2017 23:22:45
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("aib.in");
ofstream g("aib.out");
const int dim=100001;
int n,m;
int aib[dim];
int c,s; ///c=nr. de 0 pe care ii are la final un nr, in b2
void update(int poz,int val)
{
    c=0;
    while (poz<=n)
    {
        aib[poz]+=val;
        while ((poz&(1<<c))==0) c++;///bitul de pe pozitia c din poz
        poz+=(1<<c);
    }
}
int Query(int poz)
{
    c=0,s=0;
    while (poz>0)
    {
        s+=aib[poz];
        while ((poz&(1<<c))==0) c++;///bitul de pe pozitia c din poz
        poz-=(1<<c);
    }
    return s;
}
int binary_search(int val)
{
    int i, step;

    for (step=1;step<n;step<<=1);

    for(i=0;step;step>>=1)
    {
         if(i+step<=n)
         {
            if(val>=aib[i+step])
            {i+=step,val-=aib[i];
            if (val==0) return i;
            }
         }
    }

    return -1;
}
int main()
{
    int i,x,y,op;
    f>>n>>m;
    for (i=1;i<=n;i++)
    {
        f>>x;
        update(i,x);
    }
    for (i=1;i<=m;i++)
    {
        f>>op;
        if (op<2)
        {
            f>>x>>y;
            if (op==0) update(x,y);
            if (op==1) g<<Query(y)-Query(x-1)<<'\n';
        }
        if (op==2)
        {
            f>>x;
            g<<binary_search(x)<<'\n';
        }
    }
}