Cod sursa(job #3153044)

Utilizator AlexSerban21Serban Alexandru AlexSerban21 Data 27 septembrie 2023 19:37:09
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <fstream>
using namespace std;
ifstream fin ("aesm.in");
ofstream fout ("aesm.out");
int q,t,ch,sum,poz,i,n,x,y,aint[400001],v[100001];
void build (int nod,int st,int dr)
{
    if (st==dr)
        aint[nod]=v[st];
    else
    {
        int mij=(st+dr)/2;
        build (2*nod,st,mij);
        build (2*nod+1,mij+1,dr);
        aint[nod]=aint[2*nod]+aint[2*nod+1];
    }
}
void update (int nod,int st,int dr)
{
    if (st==dr)
        aint[nod]=v[st];
    else
    {
        int mij=(st+dr)/2;
        if (poz<=mij)
            update (2*nod,st,mij);
        else
            update (2*nod+1,mij+1,dr);
        aint[nod]=aint[2*nod]+aint[2*nod+1];
    }
}
void query (int nod,int st,int dr)
{
    if (st>=x&&dr<=y)
        sum+=aint[nod];
    else
    {
        int mij=(st+dr)/2;
        if (x<=mij)
            query (2*nod,st,mij);
        if (y>mij)
            query (2*nod+1,mij+1,dr);
    }
}
void pozitie (int nod,int st,int dr,int sum)
{
    if (st==dr)
    {
        sum-=aint[nod];
        if (sum==0)
            poz=st;
        else
            poz=-1;
    }
    else
    {
        int mij=(st+dr)/2;
        if (aint[2*nod]>=sum)
            pozitie (2*nod,st,mij,sum);
        else
            pozitie (2*nod+1,mij+1,dr,sum-aint[2*nod]);
    }
}
int main()
{
    fin>>n>>q;
    for (i=1; i<=n; i++)
        fin>>v[i];
    build (1,1,n);
    for (t=1; t<=q; t++)
    {
        fin>>ch;
        if (ch==0)
        {
            fin>>poz>>x;
            v[poz]+=x;
            update (1,1,n);
        }
        else if (ch==1)
        {
            fin>>x>>y;
            sum=0;
            query (1,1,n);
            fout<<sum<<"\n";
        }
        else
        {
            fin>>sum;
            pozitie (1,1,n,sum);
            fout<<poz<<"\n";
        }
    }
    return 0;
}