33#ifndef OR_TOOLS_UTIL_RANGE_MINIMUM_QUERY_H_
34#define OR_TOOLS_UTIL_RANGE_MINIMUM_QUERY_H_
45template <
typename T,
typename Compare = std::less<T>>
59 const std::vector<T>&
array()
const;
63 std::vector<std::vector<T>> cache_;
69template <
typename T,
typename Compare = std::less<T>>
84 const std::vector<T>&
array()
const;
88 static std::vector<int> CreateIndexVector(
int n);
89 struct IndexComparator {
90 bool operator()(
int lhs_idx,
int rhs_idx)
const;
91 const std::vector<T> array;
98template <
typename T,
typename Compare>
106template <
typename T,
typename Compare>
110 cmp_(
std::move(cmp)) {
111 const int array_size =
array.size();
112 cache_[0] = std::move(
array);
113 for (
int row_idx = 1; row_idx < cache_.size(); ++row_idx) {
114 const int row_length = array_size - (1 << row_idx) + 1;
115 const int window = 1 << (row_idx - 1);
116 cache_[row_idx].resize(row_length);
117 for (
int col_idx = 0; col_idx < row_length; ++col_idx) {
118 cache_[row_idx][col_idx] =
119 std::min(cache_[row_idx - 1][col_idx],
120 cache_[row_idx - 1][col_idx + window], cmp_);
125template <
typename T,
typename Compare>
130 DCHECK_LE(
to, array().
size());
132 const int window = 1 << log_diff;
133 const std::vector<T>&
row = cache_[log_diff];
134 return std::min(
row[from],
row[
to - window], cmp_);
137template <
typename T,
typename Compare>
143template <
typename T,
typename Compare>
145 std::vector<T> array)
148template <
typename T,
typename Compare>
151 : cmp_({std::move(
array), std::move(cmp)}),
152 rmq_(CreateIndexVector(cmp_.array.size()), cmp_) {}
154template <
typename T,
typename Compare>
156 int from,
int to)
const {
157 return rmq_.GetMinimumFromRange(from,
to);
160template <
typename T,
typename Compare>
162 int lhs_idx,
int rhs_idx)
const {
163 return cmp(array[lhs_idx], array[rhs_idx]);
166template <
typename T,
typename Compare>
167std::vector<int> RangeMinimumIndexQuery<T, Compare>::CreateIndexVector(
int n) {
168 std::vector<int> result(n, 0);
169 std::iota(result.begin(), result.end(), 0);
173template <
typename T,
typename Compare>
RangeMinimumIndexQuery(const RangeMinimumIndexQuery &)=delete
This type is neither copyable nor movable.
RangeMinimumIndexQuery(std::vector< T > array)
RangeMinimumIndexQuery implementation.
const std::vector< T > & array() const
Returns the original array.
RangeMinimumIndexQuery & operator=(const RangeMinimumIndexQuery &)=delete
int GetMinimumIndexFromRange(int from, int to) const
T GetMinimumFromRange(int from, int to) const
const std::vector< T > & array() const
RangeMinimumQuery(std::vector< T > array, Compare cmp)
RangeMinimumQuery & operator=(const RangeMinimumQuery &)=delete
RangeMinimumQuery(const RangeMinimumQuery &)=delete
This type is neither copyable nor movable.
RangeMinimumQuery(std::vector< T > array)
RangeMinimumQuery implementation.
In SWIG mode, we don't want anything besides these top-level includes.
int MostSignificantBitPosition32(uint32_t n)
trees with all degrees equal to