Cod sursa(job #2736672)

Utilizator niculaandreiNicula Andrei Bogdan niculaandrei Data 3 aprilie 2021 19:16:33
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
#define lsb(i) ((i ^ (i - 1)) & i)

using namespace std;

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

const int N_MAX = 1e5 + 5;

int N, M;
int op, a, b;

int AIB[N_MAX];

void Update(int pos, int val)
{
    for (int i = pos; i <= N; i += lsb(i)) {
        AIB[i] += val;
    }
}

int Query(int pos)
{
    int ret = 0;
    for (int i = pos; i > 0; i -= lsb(i)) {
        ret += AIB[i];
    }
    return ret;
}

int Search(int val)
{
    int sum = 0, pos = 0;
    for (int i = 18; i >= 0; i--) {
        if ((pos | (1 << i)) < N && sum + AIB[(pos | (1 << i))] < val) {
            sum += AIB[(pos | (1 << i))];
            pos |= (1 << i);
        }
    }
    if (Query(pos + 1) != val) {
        return -1;
    }
    return pos + 1;
}

int main()
{
    fin >> N >> M;
    for (int i = 1; i <= N; i++) {
        fin >> a;
        Update(i, a);
    }
    for (int i = 1; i <= M; i++) {
        fin >> op;
        if (op == 0){
            fin >> a >> b;
            Update(a, b);
        }
        else if (op == 1) {
            fin >> a >> b;
            fout << Query(b) - Query(a - 1) << "\n";
        }
        else {
            fin >> a;
            fout << Search(a) << "\n";
        }
    }
    return 0;
}