Cod sursa(job #3166187)

Utilizator not_anduAndu Scheusan not_andu Data 7 noiembrie 2023 20:30:46
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>

using namespace std;

const int VMAX = 100005;

int n, queries;
int bit[VMAX];

void update(int pos, int val){

    for(int i = pos; i <= n; i += (i & -i)){
        bit[i] += val;
    }

}

int getSum(int pos){

    int ans = 0;

    for(int i = pos; i > 0; i -= (i & -i)){
        ans += bit[i];
    }

    return ans;

}

int find(int val){

    int step = 1, pos = 0;

    for(; step <= n; step <<= 1);

    for(; step > 0; step >>= 1){

        if(pos + step <= n){
            if(bit[pos + step] <= val){
                val -= bit[pos + step];
                pos += step;
            }
        }

    }

    return pos;

}

void solve(){

    cin >> n >> queries;

    for(int i = 1; i <= n; ++i){
        int aux; cin >> aux; update(i, aux);
    }

    for(int i = 0; i < queries; ++i){

        int type, x, y; cin >> type >> x;

        if(type == 0){
            cin >> y; update(x, y);
        }
        else if(type == 1){
            cin >> y; cout << getSum(y) - getSum(x - 1) << '\n';
        }
        else{

            auto pos = find(x - 1);

            if(getSum(pos + 1) == x){
                cout << pos + 1 << '\n';
            }
            else{
                cout << -1 << '\n';
            }

        }

    }

}

int main(){
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);
    solve();
    return 0;
}