Cod sursa(job #3157252)

Utilizator stefandutastefandutahoria stefanduta Data 14 octombrie 2023 21:50:21
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#define NMAX 100005

using namespace std;

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

long long v[NMAX], aib[NMAX], n;

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

void build()
{
    for (int i = 1; i <= n; ++i)
    {
        aib[i] = aib[i] + v[i];

        if (i + lsb(i) <= n)
            aib[i + lsb(i)] += aib[i];
    }
}

void update(int pos, int val)
{
    while (pos <= n)
    {
        aib[pos] = aib[pos] + val;
        pos = pos + lsb(pos);
    }
}

long long query(int a)
{
    long long suma = 0;
    while (a > 0)
    {
        suma = suma + aib[a];
        a = a - lsb(a);
    }
    return suma;
}

int main()
{
    int m, i, j, a, b, c;
    in >> n >> m;
    for (i = 1; i <= n; ++i)
        in >> v[i];
    build();
    for (i = 1; i <= m; ++i)
    {
        in >> c;
        if (c == 0)
        {
            in >> a >> b;
            update(a, b);
        }
        else if (c == 1)
        {
            in >> a >> b;
            out << query(b) - query(a - 1) << '\n';
        }
        else if (c == 2)
        {
            in >> a;
            int st = 1, dr = n + 1;
            while (dr - st > 1)
            {
                int mij = (st + dr) / 2;
                if (query(mij) > a)
                    dr = mij;
                else
                    st = mij;
            }
            if (st > n || st < 1 || query(st) != a)
                out << -1 << '\n';
            else
                out << st << '\n';
        }
    }
    return 0;
}