Cod sursa(job #2642632)

Utilizator GiosinioGeorge Giosan Giosinio Data 16 august 2020 13:19:21
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
/*https://www.topcoder.com/community/competitive-programming/tutorials/binary-indexed-trees/
op-0 si op-1 = log2(n)
op-2 = (log2(n))^2 cu cautare binara */

#include <iostream>
#include <fstream>
#define DIM 100005

using namespace std;

ifstream f("aib.in");
ofstream g("aib.out");

int N,M, tree[DIM];

int secv(int ind){
    int sum = 0, c = 0;
    while(ind > 0){
        sum += tree[ind];
        while(!(ind & (1 << c)))
            c++;
        ind -= (1 << c);
        c++;
    }
    return sum;
}

void update(int tree[], int ind, int key){
    int MaxInd = N, c = 0;
    while(ind <= MaxInd){
        tree[ind] += key;
        int c=0;
        while(!(ind & (1 << c)))
            c++;
        ind += (1 << c);
        c++;
    }
}

int cautare(int tree[], int N, int key){
    int st = 1, dr = N;
    while(st <= dr){
        int mij = (st + dr)/2;
        int s = secv(mij);
        if(s == key)
            return mij;
        else if(s > key)
            dr = mij-1;
        else
            st = mij + 1;
    }
    return -1;
}

int main()
{
    f>>N>>M;
    int val;
    for(int i=1; i<=N; i++){
        f>>val;
        update(tree,i,val);
    }
    int op,a,b;
    for(int i=1; i<=M; i++){
        f>>op;
        if(op < 2){
            f>>a>>b;
            if(op == 0)
                update(tree,a,b);
            else
                g<<secv(b) - secv(a-1)<<"\n";
        }
        else{
            f>>a;
            g<<cautare(tree,N,a)<<"\n";
        }
    }
}