Cod sursa(job #2431244)

Utilizator ezioconnorVlad - Gabriel Iftimescu ezioconnor Data 18 iunie 2019 18:44:16
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <cmath>

using namespace std;

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

int v[100001], n, m, x, y;
long long buck[320];
const int sq = 256;

inline long long query1(int x, int y)
{
    int poz = x;
    long long s = 0;
    while (poz % sq != 1 && poz <= y && poz <= n)
    {
        s += v[poz];
        ++poz;
    }
    if (poz > y)
        return s;
    int nr = poz / sq + 1;
    while (sq * nr <= y)
    {
        s += buck[nr];
        ++nr;
    }
    poz = sq * (nr - 1) + 1;
    while (poz <= y)
    {
        s += v[poz];
        ++poz;
    }
    return s;
}

inline int cautbin(int x)
{
    int i, lg;
    for (lg = 1; lg <= n; lg <<= 1);
    for (i = 0; lg; lg >>= 1)
    {
        if (i + lg <= n && query1(0, i + lg) <= x)
            i += lg;
    }
    if (query1(0, i) != x)
        return -1;
    return i;
}

int main()
{
    int tip, a, b;
    in >> n >> m;
    for (int i = 1; i <= n; ++i)
    {
        in >> v[i];
        if (i % sq == 0)
            buck[i / sq] += v[i];
        else
            buck[i / sq + 1] += v[i];
    }
    for (int i = 1; i <= m; ++i)
    {
        in >> tip;
        if (tip != 2)
        {
            in >> a >> b;
            if (!tip)
            {
                v[a] += b;
                if (a % sq == 0)
                    buck[a / sq] += b;
                else
                    buck[a / sq + 1] += b;
            }
            else
                out << query1(a, b) << '\n';
        }
        else
        {
            in >> a;
            out << cautbin(a) << '\n';
        }

    }
    return 0;
}