Cod sursa(job #2750503)

Utilizator Razvan48Capatina Razvan Nicolae Razvan48 Data 11 mai 2021 17:56:00
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>

using namespace std;

const int NMAX = 100000;

int n;
unsigned int aib[1 + NMAX];

void build()
{
  for (int i = 1; i <= n; i++)
  {
    int j = i + (i & -i);

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

void update(int pos, unsigned int val)
{
  for (; pos <= n; pos += pos & -pos)
    aib[pos] += val;
}

unsigned int query(int pos)
{
  unsigned int sol = 0;

  for (; pos > 0; pos -= pos & -pos)
    sol += aib[pos];

  return sol;
}

int expStart;

void preCalc()
{
  int putere2 = 1;

  while (putere2 * 2 <= n)
  {
    putere2 *= 2;
    expStart++;
  }
}

int cautare(unsigned int sum)
{
  int pos = 0;

  for (int step = expStart; step >= 0; step--)
  {
    int next = pos + (1 << step);

    if (next <= n && aib[next] <= sum)
    {
      pos = next;
      sum -= aib[next];
    }
  }

  if (sum != 0)
    return -1;
  return pos;
}

int main()
{
  ifstream in("aib.in");
  ofstream out("aib.out");
  int m;

  in >> n >> m;

  preCalc();

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

  build();

  for (int j = 1; j <= m; j++)
  {
    int op;
    in >> op;

    if (op == 0)
    {
      int a, b;
      in >> a >> b;

      update(a, b);
    }
    else if (op == 1)
    {
      int a, b;
      in >> a >> b;

      out << query(b) - query(a - 1) << '\n';
    }
    else
    {
      unsigned int a;
      in >> a;

      out << cautare(a) << '\n';
    }
  }

  return 0;
}