Cod sursa(job #2019625)

Utilizator bebeetarepredescu bebeetare Data 8 septembrie 2017 10:40:07
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>
#define ub(x) (x&(-x))

using namespace std;
int n,m,x,i,y,z,aib[1000003],st,dr,j,poz,k;
ifstream f("aib.in");
ofstream g("aib.out");
int sum(int poz)
{
    int s=0,j;
    for(j=poz;j>0;j-=ub(j))
    {
        s+=aib[j];
    }
    return s;
}
void updaite(int poz,int val)
{
    int j;
    for(j=poz;j<=n;j+=ub(j))
                    aib[j]+=val;
}
int main()
{
    f>>n>>m;
    for(i=1;i<=n;i++)
    {
        f>>x;
        updaite(i,x);
    }
    for(i=1;i<=m;i++)
    {
        f>>x;
        if(x==0)
        {
            f>>y>>z;
            updaite(y,z);
        }
        else if(x==1)
        {
            f>>y>>z;
            g<<sum(z)-sum(y-1)<<'\n';
        }
        else if(x==2)
        {
            f>>y;
            st=1;
            dr=n;
            poz=0;
            while(st<=dr && poz==0)
            {
                k=(st+dr)/2;
                if(sum(k)==y)poz=k;
                else if(sum(k)>y)dr=k-1;
                else st=k+1;
            }
            g<<poz<<'\n';
        }
    }
    return 0;
}