Cod sursa(job #3290739)

Utilizator Mihai_999Diaconeasa Mihai Mihai_999 Data 31 martie 2025 19:16:26
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#define nl '\n'

using namespace std;

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

const int NMAX = 1e5+5;

int n, aib[NMAX];

int lsb(int x)
{
    return (x & (-x));
}

void add(int x, int val)
{
    for (int i = x; i <= n; i+=lsb(i))
        aib[i]+=val;
    return;
}

int sum(int x)
{
    int res = 0;
    for (int i = x; i > 0; i-=lsb(i))
        res+=aib[i];
    return res;
}

int cb(int val)
{
    int pow = 1, s = 0;
    while (pow <= n)
        pow<<=1;
    int i = 0;
    for (; pow; pow>>=1)
    {
        int poz = i+pow;
        if (poz <= n && aib[poz]+s <= val)
        {
            s+=aib[poz];
            i+=pow;
        }
    }
    return i;
}

int main()
{
    int t, x;
    fin >> n >> t;
    for (int i = 1; i <= n; i++)
    {
        fin >> x;
        add(i, x);
    }
    while (t--)
    {
        int c, a, b;
        fin >> c;
        if (c == 0)
        {
            fin >> a >> b;
            add(a, b);
        }
        if (c == 1)
        {
            fin >> a >> b;
            fout << sum(b)-sum(a-1) << nl;
        }
        if (c == 2)
        {
            fin >> a;
            int poz = cb(a);
            if (sum(poz) != a || a == 0)
                poz = -1;
            fout << poz << nl;
        }
    }
    return 0;
}