Cod sursa(job #2198725)

Utilizator SqueekDanielTodasca Daniel SqueekDaniel Data 25 aprilie 2018 11:01:22
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
#define dimn 100005

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

int N, M;
int tree[dimn];

void update(int pos, int val) {
     do {
        tree[pos] += val;
        pos += pos & -pos;
     } while (pos <= N);
}
int search_tree(int val) {
    int step=1;
    while(step<N) step <<= 1;

    for (int i=0; step; step >>= 1) {
         if(i + step <= N)
            if(val >= tree[i+step] ) {
                i += step, val -= tree[i];
                if (!val) return i;
            }
    } return -1;
}
int query(int pos) {
    int p=0, sum=0;
    while (pos) {
          sum += tree[pos];
          pos = pos&(pos-1);
    } return sum;
}

void citire() {
    f >> N >> M;
    for (int i=1, x; i<=N; i++) {
        f >> x;
        update(i, x);
    }
}
void rezolvare() {
    for (int i=0, tip, a, b; i<M; i++) {
        f >> tip;
        if(tip == 2) {
            f >> a;
            g << search_tree(a) << "\n" ;
        }
        else if(tip == 1) {
            f >> a >> b;
            g << query(b) - query(a-1) << "\n" ;
        }
        else if(tip == 0) {
            f >> a >> b;
            update(a, b);
        }
    }
}

int main()
{
    citire();
    rezolvare();

    return 0;
}