Cod sursa(job #2730823)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 26 martie 2021 21:53:44
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <fstream>

const int NMAX = 1e5;
const int VMAX = 1e5;
const int LOG = 16;

int last_p2[1 + VMAX];
int rmq[1 + NMAX][1 + LOG];

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

  int p2 = 0;
  for (int i = 1; i <= VMAX; ++i) {
    if (1 << (p2 + 1) <= i)
      ++p2;

    last_p2[i] = p2;
  }

  int n, m;
  in >> n >> m;

  for (int i = 1; i <= n; ++i)
    in >> rmq[i][0];

  for (int depth = 1; depth <= LOG; ++depth) {
    for (int i = 1; i <= n - (1 << depth) + 1; ++i)
      rmq[i][depth] = std::min(rmq[i][depth - 1], rmq[i + (1 << (depth - 1))][depth - 1]);
  }

  for (int i = 1; i <= m; ++i) {
    int left, right;
    in >> left >> right;

    if (left > right)
      std::swap(left, right);

    int len = last_p2[right - left];
    out << std::min(rmq[left][len], rmq[right - (1 << len) + 1][len]) << '\n';
  }

  return 0;
}