Cod sursa(job #2913680)

Utilizator tiut_cristianTiut Cristian tiut_cristian Data 15 iulie 2022 23:32:47
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;

int n, m, t;
int Arb[100001];
int c, s;

int sum(int poz)
{
    c = 0, s = 0;
    while (poz > 0)
    {
        s += Arb[poz];
        while ( !(poz & (1<<c)) )
            c++;
        poz -= (1<<c);
        c++;
    }
    return s;
}

void update(int poz, int val)
{
     c = 0;
     while ( poz <= n )
     {
        Arb[poz] += val;
        while ( !(poz & (1<<c)) )
            c++;
        poz += (1<<c);
        c += 1;
     }
}

int cautare(int val)
{
    int step = 1;
    while(step < n)
        step <<= 1;

    int i = 0;
    while(step)
    {
        if(i + step <= n && Arb[i+step] <= val)
        {
            i += step;
            val -= Arb[i];
            if (!val)
                return i;
        }
        step >>= 1;
    }
    return -1;
}

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

    int k, x, y;

    fin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        fin >> t;
        update(i,t);
    }

    for (int i = 1; i <= m; i++)
    {
        fin >> k;
        if(k == 2)
        {
            fin >> x;
            fout << cautare(x) << '\n';
        }
        else
        {
            fin >> x >> y;
            if(k)
                fout << sum(y)-sum(x-1) << '\n';
            else
                update(x,y);
        }
    }

    return 0;
}