Cod sursa(job #1917363)

Utilizator ionut98Bejenariu Ionut Daniel ionut98 Data 9 martie 2017 12:04:23
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include<fstream>
#include<cstring>
using namespace std;
ifstream f("aib.in");
ofstream g("aib.out");
int n,op,cer,poz,val,nr,poz1,poz2,i;
int tree[100001];
int suma,put;
void update(int poz,int val)
{
    put=0;
    while(poz<=n)
    {
        tree[poz]+=val;
        while(!(poz&(1<<put)))
          put++;
        poz+=(1<<put);
        put++;
    }
}
int query(int poz)
{
    put=0,suma=0;
    while(poz>0)
    {
          suma+=tree[poz];
          while(!(poz&(1<<put)))
            put++;
          poz-=(1<<put);
          put++;
    }
    return suma;
}
int caut(int val)
{
    int i,step=1;
    while(step<n)
      step<<=1;
    for(i=0;step;step>>=1)
      if(i+step<=n&&val>=tree[i+step])
      {
          i+=step;
          val-=tree[i];
          if(!val)
            return i;
      }
    return -1;
}
int main()
{
    f>>n>>cer;
    for(i=1;i<=n;i++)
    {
        f>>nr;
        update(i,nr);
    }
    while(cer--)
    {
        f>>op;
        if(op==2)
        {
            f>>val;
            g<<caut(val)<<"\n";
        }
        else if(op==1)
        {
            f>>poz1>>poz2;
            g<<query(poz2)-query(poz1-1)<<"\n";
        }
        else if(op==0)
        {
            f>>poz>>val;
            update(poz,val);
        }
    }
    return 0;
}