Cod sursa(job #3214845)

Utilizator not_anduAndu Scheusan not_andu Data 14 martie 2024 15:01:52
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#pragma GCC optimize ("03", "Ofast", "unroll-loops")
#include <bits/stdc++.h>

using namespace std;

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

typedef long long ll;

struct Fenwick {

private:
    int n;
    vector<ll> aib;

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

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

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

    ll query(int left, int right) {
        return query(right) - query(left - 1);
    }

    int search(ll target){
        int left = 1, right = n;
        int ans = -1;
        while(left <= right){
            int middle = (left + right) >> 1;
            ll aux = this -> query(middle);
            if(aux <= target) left = middle + 1, ans = middle;
            else right = middle - 1;
        }
        ll aux = this -> query(ans);
        return (target == aux ? ans : -1);
    }

};

void solve(){

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

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

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

        int task; cin >> task;

        if(task == 0){
            int position; ll value; cin >> position >> value;
            aib.update(position, value);
        }
        else if(task == 1){
            int left, right; cin >> left >> right;
            cout << aib.query(left, right) << '\n';
        }
        else {
            ll target; cin >> target;
            cout << aib.search(target) << '\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;
}