Cod sursa(job #1100822)

Utilizator 2dorTudor Ciurca 2dor Data 7 februarie 2014 15:45:46
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
using namespace std;

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

const int MAXN = 100005;
int N, M, tree[MAXN];

void Update(int index, int val) {
    while (index <= N) {
        tree[index] += val;
        index += index & -index;
    }
}

int Query(int index) {
    int sum = 0;
    while (index) {
        sum += tree[index];
        index -= index & -index;
    }
    return sum;
}

void Read() {
    fin >> N >> M;
    int nr;
    for (int i = 1; i <= N; ++i) {
        fin >> nr;
        Update(i, nr);
    }
}

int BinSearch(int K) {
    int Left = 1; int Right = N; int Middle;
    while (Right - Left > 1) {
        Middle = (Left + Right) >> 1;
        if (Query(Middle) >= K)
            Right = Middle;
        else
            Left = Middle;
    }
    if (Query(Left) == K)
        return Left;
    if (Query(Right) == K)
        return Right;
    return -1;
}

int main() {
    Read();
    int op, a, b;
    while (M--) {
        fin >> op;
        if (op == 2) {
            fin >> a;
            fout << BinSearch(a) << '\n';
        }else {
            fin >> a >> b;
            if (op == 0)
                Update(a, b);
            else
                fout << Query(b) - Query(a - 1) << '\n';
        }
    }
    fin.close();
    fout.close();
    return 0;
}