Cod sursa(job #3243814)

Utilizator Sasha_12454Eric Paturan Sasha_12454 Data 21 septembrie 2024 15:52:20
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

const std :: string FILENAME = "aib";

std :: ifstream in (FILENAME + ".in");

std :: ofstream out (FILENAME + ".out");

const int NMAX = 1e5 + 5;

int n;

int q;

int cer;

int x;

int y;

int v[NMAX];

long long arb[NMAX];

void update(int x, int val)
{
    while(x <= n)
    {
        arb[x] += val;

        x += (x & (- x));
    }
}

long long query(int x)
{
    long long s = 0;

    while(x)
    {
        s += arb[x];

        x -= (x & (-x));
    }

    return s;
}

int cb(int x)
{
    int ans = 0;

    long long s = 0;

    for(int i = (1 << 30); i > 0; i /= 2)
    {
        if(ans + i <= n && s + arb[ans + i] < x)
        {
            ans += i;

            s += arb[ans];
        }
    }

    if(ans >= n || query(ans + 1) != x)
    {
        return -1;
    }

    return ans + 1;
}

int main()
{

    in >> n >> q;

    for(int i = 1; i <= n; i ++)
    {
        in >> v[i];

        update(i, v[i]);
    }

    while(q --)
    {
        in >> cer;

        if(cer == 0)
        {
            in >> x >> y;

            update(x, y);
        }
        else if(cer == 1)
        {
            in >> x >> y;

            x --;

            out << query(y) - query(x) << '\n';
        }
        else
        {
            in >> x;

            out << cb(x) << '\n';
        }
    }

    return 0;
}