Cod sursa(job #3290734)

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

using namespace std;

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

const int NMAX = 1e1+5;

int n, v[NMAX], sp[NMAX];
unsigned int 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;
}

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

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

int main()
{
    int t;
    fin >> n >> t;
    for (int i = 1; i <= n; i++)
    {
        fin >> v[i];
        sp[i] = v[i]+sp[i-1];
        aib[i] = sp[i]-sp[i-lsb(i)];
    }
    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)
                poz = -1;
            fout << poz << nl;
        }
    }
    return 0;
}