Cod sursa(job #3144666)

Utilizator Pacurari_SofiaPacurari Sofia Pacurari_Sofia Data 9 august 2023 17:09:38
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>

using namespace std;

int aib[150005], n, m, aux, t, x, y;

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

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

int caut(int x)
{
    int i = 1, pos = 0;
    for(; i <= n; i <<= 1);
    for(; i > 0; i >>= 1)
    {
        if(pos + i <= n)
        {
            if(aib[pos + i] <= x)
            {
                x -= aib[pos + i];
                pos += i;
            }
        }
    }
    return pos;
}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n; ++i)
    {
        cin >> aux;
        update(i, aux);
    }
    for(int i = 1; i <= m; ++i)
    {
        cin >> t;
        if(t == 0)
        {
            cin >> x >> y;
            update(x, y);
        }
        else if(t == 1)
        {
            cin >> x >> y;
            cout << query(y) - query(x - 1) << '\n';
        }
        else
        {
            cin >> x;
            int pos = caut(x - 1);
            if(query(pos + 1) == x){
                cout << pos + 1 << '\n';
            }
            else{
                cout << -1 << '\n';
            }
        }
    }
    return 0;
}