Cod sursa(job #3381285)

Utilizator Cris21234123Cristian Cris21234123 Data 5 decembrie 2026 20:32:36
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <fstream>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");
#define ll long long
const int MAXN = (int)1e5 + 1;
struct AIB {
    ll n, v[MAXN];
    void update(int poz, int val) {
        for ( ; poz <= n; poz += poz & -poz )
            v[poz] += val;
    }
    ll prefix_sum(int poz) {
        ll S = 0;
        for ( ; poz; poz -= poz & -poz )
            S += v[poz];
        return S;
    }
    ll c1(int a, int b) {
        if ( b < a )
            return 0;
        return prefix_sum(b) - prefix_sum(a-1);
    }
    ll c2(int a) {
        int poz = 0, sum_ramas = a, pas = 1;
        for ( ; (pas << 1) <= n; pas <<= 1 );
        for ( ; pas; pas >>= 1 )
            if ( poz + pas <= n && v[poz+pas] < sum_ramas ) {
                poz += pas;
                sum_ramas -= v[poz];
            }
        if ( poz < n ) {
            ll S = 0;
            for ( int i = poz + 1; i > 0; i -= i & -i )
                S += v[i];
            if ( S == a )
                return poz + 1;
        }
        return -1;
    }
    AIB(int n) : n(n) {
        int x;
        for ( int i = 1; i <= n; i++ ) {
            fin >> x;
            update(i, x);
        }
    }
};
int main() {
    ios_base::sync_with_stdio(false);
    fin.tie(nullptr);
    int N, M, i, c, a, b;
    fin >> N >> M;
    AIB aib(N);
    while ( M-- ) {
        fin >> c >> a;
        if ( c < 2 )
            fin >> b;
        if ( !c ) {
            aib.update(a, b);
        } else if ( c & 1 ) {
            fout << aib.c1(a, b) << "\n";
        } else
            fout << aib.c2(a) << "\n";
    }
    return 0;
}