Cod sursa(job #2182763)

Utilizator MarutBrabete Marius Stelian Marut Data 22 martie 2018 17:08:34
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include<cstdio>
using namespace std;
int aib[100005],sp[100005];
void update(int poz,int val, int n)
{
    for ( ;poz<=n;poz+=poz&(-poz))
        aib[poz]+=val;
}
int query(int poz)
{
    int s=0;
    for( ;poz>0;poz-=poz&(-poz))
        s+=aib[poz];
    return s;
}
int bs(int val,int n)
{
    int st=1,dr=n,med;
    while(st<=dr)
    {
        med=(st+dr)/2;
        if(query(med)==val) return med;
            else if(query(med)<val) st=med+1;
                else dr=med-1;
    }
    return 0;
}
int main()
{
    freopen("aib.in","r",stdin);
    freopen("aib.out","w",stdout);
    int x,n,i,j,m,help;
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&x);
        sp[i]=sp[i-1]+x;
        help=i&(i-1);
        if(help==0) help--;
        aib[i]=sp[i]-sp[help];
    }
    int c,x1,x2;
    for(i=1;i<=m;i++)
    {
        scanf("%d%d",&c,&x1);
        if(c==0) {scanf("%d",&x2); update(x1,x2,n);}
            else if(c==1) { scanf("%d",&x2); printf("%d\n",query(x2)-query(x1-1)); }
                else
                {
                    int help;
                    help=bs(x1,n);
                    if(help==0) printf("-1\n");
                        else printf("%d\n",help);
                }
    }
    return 0;
}