Cod sursa(job #3195289)

Utilizator not_anduAndu Scheusan not_andu Data 20 ianuarie 2024 13:15:08
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

#define INFILE "aib.in"
#define OUTFILE "aib.out"

struct Fenwick {

private:
    int n;
    vector<ll> aib;

public:
    Fenwick() : n(0) {}

    Fenwick(int _n) : n(_n) {
        aib.resize(n + 1, 0);
    }

    void update(int position, ll value){
        for(; position <= n; position += (position & -position)){
            aib[position] += value;
        }
    }

    ll query(int rightBound){
        ll ans = 0;
        for(int position = rightBound; position > 0; position -= (position & -position)){
            ans += aib[position];
        }
        return ans;
    }

    ll getSum(int leftBound, int rightBound){
        return query(rightBound) - query(leftBound - 1);
    }

    ll findSum(ll sum){
        int bit = 1, pos = 0;
        for(; bit <= n; bit <<= 1);
        for(; bit > 0; bit >>= 1){
            if(pos + bit <= n){
                if(aib[pos + bit] <= sum){
                    sum -= aib[pos + bit];
                    pos += bit;
                }
            }
        }
        return pos;
    }

};

void solve(){

    int n, queries; cin >> n >> queries;
    Fenwick bit(n);

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

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

        short type; cin >> type;

        if(type == 0){
            int a, b; cin >> a >> b; bit.update(a, b);
        }
        else if(type == 1){
            int a, b; cin >> a >> b; cout << bit.getSum(a, b) << '\n';
        }
        else{
            ll a; cin >> a;
            int pos = bit.findSum(a - 1);
            if(bit.query(pos + 1) == a) cout << pos + 1 << '\n';
            else cout << -1 << '\n';
        }

    }

}

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