Cod sursa(job #1771597)

Utilizator topala.andreiTopala Andrei topala.andrei Data 5 octombrie 2016 20:00:01
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 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++;
        poz+=(1<<C);
    }
}
int Query(int poz)
{
    C=0,S=0;
    while (poz>0)
    {
        S+=aib[poz];
        while ( (poz & (1<<C))==0) C++;
        poz-=(1<<C);
    }
    return S;
}
int Cautare(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 ) 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<<Cautare(x)<<'\n';
        }
    }
}