Cod sursa(job #2614913)

Utilizator AlexVulpoiuAlexandru Vulpoiu AlexVulpoiu Data 12 mai 2020 20:51:13
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>

using namespace std;

ifstream f("aib.in");
ofstream g("aib.out");

int n, m, i, op, x, y, a[100005], arb[100005];

void actualizeaza(int poz, const int& val)
{
    while(poz <= n)
    {
        arb[poz] += val;
        poz += (poz & (-poz));
    }
}

void construieste_arbore(int v[100005])
{
    int i;

    for(i = 1; i <= n; i++)
        arb[i] = 0;
    for(i = 1; i <= n; i++)
        actualizeaza(i, a[i]);
}

int suma(int poz)
{
    int s;

    s = 0;
    while(poz > 0)
    {
        s += arb[poz];
        poz -= (poz & (-poz));
    }

    return s;
}

int cauta_pozitia(const int& s, const int& st, const int& dr)
{
    int mij;

    if(st > dr)
        return -1;
    mij = (st + dr) / 2;
    if(suma(mij) == s)
        return mij;
    if(suma(mij) > s)
        return cauta_pozitia(s, st, mij - 1);
    else
        return cauta_pozitia(s, mij + 1, dr);
}

int main()
{
    f >> n >> m;
    for(i = 1; i <= n; i++)
        f >> a[i];
    construieste_arbore(a);
    while(m)
    {
        f >> op >> x;

        if(!op)
        {
            f >> y;
            a[x] += y;
            actualizeaza(x, y);
        }
        else
            if(op == 1)
            {
                f >> y;
                g << suma(y) - suma(x - 1) << '\n';
            }
            else
                g << cauta_pozitia(x, 1, n) << '\n';

        m--;
    }

    f.close();
    g.close();

    return 0;
}