Cod sursa(job #2611153)

Utilizator stefantagaTaga Stefan stefantaga Data 6 mai 2020 15:05:03
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("aib.in");
ofstream g("aib.out");
int n,aib[100005];
int bit (int x)
{
    return x&(-x);
}
void update (int poz,int val)
{
    int i;
    for (i=poz;i<=n;i+=bit(i))
    {
        aib[i]+=val;
    }
}
int suma (int poz)
{
    int sum=0,i;
    for (i=poz;i>0;i-=bit(i))
    {
        sum=sum+aib[i];
    }
    return sum;
}
int m,i,x,y,tip,poz,val,lim,st,dr,sol,mij;
int main()
{
    f>>n>>m;
    for (i=1;i<=n;i++)
    {
        f>>x;
        update(i,x);
    }
    for (i=1;i<=m;i++)
    {
        f>>tip;
        if (tip==0)
        {
            f>>poz>>val;
            update(poz,val);
        }
        else
        if (tip==1)
        {
            f>>x>>y;
            if (x<y)
            {
                swap(x,y);
            }
            g<<suma(x)-suma(y-1)<<'\n';
        }
        else
        {
            f>>lim;
            st=1;
            dr=n;
            sol=0;
            while (st<=dr)
            {
                mij=(st+dr)/2;
                if (suma(mij)>=lim)
                {
                    sol=mij;
                    dr=mij-1;
                }
                else
                {
                    st=mij+1;
                }
            }
            if (suma(sol)!=lim||sol==0)
            {
                g<<"-1"<<'\n';
            }
            else
            {
                g<<sol<<'\n';
            }
        }
    }
    return 0;
}