Cod sursa(job #754715)

Utilizator SpiriFlaviuBerbecariu Flaviu SpiriFlaviu Data 2 iunie 2012 23:02:52
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>

using namespace std;

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

int n,m,c[100001];

void update(int ind,int val)
{

    int poz=0;
    while(ind<=n)
    {
        c[ind]+=val;
        while(!(ind&(1<<poz))) poz++;
        ind+=1<<poz;
    }
}

int sumquery(long dr)
{
    int sum=0;
    int poz=0;
    while(dr>0)
    {
        sum+=c[dr];
        while(!(dr&(1<<poz))) poz++;
        dr-=1<<poz;
        poz++;

    }
    return sum;
}

int search(int a)
{
    int st=1,dr=n;
    if(sumquery(dr)==a) return n;
    while(st<=dr)
    {
        long mid=(st+dr)/2;
        if(sumquery(mid)==a) return mid;
        if(sumquery(mid)>a)
            dr=mid-1;
        else st=mid+1;
    }
    return dr;
}


int main()
{
    int cod,x,a,b,ind,val;
    fin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        fin>>x;
        update(i,x);
    }
    for(int i=1;i<=m;i++)
    {
        fin>>cod;
        if(cod==0)
        {
            fin>>ind>>val;
            update(ind,val);
        }
        else if(cod==1)
        {
            fin>>a>>b;
            fout<<sumquery(b)-sumquery(a-1)<<'\n';
        }
        else
        {
            fin>>a;
            fout<<search(a)<<'\n';
        }

    }
    fin.close();
    fout.close();
    return 0;
}