Cod sursa(job #3265569)

Utilizator not_anduAndu Scheusan not_andu Data 31 decembrie 2024 14:56:39
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <bits/stdc++.h>

using namespace std;

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

typedef long long ll;

class FenwickTree {

private:
    int n;
    vector<ll> tree;

public:
    FenwickTree(){}
    FenwickTree(ll _n) : n(_n) {
        tree.resize(_n + 1, 0);
    }

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

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

    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;
            int 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;
    FenwickTree tree(n);
    for(int i = 1; i <= n; ++i){
        ll aux; cin >> aux;
        tree.update(i, aux);
    }

    while(queries--){
        short type; cin >> type;
        if(type == 0){
            int position; ll value;
            cin >> position >> value;
            tree.update(position, value);
        }
        else if(type == 1){
            int left, right; cin >> left >> right;
            cout << tree.query(left, right) << '\n';
        }
        else {
            ll target; cin >> target;
            cout << tree.search(target) << '\n';
        }
    }

}

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