Cod sursa(job #2775810)

Utilizator BogdanRazvanBogdan Razvan BogdanRazvan Data 17 septembrie 2021 12:52:12
Problema Arbori indexati binar Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>

using namespace std;

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

void usain_bolt()
{
    ios::sync_with_stdio(false);
    fin.tie(0);
}

const int N = 1e5 + 5;

int aib[N];

void add(int val, int pos, int n)
{
    for(; pos <= n; pos += pos & (-pos)) {
        aib[pos] += val;
    }
}

int sum(int pos)
{
    int sol = 0;
    for(; pos > 0; pos -= pos & (-pos)) {
        sol += aib[pos];
    }
    return sol;
}

int bs(int x, int n)
{
    int step = 1, i;
    for(; step <= n; step <<= 1);
    for(i = 1; step; step >>= 1) {
        if(i + step <= n && sum(i + step) < x) {
            i += step;
        }
    }

    return (sum(i + 1) == x ? i + 1 : -1);
}

int main()
{
    usain_bolt();

    int n, q;

    fin >> n >> q;
    for(int i = 1; i <= n; ++i) {
        int x;

        fin >> x;
        add(x, i, n);
    }
    for(; q; --q) {
        int type, x, y;

        fin >> type;
        if(type == 0) {
            fin >> x >> y;
            add(y, x, n);
        }
        else if(type == 1) {
            fin >> x >> y;
            fout << sum(y) - sum(x - 1) << "\n";
        }
        else {
            fin >> x;
            fout << bs(x, n) << "\n";
        }
    }
    return 0;
}