Cod sursa(job #2759335)

Utilizator lahayonTester lahayon Data 16 iunie 2021 23:39:40
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>	
#include <vector>

using namespace std;

void update(vector<int>& AIB, int node, const int& value, const int& N){

    while(node <= N){
        AIB[node] += value;
        node += node & (-node);
    }
}

int sum(const vector<int>& AIB, int node){

    int sum = 0;
    while(node > 0){
        sum += AIB[node];
        node -= node & (-node);
    }
    return sum;
}

int bsearch(int low, int high, const vector<int>& AIB, const int& target){

    int pos = -1;
    while(low <= high){

        int mid = (low + high) / 2;
        int currsum = sum(AIB, mid);
        if(currsum < target)
            low = mid + 1;
        else if(currsum > target)
            high = mid - 1;
        else{
            pos = mid;
            high = mid - 1;
        }
    }

    return pos;
}

int main(){

    ifstream cin("aib.in");
    ofstream cout("aib.out");
    
    int N, M;
    cin >> N >> M;
    vector<int> AIB(N + 1, 0);

    for(int i = 0, x; i < N; ++i){
        cin >> x;
        update(AIB, i + 1, x, N);
    }

    for(int op, x, y; M > 0; --M){
        cin >> op;
        switch(op){
            case 0:
                cin >> x >> y;
                update(AIB, x, y, N);
                break;
            case 1:
                cin >> x >> y;
                cout << sum(AIB, y) - sum(AIB, x - 1) << "\n";
                break;
            case 2:
                cin >> x;
                cout << bsearch(1, N, AIB, x) << "\n";
                break;
            default:
                break;
        }
    }

    cin.close();
    cout.close();


    return 0;	
}