Cod sursa(job #2485961)

Utilizator tomaionutIDorando tomaionut Data 2 noiembrie 2019 10:52:09
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>

using namespace std;

int n,aib[100005];
ifstream fin("aib.in");
ofstream fout("aib.out");

void update(int p, int x)
{
    while (p<=n)
    {
        aib[p]+=x;
        p+=(p&(-p));
    }

}

int Suma(int p)
{
    int s=0;
    while (p>0)
    {
        s+=aib[p];
        p-=(p&(-p));
    }
    return s;
}

/// caut cea mai din st pozitie poz
/// cu suma a[1]+...+a[poz] = s
int CautBin(int p, int s)
{
    int st,dr,poz,mij;
    int suma;
    st=1;
    dr=p;
    poz=-1;
    while (st<=dr)
    {
        mij=(st+dr)/2;
        suma=Suma(mij);
        if (suma==s)
        {
            poz=mij;
            dr=mij-1;
        }
        else if (suma>s) dr=mij-1;
        else st=mij+1;
    }
    return poz;
}


int main()
{
    int i,m,op,x,a,b;
    fin >> n >> m;
    for (i=1; i<=n; i++)
        {
            fin >> x;
            update(i,x);
        }
    while (m--)
    {
        fin >> op;
        if (op==0)
        {
            fin >> a >> b;
        update(a,b);
        }
        else if (op==1)
        {
            fin >> a >> b;
            fout << (Suma(b)-Suma(a-1)) << "\n";
        }
        else
        {
             fin >> a;
             fout << CautBin(n,a) << "\n";
        }
    }



    return 0;
}