Cod sursa(job #3326478)

Utilizator Luca_georgescuLuca Georgescu Luca_georgescu Data 29 noiembrie 2025 09:40:11
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include <bits/stdc++.h>
#define int long long

using namespace std;

ifstream f("aib.in");
ofstream g("aib.out");

const int nmax=1e5+5;
int n,n_og;
int a[3*nmax+5],aint[3*nmax+5];

void nxt2(int &n)
{
    while ( n&(n-1) )
        n+=(n&-n);
}

struct AINT
{
    void build()
    {
        for (int i=0; i<n_og; i++ )
            aint[i+n]=a[i];

        /*for (int i=n_og; i<n; i++ )
            aint[i+n]=INT_MAX;*/

        for (int i=n-1; i>=1; i-- )
            aint[i]=aint[2*i]+aint[2*i+1];
    }

    void update(int pos, int x)
    {
        a[pos]+=x;

        pos+=n;
        aint[pos]+=x;

        for (pos/=2; pos; pos/=2 )
            aint[pos]=aint[2*pos]+aint[2*pos+1];
    }

    int query(int l, int r)
    {
        l+=n;
        r+=n;

        int sum=0;

        while ( l<=r )
        {
            if ( l&1 )
                sum+=aint[l++];

            l>>=1;

            if ( !(r&1) )
                sum+=aint[r--];

            r>>=1;
        }

        return sum;
    }

}tree;

int cb (int x)
{
    int st=0, dr=n_og-1;
    int rez=-1;

    while ( st<=dr )
    {
        int mid=(st+dr)/2;
        int sum=tree.query(0,mid);

        if ( sum>=x )
        {
            if ( sum==x ) rez=mid;
            dr=mid-1;
        }
        else st=mid+1;
    }

    return rez;
}

signed main()
{
    int q; f >> n >> q;

    for (int i=0; i<n; i++ )
        f >> a[i];

    n_og=n;
    nxt2(n);

    tree.build();

    while ( q-- )
    {
        int c; f >> c;
        if ( c==1 )
        {
            int l,r; f >> l >> r;
            g << tree.query(l-1,r-1) << '\n';
        }
        if ( c==0 )
        {
            int pos,x; f >> pos >> x;
            tree.update(pos-1,x);
        }
        if ( c==2 )
        {
            int x; f >> x;
            g << cb(x)+1 << '\n';
        }
    }
    return 0;
}