Cod sursa(job #3309558)

Utilizator SimifilLavrente Simion Simifil Data 6 septembrie 2025 13:40:43
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <algorithm>
#include <fstream>
#include <cmath>
using namespace std;
ifstream f("aib.in");
ofstream g("aib.out");

int n, q;
const int maxn = 1e5;
long long aib[maxn+1];
int v[maxn+1];

void update( int poz, long long val )
{
    for( int i = poz; i <= n; i+=(i&(-i)) )
        aib[i] += val;
}

long long queryM( int poz )
{
    long long sum = 0;
    for( int i = poz; i >= 1; i-=(i&(-i)) )
        sum += aib[i];
    return sum;
}

long long query( int l, int r )
{
    return queryM(r) - queryM(l-1);
}

int query2( long long sum )
{
    int bit = 1;
    while( bit*2 <= n )
        bit *= 2;
    int poz = 0;
    long long s = 0;
    for( int i = bit; i > 0; i=i/2 )
    {
        if( poz+i <= n && s + aib[poz+i] < sum )
        {
            s += aib[poz+i];
            poz += i;
        }
    }
    ++poz;
    if( poz > n || queryM(poz) > sum )
        return -1;
    return poz;
}

int main() {
    ios_base::sync_with_stdio(false);
    f.tie(nullptr);
    g.tie(nullptr);

    f >> n >> q;
    for( int i = 1; i <= n; ++i )
    {
        f >> v[i];
        update(i, v[i]);
    }
    for( int i = 1; i <= q; ++i )
    {
        int t;
        f >> t;
        if( t == 0 )
        {
            int poz;
            long long val;
            f >> poz >> val;
            update( poz, val );
            v[poz] += val;
        }
        else if( t == 1 )
        {
            int l, r;
            f >> l >> r;
            g << query(l, r) << "\n";
        }
        else
        {
            long long a;
            f >> a;
            g << query2( a ) << "\n";
        }
    }

    return 0;
}