Cod sursa(job #2753459)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 22 mai 2021 22:46:04
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>

const int NMAX = 1e5;

int n;
int bit[1 + NMAX];

int logMax;

inline int lsb(int a) {
  return a & -a;
}

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

int query(int i) {
  int ans = 0;
  while (i > 0) {
    ans += bit[i];
    i -= lsb(i);
  }
  return ans;
}

int search(int val) {
  if (val == 0)
    return -1;

  int pos = 0;
  for (int exp = logMax; exp >= 0; --exp) {
    if (pos + (1 << exp) <= n && bit[pos + (1 << exp)] <= val) {
      pos += (1 << exp);
      val -= bit[pos];
    }

    if (val == 0)
      return pos;
  }

  return -1;
}

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

  int m;
  in >> n >> m;

  logMax = 1;
  while ((1 << logMax) <= n)
    ++logMax;
  --logMax;

  for (int i = 1; i <= n; ++i) {
    int val;
    in >> val;

    update(i, val);
  }

  for (int i = 1; i <= m; ++i) {
    int type;
    in >> type;

    if (type == 0) {
      int a, val;
      in >> a >> val;

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

      out << query(b) - query(a - 1) << '\n';
    }
    else if (type == 2) {
      int val;
      in >> val;

      out << search(val) << "\n";
    }
    else
      exit(-147);
  }

  return 0;
}