Cod sursa(job #3147225)

Utilizator Alex_BerbescuBerbescu Alexandru Alex_Berbescu Data 24 august 2023 22:34:16
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("fast-math")
#pragma GCC optimize("O3")
#include <bits/stdc++.h>
#define dim 100005
using namespace std;
int ab[dim], n, queries, op, x, y, v[dim];
int lsb(int x)
{
    return (x & (-x));
}
void update(int poz, int val)
{
    for(; poz <= n; poz += lsb(poz))
    {
        ab[poz] += val;
    }
}
int query(int poz)
{
    int sum = 0;
    for(; poz >= 1; poz -= lsb(poz))
    {
        sum += ab[poz];
    }
    return sum;
}
int log_max;
int cb(int nr)
{
   int j = 0, step, s = 0;
   for(step = log_max; step >= 0; --step)
   {
       if(j + (1 << step) <= n && s + ab[j + (1 << step)] <= nr)
       {
           j += (1ll << step);
           s += ab[j];
       }
   }
   if(j && s >= nr)
   {
       return j;
   }
   return -1;

}
ifstream fin("aib.in");
ofstream fout("aib.out");
int32_t main(int argc, char * argv[])
{
    fin >> n >> queries;
    log_max = log2(n);
    for(int i = 1; i <= n; ++i)
    {
        fin >> v[i];
        update(i, v[i]);
    }
    while(queries--)
    {
        fin >> op;
        if(op == 0)
        {
            fin >> x >> y;
            update(x, y);
        }
        if(op == 1)
        {
            fin >> x >> y;
            fout << query(y) - query(x - 1) << '\n';
        }
        if(op == 2)
        {
            fin >> x;
            fout << cb(x) << '\n';
        }
    }
    return 0;
}