Cod sursa(job #727256)

Utilizator R.A.RFMI Romila Remus Arthur R.A.R Data 27 martie 2012 20:19:52
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#define zeros(x) x&(-x)
#define nmax 100004

using namespace std;

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

int N,M,AIB[nmax];
int st;

inline void Update(int p,int key)
{
    for(;p<=N;p+=zeros(p))AIB[p]+=key;
}

inline int Query(int p)
{
    int s=0;

    for(;p;p-=zeros(p))s+=AIB[p];

    return s;
}

inline int BS(int key)
{
    if(!key)return -1;

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

int main()
{
    int a,b,c,i;
    in>>N>>M;
    for(st=1;st<N;st<<=1);
    for(i=1;i<=N;i++)in>>a,Update(i,a);
    while(M--)
    {
        in>>c;
        if(c==0)
        {
            in>>a>>b;
            Update(a,b);
        }
        if(c==1)
        {
            in>>a>>b;
            out<<Query(b)-Query(a-1)<<'\n';
        }
        if(c==2)
        {
            in>>a;
            out<<BS(a)<<'\n';
        }
    }
    return 0;
}