cp-library

C++ Library for Competitive Programming

View the Project on GitHub emthrm/cp-library

:heavy_check_mark: データ構造/sparse table
(test/data_structure/sparse_table.test.cpp)

Depends on

Code

/*
 * @title データ構造/sparse table
 *
 * verification-helper: PROBLEM https://judge.yosupo.jp/problem/staticrmq
 */

#include <algorithm>
#include <iostream>
#include <vector>

#include "emthrm/data_structure/sparse_table.hpp"

int main() {
  int n, q;
  std::cin >> n >> q;
  std::vector<int> a(n);
  for (int i = 0; i < n; ++i) {
    std::cin >> a[i];
  }
  emthrm::SparseTable<int> dst(
      a, [](const int a, const int b) -> int { return std::min(a, b); });
  while (q--) {
    int l, r;
    std::cin >> l >> r;
    std::cout << dst.query(l, r) << '\n';
  }
  return 0;
}
#line 1 "test/data_structure/sparse_table.test.cpp"
/*
 * @title データ構造/sparse table
 *
 * verification-helper: PROBLEM https://judge.yosupo.jp/problem/staticrmq
 */

#include <algorithm>
#include <iostream>
#include <vector>

#line 1 "include/emthrm/data_structure/sparse_table.hpp"



#line 5 "include/emthrm/data_structure/sparse_table.hpp"
#include <bit>
#include <cassert>
#include <functional>
#line 9 "include/emthrm/data_structure/sparse_table.hpp"

namespace emthrm {

template <typename Band>
struct SparseTable {
  using BinOp = std::function<Band(Band, Band)>;

  SparseTable() = default;

  explicit SparseTable(const std::vector<Band>& a, const BinOp bin_op) {
    init(a, bin_op);
  }

  void init(const std::vector<Band>& a, const BinOp bin_op_) {
    bin_op = bin_op_;
    const int n = a.size();
    assert(n > 0);
    lg.assign(n + 1, 0);
    for (int i = 2; i <= n; ++i) {
      lg[i] = lg[i >> 1] + 1;
    }
    const int table_h = std::countr_zero(std::bit_floor(a.size())) + 1;
    data.assign(table_h, std::vector<Band>(n));
    std::copy(a.begin(), a.end(), data.front().begin());
    for (int i = 1; i < table_h; ++i) {
      for (int j = 0; j + (1 << i) <= n; ++j) {
        data[i][j] = bin_op(data[i - 1][j], data[i - 1][j + (1 << (i - 1))]);
      }
    }
  }

  Band query(const int left, const int right) const {
    assert(left < right);
    const int h = lg[right - left];
    return bin_op(data[h][left], data[h][right - (1 << h)]);
  }

 private:
  BinOp bin_op;
  std::vector<int> lg;
  std::vector<std::vector<Band>> data;
};

}  // namespace emthrm


#line 12 "test/data_structure/sparse_table.test.cpp"

int main() {
  int n, q;
  std::cin >> n >> q;
  std::vector<int> a(n);
  for (int i = 0; i < n; ++i) {
    std::cin >> a[i];
  }
  emthrm::SparseTable<int> dst(
      a, [](const int a, const int b) -> int { return std::min(a, b); });
  while (q--) {
    int l, r;
    std::cin >> l >> r;
    std::cout << dst.query(l, r) << '\n';
  }
  return 0;
}
Back to top page