競技プログラミング用 C++ ライブラリ
data_structure/range_lis_query.hpp · GitHub で見る
共通ページ
変更のない列に対して、半開区間 [l,r) の最長増加部分列の長さを求めます。問い合わせは構築後に順次指定でき、順列以外の列や重複する値にも対応します。
#include "lib/data_structure/range_lis_query.hpp"
std::vector<int> a{3, 1, 2, 2, 4};
RangeLISQuery<> tree(a);
int x = tree.query(0, 5); // 3: 1, 2, 4
int y = tree.query(1, 4); // 2: 1, 2
int z = tree.query(2, 2); // 0
RangeLISQuery<false> weak(a);
int w = weak.query(0, 5); // 4: 1, 2, 2, 4
RangeLISQuery<> decreasing(a, std::greater<>{});
int d = decreasing.query(0, 5); // 2: 3, 1
既定は狭義増加です。RangeLISQuery<false> は等しい値を続けて選べる広義増加を求めます。比較関数には厳密弱順序を指定します。狭義では compare(x,y)、広義では !compare(y,x) を満たす順に選びます。
| 操作 | 内容・返り値 | 計算量 |
|---|---|---|
RangeLISQuery<Strict=true>() |
空の列を作る | \(O(1)\) |
RangeLISQuery<Strict>(a,compare=std::less<>{}) |
列 a から構築する |
\(O(n\log^2 n)\) |
build(a,compare=std::less<>{}) |
列と比較を指定して構築し直す | \(O(n\log^2 n)\) |
query(l,r) const |
[l,r) の最長増加部分列の長さを int で返す |
\(O(\log n)\) |
size() / empty()
|
列の長さ / 空列かどうか | \(O(1)\) |
clear() |
空列に戻す | \(O(n)\) |
swap(other) |
同じ Strict の構造と内容を交換する |
\(O(1)\) |
a には const でサイズ取得とランダムアクセスができる範囲を渡します。vector・array・C 配列・span・deque・string_view などを利用できます。要素のコピーや値の加減算は不要で、比較できれば使えます。元の列を変更・破棄しても、構築済みの答えには影響しません。
区間は 0 <= l <= r <= size()、列の長さは INT_MAX 以下とします。空の列や空区間の答えは 0 です。部分列そのものの復元や、構築後の要素更新には対応しません。列全体の長さや復元だけが必要な場合は LIS を利用できます。
参考: Library Checker: Static Range LIS Query、Tiskin: Semi-local string comparison。
列の長さを \(n\) とし、比較を定数時間とすると、前計算は \(O(n\log^2 n)\) 時間、問い合わせは \(O(\log n)\) 時間・\(O(1)\) 追加空間です。保持空間は \(O(n\log n)\) bit、前計算の作業領域は \(O(n)\) word です。
#ifndef RANGE_LIS_QUERY_HPP
#define RANGE_LIS_QUERY_HPP
#include "../components/quad_bit_vector.hpp"
#include "../components/range_lis.hpp"
#include <algorithm>
#include <array>
#include <bit>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <limits>
#include <numeric>
#include <ranges>
#include <utility>
#include <vector>
template <bool Strict = true>
class RangeLISQuery {
int n = 0;
std::vector<QuadBitVector> bits;
std::vector<std::array<int, 4>> offsets;
[[gnu::always_inline]] int query_impl(int l, int r) const {
int length = r - l, removed = 0;
unsigned upper = unsigned(r);
for (int level = 0; level < int(bits.size()) && l < r; ++level) {
int digit = (upper >> (2 * (int(bits.size()) - 1 - level))) & 3;
const auto &row = bits[level];
removed += row.below(r, digit) - row.below(l, digit);
l = offsets[level][digit] + row.rank(l, digit);
r = offsets[level][digit] + row.rank(r, digit);
}
return length - removed;
}
#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("popcnt"))) int query_popcnt(int l, int r) const { return query_impl(l, r); }
#endif
public:
RangeLISQuery() = default;
template <class Range, class Compare = std::less<>>
requires std::ranges::random_access_range<const Range> && std::ranges::sized_range<const Range>
explicit RangeLISQuery(const Range &values, Compare compare = {}) { build(values, std::move(compare)); }
RangeLISQuery(const RangeLISQuery &) = default;
RangeLISQuery &operator=(const RangeLISQuery &) = default;
RangeLISQuery(RangeLISQuery &&other) noexcept { swap(other); }
RangeLISQuery &operator=(RangeLISQuery &&other) noexcept {
if (this != &other) {
RangeLISQuery replacement(std::move(other));
swap(replacement);
}
return *this;
}
void swap(RangeLISQuery &other) noexcept {
std::swap(n, other.n);
bits.swap(other.bits);
offsets.swap(other.offsets);
}
int size() const { return n; }
bool empty() const { return n == 0; }
void clear() { n = 0; bits.clear(); offsets.clear(); }
template <class Range, class Compare = std::less<>>
requires std::ranges::random_access_range<const Range> && std::ranges::sized_range<const Range>
void build(const Range &values, Compare compare = {}) {
assert(std::ranges::size(values) <= std::size_t(std::numeric_limits<int>::max()));
n = int(std::ranges::size(values));
bits.clear();
offsets.clear();
if (!n) return;
auto first = std::ranges::begin(values);
std::vector<int> order(n), permutation(n);
std::iota(order.begin(), order.end(), 0);
std::sort(order.begin(), order.end(), [&](int a, int b) {
if (compare(first[a], first[b])) return true;
if (compare(first[b], first[a])) return false;
if constexpr (Strict) return a > b;
else return a < b;
});
for (int i = 0; i < n; ++i) permutation[order[i]] = i;
auto endpoints = range_lis_detail::seaweed(permutation);
std::vector<std::uint32_t> current(n), next(n);
for (int i = 0; i < n; ++i) current[i] = endpoints[i] < 0 ? unsigned(n) : unsigned(endpoints[i]);
int levels = (std::bit_width(unsigned(n)) + 1) / 2;
bits.reserve(levels);
offsets.resize(levels);
for (int level = 0; level < levels; ++level) {
int shift = 2 * (levels - 1 - level);
auto &row = bits.emplace_back(n);
row.build(current, shift);
auto counts = row.ranks(n);
for (int digit = 1; digit < 4; ++digit) offsets[level][digit] = offsets[level][digit - 1] + counts[digit - 1];
if (level + 1 == levels) break;
auto positions = offsets[level];
for (auto value : current) next[positions[(value >> shift) & 3]++] = value;
current.swap(next);
}
}
int query(int l, int r) const {
assert(0 <= l && l <= r && r <= n);
if (r - l <= 1) return r - l;
#if defined(__x86_64__) || defined(__i386__)
static const bool hardware = __builtin_cpu_supports("popcnt");
if (hardware) return query_popcnt(l, r);
#endif
return query_impl(l, r);
}
};
#endif
#line 1 "data_structure/range_lis_query.hpp"
#line 1 "components/quad_bit_vector.hpp"
#include <algorithm>
#include <array>
#include <bit>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <vector>
#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
#endif
struct QuadBitVector {
struct Block {
std::uint64_t low = 0, high = 0;
std::array<int, 4> prefix{};
};
int n;
std::vector<Block> blocks;
#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2"))) static void pack_avx2(const std::uint32_t *a, int n, int shift, Block *blocks) {
auto low_shift = _mm_cvtsi32_si128(31 - shift), high_shift = _mm_cvtsi32_si128(30 - shift);
for (int w = 0; w < (n >> 6) + bool(n & 63); ++w) {
int start = w * 64;
std::uint64_t low = 0, high = 0;
int length = std::min(64, n - start), j = 0;
for (; j + 8 <= length; j += 8) {
auto x = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(a + start + j));
low |= std::uint64_t(_mm256_movemask_ps(_mm256_castsi256_ps(_mm256_sll_epi32(x, low_shift)))) << j;
high |= std::uint64_t(_mm256_movemask_ps(_mm256_castsi256_ps(_mm256_sll_epi32(x, high_shift)))) << j;
}
for (; j < length; ++j) {
low |= std::uint64_t((a[start + j] >> shift) & 1) << j;
high |= std::uint64_t((a[start + j] >> (shift + 1)) & 1) << j;
}
blocks[w].low = low;
blocks[w].high = high;
}
blocks[n >> 6].low = n & 63 ? blocks[n >> 6].low : 0;
blocks[n >> 6].high = n & 63 ? blocks[n >> 6].high : 0;
}
#endif
explicit QuadBitVector(int n = 0) : n(n), blocks((n >> 6) + 1) {}
void build(const std::vector<std::uint32_t> &a, int shift) {
assert(a.size() == std::size_t(n) && 0 <= shift && shift <= 30);
[[maybe_unused]] bool vectorized = false;
#if defined(__x86_64__) || defined(__i386__)
vectorized = n >= 64 && __builtin_cpu_supports("avx2");
if (vectorized) pack_avx2(a.data(), n, shift, blocks.data());
#endif
std::array<int, 4> counts{};
for (int w = 0; w < static_cast<int>(blocks.size()); ++w) {
std::uint64_t low = 0, high = 0;
int start = w * 64, length = std::min(64, n - start);
if (vectorized) low = blocks[w].low, high = blocks[w].high;
else
for (int j = 0; j < length; ++j) {
low |= std::uint64_t((a[start + j] >> shift) & 1) << j;
high |= std::uint64_t((a[start + j] >> (shift + 1)) & 1) << j;
}
blocks[w] = {low, high, counts};
int c1 = std::popcount(low & ~high), c2 = std::popcount(~low & high), c3 = std::popcount(low & high);
counts[0] += length - c1 - c2 - c3;
counts[1] += c1;
counts[2] += c2;
counts[3] += c3;
}
}
std::uint64_t mask(const Block &b, int digit) const {
return ((digit & 1) ? b.low : ~b.low) & ((digit & 2) ? b.high : ~b.high);
}
int rank(int r, int digit) const {
const auto &b = blocks[r >> 6];
return b.prefix[digit] + std::popcount(mask(b, digit) & ((std::uint64_t(1) << (r & 63)) - 1));
}
int below(int r, int digit) const {
if (!digit) return 0;
if (digit == 1) return rank(r, 0);
if (digit == 3) return r - rank(r, 3);
const auto &b = blocks[r >> 6];
return b.prefix[0] + b.prefix[1] + std::popcount(~b.high & ((std::uint64_t(1) << (r & 63)) - 1));
}
std::array<int, 4> ranks(int r) const {
const auto &b = blocks[r >> 6];
std::uint64_t m = (std::uint64_t(1) << (r & 63)) - 1;
std::array<int, 4> a;
a[1] = b.prefix[1] + std::popcount(b.low & ~b.high & m);
a[2] = b.prefix[2] + std::popcount(~b.low & b.high & m);
a[3] = b.prefix[3] + std::popcount(b.low & b.high & m);
a[0] = r - a[1] - a[2] - a[3];
return a;
}
};
#line 1 "components/range_lis.hpp"
#line 6 "components/range_lis.hpp"
#include <numeric>
#include <span>
#include <utility>
#line 10 "components/range_lis.hpp"
namespace range_lis_detail {
inline void multiply(int n, const int *a, const int *b, int *result, int *work) {
if (n == 1) {
result[0] = 0;
return;
}
int *inverse = work;
work += n;
int middle = n / 2;
for (int side = 0; side < 2; ++side) {
int length = side ? n - middle : middle;
int *left = work, *rows = left + length, *right = rows + length;
int *columns = right + length, *child = columns + length;
int x = 0, y = 0;
for (int i = 0; i < n; ++i) {
if ((a[i] >= middle) == bool(side)) {
left[x] = a[i] - (side ? middle : 0);
rows[x++] = i;
}
if ((b[i] >= middle) == bool(side)) {
right[y] = b[i] - (side ? middle : 0);
columns[y++] = i;
}
}
multiply(length, left, right, child, child + length);
for (int i = 0; i < length; ++i) {
int column = columns[child[i]];
result[rows[i]] = column;
inverse[column] = rows[i];
}
}
int row = n, low = 0, high = 0, low_delta = 0, high_delta = 0;
auto step = [&](int column) {
return b[column] < middle ? inverse[column] >= row : inverse[column] < row;
};
while (row) {
while (high < n && high_delta + step(high) == 0) {
high_delta = 0;
++high;
}
--row;
if (a[row] < middle) {
low_delta -= result[row] >= low;
high_delta -= result[row] >= high;
} else {
low_delta -= result[row] < low;
high_delta -= result[row] < high;
}
while (low_delta) low_delta += step(low++);
if (low > high) result[row] = high;
}
}
inline std::vector<int> compose(const std::vector<int> &a, const std::vector<int> &b) {
int n = int(a.size());
std::vector<int> left(n), right(n), inverse(n, -1), rows, columns;
rows.reserve(n);
columns.reserve(n);
for (int i = 0; i < n; ++i) if (a[i] >= 0) {
rows.push_back(i);
inverse[a[i]] = i;
}
int cursor = 0;
for (int i = 0; i < n; ++i) if (inverse[i] < 0) left[cursor++] = i;
for (int row : rows) left[cursor++] = a[row];
std::fill(inverse.begin(), inverse.end(), -1);
for (int i = 0; i < n; ++i) if (b[i] >= 0) inverse[b[i]] = i;
cursor = 0;
for (int i = 0; i < n; ++i) if (inverse[i] >= 0) {
right[cursor++] = inverse[i];
columns.push_back(i);
}
for (int i = 0; i < n; ++i) if (b[i] < 0) right[cursor++] = i;
std::size_t space = 0;
for (int length = n; length > 1;) {
int half = length / 2 + length % 2;
space += std::size_t(length) + 5 * std::size_t(half);
length = half;
}
std::vector<int> product(n), work(space);
multiply(n, left.data(), right.data(), product.data(), work.data());
std::vector<int> result(n, -1);
for (std::size_t i = 0; i < rows.size(); ++i) {
int column = product[n - rows.size() + i];
if (std::size_t(column) < columns.size()) result[rows[i]] = columns[column];
}
return result;
}
inline std::vector<int> seaweed(std::span<const int> permutation) {
int n = int(permutation.size());
if (n <= 32) {
std::vector<int> state(n, -1), result(n, -1);
for (int i = 0; i < n; ++i) {
int value = permutation[i], carry = -1;
state[value] = i;
for (int j = value + 1; j < n; ++j)
if (state[j] > carry) std::swap(state[j], carry);
if (carry >= 0) result[carry] = i;
}
return result;
}
int middle = n / 2;
std::vector<int> low, high, low_positions, high_positions;
low.reserve(middle);
high.reserve(n - middle);
low_positions.reserve(middle);
high_positions.reserve(n - middle);
for (int i = 0; i < n; ++i) {
int value = permutation[i];
if (value < middle) {
low.push_back(value);
low_positions.push_back(i);
} else {
high.push_back(value - middle);
high_positions.push_back(i);
}
}
low = seaweed(low);
high = seaweed(high);
std::vector<int> a(n), b(n);
std::iota(a.begin(), a.end(), 0);
std::iota(b.begin(), b.end(), 0);
for (int i = 0; i < middle; ++i) a[low_positions[i]] = low[i] < 0 ? -1 : low_positions[low[i]];
for (int i = 0; i < n - middle; ++i) b[high_positions[i]] = high[i] < 0 ? -1 : high_positions[high[i]];
return compose(a, b);
}
}
#line 12 "data_structure/range_lis_query.hpp"
#include <functional>
#include <limits>
#line 15 "data_structure/range_lis_query.hpp"
#include <ranges>
#line 18 "data_structure/range_lis_query.hpp"
template <bool Strict = true>
class RangeLISQuery {
int n = 0;
std::vector<QuadBitVector> bits;
std::vector<std::array<int, 4>> offsets;
[[gnu::always_inline]] int query_impl(int l, int r) const {
int length = r - l, removed = 0;
unsigned upper = unsigned(r);
for (int level = 0; level < int(bits.size()) && l < r; ++level) {
int digit = (upper >> (2 * (int(bits.size()) - 1 - level))) & 3;
const auto &row = bits[level];
removed += row.below(r, digit) - row.below(l, digit);
l = offsets[level][digit] + row.rank(l, digit);
r = offsets[level][digit] + row.rank(r, digit);
}
return length - removed;
}
#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("popcnt"))) int query_popcnt(int l, int r) const { return query_impl(l, r); }
#endif
public:
RangeLISQuery() = default;
template <class Range, class Compare = std::less<>>
requires std::ranges::random_access_range<const Range> && std::ranges::sized_range<const Range>
explicit RangeLISQuery(const Range &values, Compare compare = {}) { build(values, std::move(compare)); }
RangeLISQuery(const RangeLISQuery &) = default;
RangeLISQuery &operator=(const RangeLISQuery &) = default;
RangeLISQuery(RangeLISQuery &&other) noexcept { swap(other); }
RangeLISQuery &operator=(RangeLISQuery &&other) noexcept {
if (this != &other) {
RangeLISQuery replacement(std::move(other));
swap(replacement);
}
return *this;
}
void swap(RangeLISQuery &other) noexcept {
std::swap(n, other.n);
bits.swap(other.bits);
offsets.swap(other.offsets);
}
int size() const { return n; }
bool empty() const { return n == 0; }
void clear() { n = 0; bits.clear(); offsets.clear(); }
template <class Range, class Compare = std::less<>>
requires std::ranges::random_access_range<const Range> && std::ranges::sized_range<const Range>
void build(const Range &values, Compare compare = {}) {
assert(std::ranges::size(values) <= std::size_t(std::numeric_limits<int>::max()));
n = int(std::ranges::size(values));
bits.clear();
offsets.clear();
if (!n) return;
auto first = std::ranges::begin(values);
std::vector<int> order(n), permutation(n);
std::iota(order.begin(), order.end(), 0);
std::sort(order.begin(), order.end(), [&](int a, int b) {
if (compare(first[a], first[b])) return true;
if (compare(first[b], first[a])) return false;
if constexpr (Strict) return a > b;
else return a < b;
});
for (int i = 0; i < n; ++i) permutation[order[i]] = i;
auto endpoints = range_lis_detail::seaweed(permutation);
std::vector<std::uint32_t> current(n), next(n);
for (int i = 0; i < n; ++i) current[i] = endpoints[i] < 0 ? unsigned(n) : unsigned(endpoints[i]);
int levels = (std::bit_width(unsigned(n)) + 1) / 2;
bits.reserve(levels);
offsets.resize(levels);
for (int level = 0; level < levels; ++level) {
int shift = 2 * (levels - 1 - level);
auto &row = bits.emplace_back(n);
row.build(current, shift);
auto counts = row.ranks(n);
for (int digit = 1; digit < 4; ++digit) offsets[level][digit] = offsets[level][digit - 1] + counts[digit - 1];
if (level + 1 == levels) break;
auto positions = offsets[level];
for (auto value : current) next[positions[(value >> shift) & 3]++] = value;
current.swap(next);
}
}
int query(int l, int r) const {
assert(0 <= l && l <= r && r <= n);
if (r - l <= 1) return r - l;
#if defined(__x86_64__) || defined(__i386__)
static const bool hardware = __builtin_cpu_supports("popcnt");
if (hardware) return query_popcnt(l, r);
#endif
return query_impl(l, r);
}
};