Cod sursa(job #3381284)

Utilizator Cris21234123Cristian Cris21234123 Data 5 decembrie 2026 20:23:41
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");
const int MAXN = (int)1e6 + 1;
struct AIB {
    int n, v[4*MAXN];
    void update(int poz, int val) {
        for ( ; poz <= n; poz += poz & -poz )
            v[poz] += val;
    }
    int prefix_sum(int poz) {
        int S = 0;
        for ( ; poz; poz -= poz & -poz )
            S += v[poz];
        return S;
    }
    int c1(int a, int b) {
        if ( b < a )
            return 0;
        return prefix_sum(b) - prefix_sum(a-1);
    }
    int 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 ) {
            int 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, int a[]) : n(n) {
        for ( int i = 1; i <= n; i++ )
            update(i, a[i]);
    }
};
int main() {
    ios_base::sync_with_stdio(false);
    fin.tie(nullptr);
    int N, M, v[MAXN], i, c, a, b;
    fin >> N >> M;
    for ( i = 1; i <= N; i++ )
        fin >> v[i];
    AIB aib(N, v);
    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;
}