Cod sursa(job #2648711)

Utilizator buhaidarius@gmail.comBuhai Darius [email protected] Data 12 septembrie 2020 12:20:08
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <iostream>
#include <fstream>

#define MAXN 100001

using namespace std;

ifstream fin("aib.in");
ofstream fout("aib.out");

int BITree[MAXN];

void update(int pos, int val, int n){
    while(pos <= n){
        BITree[pos] += val;
        pos += pos & (-pos);
    }
}

int sum(int pos, int n){
    int sum = 0;
    while(pos > 0){
        sum += BITree[pos];
        pos -= pos & (-pos);
    }
    return sum;
}

int search(int val, int n){
    int pow = 1, i;
    while(pow<n) pow*=2;
    for(i = 0;pow>0;pow/=2)
        if(pow+i <= n && val >= BITree[pow+i]){
            val -= BITree[pow+i];
            i += pow;
            if(val==0)
                return i;
        }
    return -1;
}

int main() {
    int x, y, op, n, m, i=0;
    fin>>n>>m;
    for(int i=0;i<n;i++){
        fin>>x;
        update(i+1, x, n);
    }
    while(m--){
        fin>>op>>x;
        if(op==0){
            fin>>y;
            update(x, y, n);
        }else if(op==1){
            fin>>y;
            fout<<sum(y, n)-sum(x-1,n)<<'\n';
        }else{
            fout<<search(x, n)<<'\n';
        }
    }
    return 0;
}