Cod sursa(job #2982772)

Utilizator tiberia_farkasFarkas Tiberia tiberia_farkas Data 20 februarie 2023 20:42:33
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("aib.in");
ofstream fout("aib.out");

int a[100001], n;

int query(int pi) {
    int sum = 0;
    for ( int i = pi; i > 0; i -= (i&-i) ) {
        sum += a[i];
    }
    return sum;
}

void update(int p, int x) {
    for ( int i = p; i <= n; i += (i&-i) ) {
        a[i] += x;
    }
}

int Search(int x) {
    int i;
    for ( i = 1; i < n; i <<= 1 ) ;
        for ( int j = 0; i; i >>= 1 ) {
            if ( i + j <= n ) {
                if ( x >= a[i+j] ) {
                    j += i;
                    x -= a[j];
                }
                if ( !x ) return j;
            }
        }
    return -1;
}

int main() {
    int m, c, i, x, y;
    fin >> n >> m;
    for ( i = 1; i <= n; ++i ) {
        fin >> x;
        update(i, x);
    }
    //for ( i = 1; i <= n; ++i ) cout << a[i] << " ";
    //cout << '\n';
    for ( i = 1; i <= m; ++i ) {
        fin >> c;
        if ( c == 2 ) {
            fin >> x;
            fout << Search(x) << '\n';
        } else {
            fin >> x >> y;
            if ( c == 0 ) update(x, y);
            else fout << query(y) - query(x-1) << '\n';
        }
    }
    return 0;
}