Cod sursa(job #2852876)

Utilizator Iordache_CezarIordache Cezar Iordache_Cezar Data 19 februarie 2022 17:35:39
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#define lsb(x) ((x ^ (x - 1)) + 1) / 2
#define NMAX 100004

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

int n, m;
int aib[NMAX];

void citire();
void update(int poz, int val);
int suma(int poz);
int caut_binar(int val);

int main()
{
    citire();
    return 0;
}

void citire()
{
    int cerinta, a, b;
    fin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        fin >> a;
        update(i, a);
    }
    for (int i = 1; i <= m; i++)
    {
        fin >> cerinta;
        if (cerinta == 0)
        {
            fin >> a >> b;
            update(a, b);
        }
        else if (cerinta == 1)
        {
            fin >> a >> b;
            fout << suma(b) - suma(a-1) << '\n';
        }
        else
        {
            fin >> a;
            fout << caut_binar(a) << '\n';
        }
    }
}

int suma(int poz)
{
    int s = 0;
    for (int i = poz; i; i -= lsb(i))
        s += aib[i];
    return s;
}

void update(int poz, int val)
{
    for (int i = poz; i <= n; i += lsb(i))
        aib[i] += val;
}

int caut_binar(int val)
{
    int st = 0, dr = n + 1, mij;
    while (dr - st > 1)
    {
        mij = (st + dr) / 2;
        if (val < suma(mij))
            dr = mij;
        else if (val > suma(mij))
            st = mij;
        else
            return mij;
    }

    return -1;
}