Cod sursa(job #1507096)

Utilizator pepsiM4A1Ozturk Arif pepsiM4A1 Data 21 octombrie 2015 13:03:44
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <cstdio>
#include <cmath>
#define DIM 10000
char buff[DIM];
int poz=0;
 
void citeste(int &numar)
{
     numar = 0;
     while (buff[poz] < '0' || buff[poz] > '9')     
          if (++poz == DIM) 
               fread(buff,1,DIM,stdin),poz=0;     
     while ('0'<=buff[poz] && buff[poz]<='9')
     {
          numar = numar*10 + buff[poz] - '0';
          if (++poz == DIM) 
               fread(buff,1,DIM,stdin),poz=0;               
     }     
}
int n,m,lgn;
int a[100023];
void update(int x,int y)
{
     for(;x<=n;x+=(x&(x^(x-1)))) a[x]+=y;
}
int query(int x)
{
    int s=0;
    for(;x>0;x-=(x&(x^(x-1))))
    {
                              s+=a[x];
    }
    return s;
}
int main()
{
    freopen ("aib.in","r",stdin);
    freopen ("aib.out","w",stdout);
    citeste(n);
    citeste(m);
    lgn=(int)log2(n);
    for(int i=1;i<=n;i++)
    {
            int nr;
            citeste(nr);
            update(i,nr);
    }
    for(int i=1;i<=m;i++)
    {
            int tip;
            citeste(tip);
            if(tip==0)
            {
                      int x1,x2;
                      citeste(x1);
                      citeste(x2);
                      update(x1,x2);
            }
            else if(tip==1)
            {
                 int x1,x2;
                 citeste(x1);
                 citeste(x2);
                 printf("%d\n",query(x2)-query(x1-1));
            }
            else
            {
                int x1;
                citeste(x1);
                int s=1,e=n,rasp=-1;
                while(s<=e)
                {
                           int mij=(s+e)/2;
                           int val=query(mij);
                           if(val==x1)
                           {
                                      rasp=mij;
                                      e=mij-1;
                           }
                           else if(val<x1) s=mij+1;
                           else e=mij-1;
                }
                printf("%d\n",rasp);
            }
    }
}