Cod sursa(job #1344466)

Utilizator tudorv96Tudor Varan tudorv96 Data 16 februarie 2015 19:09:07
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <iostream>
using namespace std;

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

const int N = 100005;

int aib[N], n, m, type, a, b;

void update(int i, int &a) {
    while (i <= n) {
        aib[i] += a;
        i += i & -i;
    }
}

int query(int i) {
    int sum = 0;
    while (i > 0) {
        sum += aib[i];
        i -= i & -i;
    }
    return sum;
}

int bs(int &x) {
    int sol = 0, step;
    for (step = 1; (step << 1) <= n; step <<= 1);
    for (; step; step >>= 1)
        if (sol + step <= n && query(sol + step) <= x)
            sol += step;
    if (sol > 0 && query(sol) == x)
        return sol;
    return -1;
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        fin >> a;
        update(i, a);
    }
    while (m--) {
        fin >> type >> a;
        if (!type) {
            fin >> b;
            update(a, b);
        }
        else
            if (type == 1) {
                fin >> b;
                fout << query(b) - query(a-1) << "\n";
            }
        else
            if (type == 2)
                fout << bs(a) << "\n";
    }
}