Cod sursa(job #1955629)

Utilizator dumbraveanbDumbravean Bogdan dumbraveanb Data 6 aprilie 2017 09:21:10
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int n, m, A[100005];

void Update(int pos, int val) {
    for(; pos <= n; pos += pos ^ (pos - 1) & pos)
        A[pos] += val;
}

int Query(int pos) {
    int sum = 0;
    for(; pos; pos -= pos ^ (pos - 1) & pos)
        sum += A[pos];
    return sum;
}

int Bs(int val) {
    int sol = 0, pas = 1;
    while(pas * 2 <= n)
        pas <<= 1;

    for(; pas; pas >>= 1)
        if(sol + pas <= n && val >= A[sol + pas]) {
            sol += pas;
            val -= A[sol];
            if(!val) return sol;
        }
    return -1;
}

int main()
{
    fin >> n >> m;
    int x;
    for(int i = 1; i <= n; ++i) {
        fin >> x;
        Update(i, x);
    }
    int op, y;
    for(int i = 1; i <= m; ++i) {
        fin >> op;
        if(op < 2) {
            fin >> x >> y;
            if(!op)
                Update(x, y);
            else
                fout << Query(y) - Query(x - 1) << '\n';

            } else {
                fin >> x;
                fout << Bs(x) << '\n';
            }
    }
    return 0;
}