Convex All
(convex/all.hpp)
- View this file on GitHub
- Last update: 2026-07-07 18:38:36+09:00
- Include:
#include "convex/all.hpp"
Overview
convex/all.hpp includes convex data structures and convex optimization
helpers. The public namespace is m1une::convex.
Included Headers
| Header | Contents |
|---|---|
convex/alien_trick.hpp |
Exact-count optimization through Lagrangian relaxation. |
convex/convex_hull_trick.hpp |
Monotone-slope CHT for minimum or maximum line queries. |
convex/li_chao_tree.hpp |
Dynamic Li Chao tree for arbitrary line and line-segment insertion. |
convex/monge/all.hpp |
SMAWK, monotone minima, Knuth/D&C DP optimization, LARSCH, Monge checks, and structured min-plus/max-plus convolution. |
convex/slope_trick.hpp |
Heap-based slope trick for convex piecewise-linear functions. |
Depends on
Alien Trick
(convex/alien_trick.hpp)
Convex Hull Trick
(convex/convex_hull_trick.hpp)
Li Chao Tree
(convex/li_chao_tree.hpp)
Monge All
(convex/monge/all.hpp)
Monge Checks
(convex/monge/check.hpp)
Divide-and-Conquer DP Optimization
(convex/monge/divide_and_conquer_optimization.hpp)
Knuth Optimization
(convex/monge/knuth_optimization.hpp)
LARSCH
(convex/monge/larsch.hpp)
Structured Min-Plus and Max-Plus Convolution
(convex/monge/min_plus_convolution.hpp)
Monotone Minima
(convex/monge/monotone_minima.hpp)
SMAWK
(convex/monge/smawk.hpp)
Slope Trick
(convex/slope_trick.hpp)
Code
#ifndef M1UNE_CONVEX_ALL_HPP
#define M1UNE_CONVEX_ALL_HPP 1
#include "alien_trick.hpp"
#include "convex_hull_trick.hpp"
#include "li_chao_tree.hpp"
#include "monge/all.hpp"
#include "slope_trick.hpp"
#endif // M1UNE_CONVEX_ALL_HPP#line 1 "convex/all.hpp"
#line 1 "convex/alien_trick.hpp"
#include <cassert>
#include <concepts>
#include <numeric>
#include <type_traits>
#include <utility>
namespace m1une {
namespace convex {
namespace detail {
template <std::integral Penalty, std::integral Count, class Oracle>
Penalty alien_trick_penalty(Penalty lower, Penalty upper, Count target_count, Oracle& oracle) {
assert(lower <= upper);
assert(oracle(lower).second >= target_count);
assert(oracle(upper).second <= target_count);
while (lower < upper) {
Penalty middle = std::midpoint(lower, upper);
if (middle == lower) ++middle;
if (oracle(middle).second >= target_count) {
lower = middle;
} else {
upper = middle - 1;
}
}
return lower;
}
} // namespace detail
// Recovers the minimum value among solutions using exactly `target_count`
// items. The oracle minimizes value + penalty * count and breaks ties in favor
// of the larger count.
template <std::integral Penalty, std::integral Count, class Oracle>
auto alien_trick_minimize(Penalty lower, Penalty upper, Count target_count, Oracle oracle) {
Penalty penalty = detail::alien_trick_penalty(lower, upper, target_count, oracle);
auto result = oracle(penalty);
using Value = std::remove_cvref_t<decltype(result.first)>;
return result.first - static_cast<Value>(penalty) * static_cast<Value>(target_count);
}
// Recovers the maximum value among solutions using exactly `target_count`
// items. The oracle maximizes value - penalty * count and breaks ties in favor
// of the larger count.
template <std::integral Penalty, std::integral Count, class Oracle>
auto alien_trick_maximize(Penalty lower, Penalty upper, Count target_count, Oracle oracle) {
Penalty penalty = detail::alien_trick_penalty(lower, upper, target_count, oracle);
auto result = oracle(penalty);
using Value = std::remove_cvref_t<decltype(result.first)>;
return result.first + static_cast<Value>(penalty) * static_cast<Value>(target_count);
}
} // namespace convex
} // namespace m1une
#line 1 "convex/convex_hull_trick.hpp"
#line 6 "convex/convex_hull_trick.hpp"
#include <cstddef>
#include <optional>
#line 9 "convex/convex_hull_trick.hpp"
#include <vector>
namespace m1une {
namespace convex {
enum class LineOptimization {
Minimize,
Maximize,
};
template <std::signed_integral T>
using line_wide_type = __int128_t;
template <std::signed_integral T>
struct LinearFunction {
using value_type = line_wide_type<T>;
value_type slope;
value_type intercept;
constexpr LinearFunction() : slope(0), intercept(0) {}
constexpr LinearFunction(T slope_value, T intercept_value) : slope(slope_value), intercept(intercept_value) {}
constexpr value_type operator()(T x) const {
return slope * value_type(x) + intercept;
}
};
// Convex hull trick for lines inserted in nondecreasing slope order.
template <std::signed_integral T, LineOptimization Objective = LineOptimization::Minimize>
struct ConvexHullTrick {
using Line = LinearFunction<T>;
using value_type = typename Line::value_type;
private:
std::vector<Line> _lines;
static bool better(value_type first, value_type second) {
if constexpr (Objective == LineOptimization::Minimize) {
return first < second;
} else {
return second < first;
}
}
static bool redundant(const Line& first, const Line& middle, const Line& last) {
value_type left = (first.intercept - middle.intercept) * (last.slope - middle.slope);
value_type right = (middle.intercept - last.intercept) * (middle.slope - first.slope);
if constexpr (Objective == LineOptimization::Minimize) {
return left <= right;
} else {
return right <= left;
}
}
public:
ConvexHullTrick() = default;
int size() const {
return int(_lines.size());
}
bool empty() const {
return _lines.empty();
}
const std::vector<Line>& lines() const {
return _lines;
}
void reserve(std::size_t line_capacity) {
_lines.reserve(line_capacity);
}
void clear() {
_lines.clear();
}
// Slopes must be inserted in nondecreasing order.
void add_line(T slope, T intercept) {
Line line(slope, intercept);
if (!_lines.empty()) {
assert(_lines.back().slope <= line.slope);
}
if (!_lines.empty() && _lines.back().slope == line.slope) {
if (!better(line.intercept, _lines.back().intercept)) return;
_lines.pop_back();
}
while (_lines.size() >= 2 && redundant(_lines[_lines.size() - 2], _lines.back(), line)) {
_lines.pop_back();
}
_lines.push_back(line);
}
std::optional<value_type> try_query(T x) const {
if (_lines.empty()) return std::nullopt;
int low = 0;
int high = int(_lines.size()) - 1;
while (low < high) {
int middle = low + (high - low) / 2;
value_type first = _lines[middle](x);
value_type second = _lines[middle + 1](x);
if (better(first, second) || first == second) {
high = middle;
} else {
low = middle + 1;
}
}
return _lines[low](x);
}
value_type query(T x) const {
assert(!empty());
return *try_query(x);
}
};
template <std::signed_integral T>
using MinConvexHullTrick = ConvexHullTrick<T, LineOptimization::Minimize>;
template <std::signed_integral T>
using MaxConvexHullTrick = ConvexHullTrick<T, LineOptimization::Maximize>;
} // namespace convex
} // namespace m1une
#line 1 "convex/li_chao_tree.hpp"
#line 7 "convex/li_chao_tree.hpp"
#include <limits>
#line 13 "convex/li_chao_tree.hpp"
#line 15 "convex/li_chao_tree.hpp"
namespace m1une {
namespace convex {
// Dynamic Li Chao tree over an integral half-open coordinate domain.
template <std::signed_integral T, LineOptimization Objective = LineOptimization::Minimize>
struct LiChaoTree {
using Line = LinearFunction<T>;
using value_type = typename Line::value_type;
private:
struct Node {
Line line;
bool has_line;
int left;
int right;
Node() : has_line(false), left(-1), right(-1) {}
explicit Node(Line value) : line(std::move(value)), has_line(true), left(-1), right(-1) {}
};
T _left;
T _right;
int _root;
std::vector<Node> _nodes;
static bool better(value_type first, value_type second) {
if constexpr (Objective == LineOptimization::Minimize) {
return first < second;
} else {
return second < first;
}
}
int new_node() {
assert(_nodes.size() < std::size_t(std::numeric_limits<int>::max()));
_nodes.emplace_back();
return int(_nodes.size()) - 1;
}
int new_node(Line line) {
assert(_nodes.size() < std::size_t(std::numeric_limits<int>::max()));
_nodes.emplace_back(std::move(line));
return int(_nodes.size()) - 1;
}
int add_line_node(int node, T left, T right, Line line) {
if (node == -1) return new_node(std::move(line));
if (!_nodes[node].has_line) {
_nodes[node].line = std::move(line);
_nodes[node].has_line = true;
return node;
}
T middle = std::midpoint(left, right);
bool left_better = better(line(left), _nodes[node].line(left));
bool middle_better = better(line(middle), _nodes[node].line(middle));
if (middle_better) std::swap(line, _nodes[node].line);
if (middle == left) return node;
if (left_better != middle_better) {
int child = add_line_node(_nodes[node].left, left, middle, std::move(line));
_nodes[node].left = child;
} else {
int child = add_line_node(_nodes[node].right, middle, right, std::move(line));
_nodes[node].right = child;
}
return node;
}
int add_segment_node(int node, T left, T right, T query_left, T query_right, const Line& line) {
if (query_right <= left || right <= query_left) return node;
if (query_left <= left && right <= query_right) {
return add_line_node(node, left, right, line);
}
if (node == -1) node = new_node();
T middle = std::midpoint(left, right);
if (middle == left) return add_line_node(node, left, right, line);
int left_child = add_segment_node(_nodes[node].left, left, middle, query_left, query_right, line);
int right_child = add_segment_node(_nodes[node].right, middle, right, query_left, query_right, line);
_nodes[node].left = left_child;
_nodes[node].right = right_child;
return node;
}
public:
LiChaoTree() : _left(0), _right(0), _root(-1) {}
LiChaoTree(T left, T right) : _left(left), _right(right), _root(-1) {
assert(left <= right);
}
T left_bound() const {
return _left;
}
T right_bound() const {
return _right;
}
bool empty() const {
return _root == -1;
}
std::size_t node_count() const {
return _nodes.size();
}
void reserve(std::size_t node_capacity) {
_nodes.reserve(node_capacity);
}
void clear() {
_root = -1;
_nodes.clear();
}
void add_line(T slope, T intercept) {
assert(_left < _right);
_root = add_line_node(_root, _left, _right, Line(slope, intercept));
}
void add_segment(T segment_left, T segment_right, T slope, T intercept) {
assert(_left <= segment_left && segment_left <= segment_right && segment_right <= _right);
if (segment_left == segment_right) return;
_root = add_segment_node(_root, _left, _right, segment_left, segment_right, Line(slope, intercept));
}
// Returns nullopt when no inserted line covers x.
std::optional<value_type> query(T x) const {
assert(_left <= x && x < _right);
std::optional<value_type> result;
int node = _root;
T left = _left;
T right = _right;
while (node != -1) {
if (_nodes[node].has_line) {
value_type candidate = _nodes[node].line(x);
if (!result || better(candidate, *result)) {
result = candidate;
}
}
T middle = std::midpoint(left, right);
if (middle == left) break;
if (x < middle) {
node = _nodes[node].left;
right = middle;
} else {
node = _nodes[node].right;
left = middle;
}
}
return result;
}
value_type get(T x) const {
std::optional<value_type> result = query(x);
assert(result.has_value());
return result.value_or(value_type());
}
};
template <std::signed_integral T>
using MinLiChaoTree = LiChaoTree<T, LineOptimization::Minimize>;
template <std::signed_integral T>
using MaxLiChaoTree = LiChaoTree<T, LineOptimization::Maximize>;
} // namespace convex
} // namespace m1une
#line 1 "convex/monge/all.hpp"
#line 1 "convex/monge/check.hpp"
#line 6 "convex/monge/check.hpp"
namespace m1une {
namespace convex {
template <class Value>
bool is_monge(int row_count, int column_count, Value value) {
assert(row_count >= 0);
assert(column_count >= 0);
for (int row = 0; row + 1 < row_count; row++) {
for (int column = 0; column + 1 < column_count; column++) {
if (value(row, column) + value(row + 1, column + 1) >
value(row, column + 1) + value(row + 1, column)) {
return false;
}
}
}
return true;
}
template <class Value>
bool is_anti_monge(int row_count, int column_count, Value value) {
assert(row_count >= 0);
assert(column_count >= 0);
for (int row = 0; row + 1 < row_count; row++) {
for (int column = 0; column + 1 < column_count; column++) {
if (value(row, column) + value(row + 1, column + 1) <
value(row, column + 1) + value(row + 1, column)) {
return false;
}
}
}
return true;
}
template <class T>
bool is_monge(const std::vector<std::vector<T>>& matrix) {
int row_count = int(matrix.size());
int column_count = row_count == 0 ? 0 : int(matrix[0].size());
for (const auto& row : matrix) assert(int(row.size()) == column_count);
return is_monge(row_count, column_count,
[&](int row, int column) -> const T& { return matrix[row][column]; });
}
template <class T>
bool is_anti_monge(const std::vector<std::vector<T>>& matrix) {
int row_count = int(matrix.size());
int column_count = row_count == 0 ? 0 : int(matrix[0].size());
for (const auto& row : matrix) assert(int(row.size()) == column_count);
return is_anti_monge(
row_count, column_count,
[&](int row, int column) -> const T& { return matrix[row][column]; });
}
} // namespace convex
} // namespace m1une
#line 1 "convex/monge/divide_and_conquer_optimization.hpp"
#line 7 "convex/monge/divide_and_conquer_optimization.hpp"
#line 1 "convex/monge/monotone_minima.hpp"
#line 5 "convex/monge/monotone_minima.hpp"
#include <functional>
#line 7 "convex/monge/monotone_minima.hpp"
namespace m1une {
namespace convex {
namespace monotone_minima_detail {
template <class Value, class Compare>
void solve(int row_left, int row_right, int column_left, int column_right,
const Value& value, const Compare& compare, std::vector<int>& answer) {
if (row_left == row_right) return;
int row = (row_left + row_right) / 2;
int best = column_left;
for (int column = column_left + 1; column < column_right; column++) {
if (compare(value(row, column), value(row, best))) best = column;
}
answer[row] = best;
solve(row_left, row, column_left, best + 1, value, compare, answer);
solve(row + 1, row_right, best, column_right, value, compare, answer);
}
} // namespace monotone_minima_detail
template <class Value, class Compare = std::less<>>
std::vector<int> monotone_row_optima(int row_count, int column_count, Value value,
Compare compare = Compare()) {
assert(row_count >= 0);
assert(column_count >= 0);
std::vector<int> answer(row_count, -1);
if (row_count == 0 || column_count == 0) return answer;
monotone_minima_detail::solve(0, row_count, 0, column_count, value, compare, answer);
return answer;
}
template <class Value>
std::vector<int> monotone_row_argmin(int row_count, int column_count, Value value) {
return monotone_row_optima(row_count, column_count, value, std::less<>());
}
template <class Value>
std::vector<int> monotone_row_argmax(int row_count, int column_count, Value value) {
return monotone_row_optima(row_count, column_count, value, std::greater<>());
}
template <class T>
std::vector<int> monotone_row_argmin(const std::vector<std::vector<T>>& matrix) {
int row_count = int(matrix.size());
int column_count = row_count == 0 ? 0 : int(matrix[0].size());
for (const auto& row : matrix) assert(int(row.size()) == column_count);
return monotone_row_argmin(
row_count, column_count,
[&](int row, int column) -> const T& { return matrix[row][column]; });
}
template <class T>
std::vector<int> monotone_row_argmax(const std::vector<std::vector<T>>& matrix) {
int row_count = int(matrix.size());
int column_count = row_count == 0 ? 0 : int(matrix[0].size());
for (const auto& row : matrix) assert(int(row.size()) == column_count);
return monotone_row_argmax(
row_count, column_count,
[&](int row, int column) -> const T& { return matrix[row][column]; });
}
} // namespace convex
} // namespace m1une
#line 9 "convex/monge/divide_and_conquer_optimization.hpp"
namespace m1une {
namespace convex {
template <class T>
struct DivideAndConquerDpResult {
std::vector<T> value;
std::vector<int> argmin;
};
template <class Value>
auto divide_and_conquer_dp(int state_count, int candidate_count, Value value)
-> DivideAndConquerDpResult<
std::decay_t<std::invoke_result_t<Value, int, int>>> {
using T = std::decay_t<std::invoke_result_t<Value, int, int>>;
DivideAndConquerDpResult<T> result;
result.argmin = monotone_row_argmin(state_count, candidate_count, value);
result.value.resize(state_count);
for (int state = 0; state < state_count; state++) {
if (result.argmin[state] != -1) {
result.value[state] = value(state, result.argmin[state]);
}
}
return result;
}
template <class T, class Cost>
auto divide_and_conquer_transition(const std::vector<T>& previous, int state_count,
Cost cost)
-> DivideAndConquerDpResult<
std::decay_t<decltype(std::declval<T>() + cost(0, 0))>> {
using Result = std::decay_t<decltype(std::declval<T>() + cost(0, 0))>;
return divide_and_conquer_dp(
state_count, int(previous.size()),
[&](int state, int candidate) -> Result {
return previous[candidate] + cost(candidate, state);
});
}
} // namespace convex
} // namespace m1une
#line 1 "convex/monge/knuth_optimization.hpp"
#include <algorithm>
#line 8 "convex/monge/knuth_optimization.hpp"
namespace m1une {
namespace convex {
template <class T>
struct KnuthOptimizationResult {
std::vector<std::vector<T>> value;
std::vector<std::vector<int>> split;
T optimum() const {
return value[0].back();
}
};
template <class IntervalCost>
auto knuth_optimization(int element_count, IntervalCost interval_cost)
-> KnuthOptimizationResult<
std::decay_t<std::invoke_result_t<IntervalCost, int, int>>> {
assert(element_count >= 0);
using T = std::decay_t<std::invoke_result_t<IntervalCost, int, int>>;
KnuthOptimizationResult<T> result;
result.value.assign(element_count + 1, std::vector<T>(element_count + 1, T()));
result.split.assign(element_count + 1, std::vector<int>(element_count + 1, -1));
for (int left = 0; left <= element_count; left++) result.split[left][left] = left;
for (int left = 0; left < element_count; left++) result.split[left][left + 1] = left + 1;
for (int length = 2; length <= element_count; length++) {
for (int left = 0; left + length <= element_count; left++) {
int right = left + length;
int first = std::max(left + 1, result.split[left][right - 1]);
int last = std::min(right - 1, result.split[left + 1][right]);
assert(first <= last);
int best = first;
T best_value = result.value[left][best] + result.value[best][right];
for (int split = first + 1; split <= last; split++) {
T candidate = result.value[left][split] + result.value[split][right];
if (candidate < best_value) {
best = split;
best_value = candidate;
}
}
result.value[left][right] = best_value + interval_cost(left, right);
result.split[left][right] = best;
}
}
return result;
}
} // namespace convex
} // namespace m1une
#line 1 "convex/monge/larsch.hpp"
#line 6 "convex/monge/larsch.hpp"
#include <memory>
#line 10 "convex/monge/larsch.hpp"
namespace m1une {
namespace convex {
template <class T>
class Larsch {
struct ReduceColumn;
struct ReduceRow {
int size;
std::function<T(int, int)> value;
int current_row = 0;
int boundary = 0;
std::unique_ptr<ReduceColumn> recursive;
explicit ReduceRow(int size_) : size(size_) {
if (size / 2 != 0) recursive = std::make_unique<ReduceColumn>(size / 2);
}
void set_value(std::function<T(int, int)> value_) {
value = std::move(value_);
if (recursive) {
recursive->set_value(
[&](int row, int column) { return value(row * 2 + 1, column); });
}
}
int next_argmin() {
int row = current_row++;
if (row % 2 == 0) {
int previous = boundary;
int next = row + 1 == size ? size - 1 : recursive->next_argmin();
boundary = next;
int best = previous;
for (int column = previous + 1; column <= next; column++) {
if (value(row, column) < value(row, best)) best = column;
}
return best;
}
return value(row, boundary) <= value(row, row) ? boundary : row;
}
};
struct ReduceColumn {
int size;
std::function<T(int, int)> value;
int current_row = 0;
std::vector<int> columns;
ReduceRow recursive;
explicit ReduceColumn(int size_) : size(size_), recursive(size_) {}
void set_value(std::function<T(int, int)> value_) {
value = std::move(value_);
recursive.set_value(
[&](int row, int column) { return value(row, columns[column]); });
}
int next_argmin() {
int row = current_row++;
int first = row == 0 ? 0 : row * 2 - 1;
int last = row * 2;
for (int column = first; column <= last; column++) {
while (int(columns.size()) != row &&
value(int(columns.size()) - 1, columns.back()) >
value(int(columns.size()) - 1, column)) {
columns.pop_back();
}
if (int(columns.size()) != size) columns.push_back(column);
}
return columns[recursive.next_argmin()];
}
};
int _size;
int _processed = 0;
std::unique_ptr<ReduceRow> _base;
public:
template <class Value>
explicit Larsch(int size, Value value)
: _size(size), _base(std::make_unique<ReduceRow>(size)) {
assert(size >= 0);
_base->set_value(std::function<T(int, int)>(std::move(value)));
}
int size() const {
return _size;
}
int processed_rows() const {
return _processed;
}
bool finished() const {
return _processed == _size;
}
int next_argmin() {
assert(!finished());
_processed++;
return _base->next_argmin();
}
};
template <class T>
struct LarschShortestPathResult {
std::vector<T> distance;
std::vector<int> parent;
};
template <class Cost>
auto larsch_shortest_path(int vertex_count, Cost cost)
-> LarschShortestPathResult<
std::decay_t<std::invoke_result_t<Cost, int, int>>> {
using T = std::decay_t<std::invoke_result_t<Cost, int, int>>;
assert(vertex_count >= 0);
LarschShortestPathResult<T> result;
result.distance.assign(vertex_count, T());
result.parent.assign(vertex_count, -1);
if (vertex_count <= 1) return result;
Larsch<T> optimizer(vertex_count - 1, [&](int row, int column) {
return result.distance[column] + cost(column, row + 1);
});
for (int vertex = 1; vertex < vertex_count; vertex++) {
int parent = optimizer.next_argmin();
result.parent[vertex] = parent;
result.distance[vertex] = result.distance[parent] + cost(parent, vertex);
}
return result;
}
} // namespace convex
} // namespace m1une
#line 1 "convex/monge/min_plus_convolution.hpp"
#line 7 "convex/monge/min_plus_convolution.hpp"
#line 1 "convex/monge/smawk.hpp"
#line 8 "convex/monge/smawk.hpp"
namespace m1une {
namespace convex {
namespace smawk_detail {
template <class Select>
void solve(const std::vector<int>& rows, const std::vector<int>& columns,
const Select& select, std::vector<int>& answer) {
if (rows.empty()) return;
std::vector<int> reduced;
reduced.reserve(columns.size());
for (int column : columns) {
while (!reduced.empty()) {
int row = rows[int(reduced.size()) - 1];
if (!select(row, reduced.back(), column)) break;
reduced.pop_back();
}
if (reduced.size() < rows.size()) reduced.push_back(column);
}
std::vector<int> odd_rows;
odd_rows.reserve(rows.size() / 2);
for (int i = 1; i < int(rows.size()); i += 2) odd_rows.push_back(rows[i]);
solve(odd_rows, reduced, select, answer);
int left = 0;
int right = 0;
for (int i = 0; i < int(rows.size()); i += 2) {
if (i + 1 < int(rows.size())) {
while (reduced[right] != answer[rows[i + 1]]) right++;
} else {
right = int(reduced.size()) - 1;
}
int best = left;
for (int j = left + 1; j <= right; j++) {
if (select(rows[i], reduced[best], reduced[j])) {
best = j;
}
}
answer[rows[i]] = reduced[best];
left = right;
}
}
template <class Select>
std::vector<int> row_optima(int row_count, int column_count, const Select& select) {
std::vector<int> answer(row_count, -1);
if (row_count == 0 || column_count == 0) return answer;
std::vector<int> rows(row_count), columns(column_count);
std::iota(rows.begin(), rows.end(), 0);
std::iota(columns.begin(), columns.end(), 0);
solve(rows, columns, select, answer);
return answer;
}
} // namespace smawk_detail
template <class Value, class Compare = std::less<>>
std::vector<int> smawk_row_optima(int row_count, int column_count, Value value,
Compare compare = Compare()) {
assert(row_count >= 0);
assert(column_count >= 0);
return smawk_detail::row_optima(
row_count, column_count,
[&](int row, int current, int candidate) {
return compare(value(row, candidate), value(row, current));
});
}
template <class Value>
std::vector<int> smawk_row_argmin(int row_count, int column_count, Value value) {
return smawk_row_optima(row_count, column_count, value, std::less<>());
}
template <class Value>
std::vector<int> smawk_row_argmax(int row_count, int column_count, Value value) {
return smawk_row_optima(row_count, column_count, value, std::greater<>());
}
template <class T>
std::vector<int> smawk_row_argmin(const std::vector<std::vector<T>>& matrix) {
int row_count = int(matrix.size());
int column_count = row_count == 0 ? 0 : int(matrix[0].size());
for (const auto& row : matrix) assert(int(row.size()) == column_count);
return smawk_row_argmin(
row_count, column_count,
[&](int row, int column) -> const T& { return matrix[row][column]; });
}
template <class T>
std::vector<int> smawk_row_argmax(const std::vector<std::vector<T>>& matrix) {
int row_count = int(matrix.size());
int column_count = row_count == 0 ? 0 : int(matrix[0].size());
for (const auto& row : matrix) assert(int(row.size()) == column_count);
return smawk_row_argmax(
row_count, column_count,
[&](int row, int column) -> const T& { return matrix[row][column]; });
}
} // namespace convex
} // namespace m1une
#line 9 "convex/monge/min_plus_convolution.hpp"
namespace m1une {
namespace convex {
namespace convolution_detail {
template <class T, class Compare, class Add>
std::vector<T> structured_convolution(const std::vector<T>& arbitrary,
const std::vector<T>& structured,
Compare compare, Add add) {
if (arbitrary.empty() || structured.empty()) return {};
int first_size = int(arbitrary.size());
int second_size = int(structured.size());
int result_size = first_size + second_size - 1;
auto select = [&](int index, int current, int candidate) {
if (index < candidate) return false;
if (index - current >= second_size) return true;
T current_value = add(arbitrary[current], structured[index - current]);
T candidate_value = add(arbitrary[candidate], structured[index - candidate]);
return !compare(current_value, candidate_value);
};
std::vector<int> optima =
smawk_detail::row_optima(result_size, first_size, select);
std::vector<T> result;
result.reserve(result_size);
for (int index = 0; index < result_size; index++) {
int first_index = optima[index];
result.emplace_back(add(arbitrary[first_index],
structured[index - first_index]));
}
return result;
}
template <class T>
std::pair<int, int> finite_interval(const std::vector<T>& sequence,
const T& infinity) {
int left = 0;
while (left < int(sequence.size()) && sequence[left] == infinity) left++;
int right = int(sequence.size());
while (right > left && sequence[right - 1] == infinity) right--;
return {left, right};
}
template <class T, class Compare>
std::vector<T> structured_convolution_with_infinity(
const std::vector<T>& arbitrary, const std::vector<T>& structured,
const T& infinity, Compare compare) {
if (arbitrary.empty() || structured.empty()) return {};
auto [left, right] = finite_interval(structured, infinity);
int result_size = int(arbitrary.size() + structured.size() - 1);
std::vector<T> result(result_size, infinity);
if (left == right) return result;
std::vector<int> columns;
columns.reserve(arbitrary.size());
for (int i = 0; i < int(arbitrary.size()); i++) {
if (arbitrary[i] != infinity) columns.push_back(i);
}
if (columns.empty()) return result;
int finite_size = right - left;
int middle_size = int(arbitrary.size()) + finite_size - 1;
std::vector<int> rows;
rows.reserve(middle_size);
int active = 0;
for (int row = 0; row < middle_size; row++) {
if (row < int(arbitrary.size()) && arbitrary[row] != infinity) active++;
if (row >= finite_size && arbitrary[row - finite_size] != infinity) active--;
if (active > 0) rows.push_back(row);
}
auto select = [&](int index, int current, int candidate) {
if (index < candidate) return false;
if (index - current >= finite_size) return true;
T current_value =
arbitrary[current] + structured[left + index - current];
T candidate_value =
arbitrary[candidate] + structured[left + index - candidate];
return !compare(current_value, candidate_value);
};
std::vector<int> optima(middle_size, -1);
smawk_detail::solve(rows, columns, select, optima);
for (int row : rows) {
int first_index = optima[row];
result[left + row] =
arbitrary[first_index] + structured[left + row - first_index];
}
return result;
}
template <class T, class Compare>
std::vector<T> linear_structured_convolution(const std::vector<T>& first,
const std::vector<T>& second,
Compare compare) {
if (first.empty() || second.empty()) return {};
int first_size = int(first.size());
int second_size = int(second.size());
std::vector<T> result(first_size + second_size - 1);
result[0] = first[0] + second[0];
int first_index = 1;
int second_index = 1;
int result_index = 1;
while (first_index < first_size && second_index < second_size) {
T first_difference = first[first_index] - first[first_index - 1];
T second_difference = second[second_index] - second[second_index - 1];
if (compare(second_difference, first_difference)) {
result[result_index] = result[result_index - 1] + second_difference;
second_index++;
} else {
result[result_index] = result[result_index - 1] + first_difference;
first_index++;
}
result_index++;
}
while (first_index < first_size) {
T difference = first[first_index] - first[first_index - 1];
result[result_index] = result[result_index - 1] + difference;
first_index++;
result_index++;
}
while (second_index < second_size) {
T difference = second[second_index] - second[second_index - 1];
result[result_index] = result[result_index - 1] + difference;
second_index++;
result_index++;
}
return result;
}
template <class T, class Compare>
std::vector<T> linear_structured_convolution_with_infinity(
const std::vector<T>& first, const std::vector<T>& second,
const T& infinity, Compare compare) {
if (first.empty() || second.empty()) return {};
auto [first_left, first_right] = finite_interval(first, infinity);
auto [second_left, second_right] = finite_interval(second, infinity);
int result_size = int(first.size() + second.size() - 1);
std::vector<T> result(result_size, infinity);
if (first_left == first_right || second_left == second_right) return result;
int offset = first_left + second_left;
result[offset] = first[first_left] + second[second_left];
int first_index = first_left + 1;
int second_index = second_left + 1;
int result_index = offset + 1;
while (first_index < first_right && second_index < second_right) {
T first_difference = first[first_index] - first[first_index - 1];
T second_difference = second[second_index] - second[second_index - 1];
if (compare(second_difference, first_difference)) {
result[result_index] = result[result_index - 1] + second_difference;
second_index++;
} else {
result[result_index] = result[result_index - 1] + first_difference;
first_index++;
}
result_index++;
}
while (first_index < first_right) {
T difference = first[first_index] - first[first_index - 1];
result[result_index] = result[result_index - 1] + difference;
first_index++;
result_index++;
}
while (second_index < second_right) {
T difference = second[second_index] - second[second_index - 1];
result[result_index] = result[result_index - 1] + difference;
second_index++;
result_index++;
}
return result;
}
template <class T, class Compare>
bool is_structured_sequence_with_infinity(const std::vector<T>& sequence,
const T& infinity, Compare violation) {
auto [left, right] = finite_interval(sequence, infinity);
for (int i = left; i < right; i++) {
if (sequence[i] == infinity) return false;
}
for (int i = left + 1; i + 1 < right; i++) {
T first_difference = sequence[i] - sequence[i - 1];
T second_difference = sequence[i + 1] - sequence[i];
if (violation(first_difference, second_difference)) return false;
}
return true;
}
} // namespace convolution_detail
template <class T>
bool is_convex_sequence(const std::vector<T>& sequence) {
for (int i = 1; i + 1 < int(sequence.size()); i++) {
if (sequence[i] - sequence[i - 1] > sequence[i + 1] - sequence[i]) {
return false;
}
}
return true;
}
template <class T>
bool is_convex_sequence(const std::vector<T>& sequence, const T& infinity) {
return convolution_detail::is_structured_sequence_with_infinity(
sequence, infinity, std::greater<>());
}
template <class T>
bool is_concave_sequence(const std::vector<T>& sequence) {
for (int i = 1; i + 1 < int(sequence.size()); i++) {
if (sequence[i] - sequence[i - 1] < sequence[i + 1] - sequence[i]) {
return false;
}
}
return true;
}
template <class T>
bool is_concave_sequence(const std::vector<T>& sequence,
const T& negative_infinity) {
return convolution_detail::is_structured_sequence_with_infinity(
sequence, negative_infinity, std::less<>());
}
template <class T>
std::vector<T> min_plus_convolution_convex(const std::vector<T>& arbitrary,
const std::vector<T>& convex) {
auto add = [](const T& first, const T& second) { return first + second; };
return convolution_detail::structured_convolution(arbitrary, convex,
std::less<>(), add);
}
template <class T>
std::vector<T> min_plus_convolution_convex(const std::vector<T>& arbitrary,
const std::vector<T>& convex,
const T& infinity) {
return convolution_detail::structured_convolution_with_infinity(
arbitrary, convex, infinity, std::less<>());
}
template <class T>
std::vector<T> min_plus_convolution_convex_convex(const std::vector<T>& first,
const std::vector<T>& second) {
return convolution_detail::linear_structured_convolution(first, second, std::less<>());
}
template <class T>
std::vector<T> min_plus_convolution_convex_convex(
const std::vector<T>& first, const std::vector<T>& second,
const T& infinity) {
return convolution_detail::linear_structured_convolution_with_infinity(
first, second, infinity, std::less<>());
}
template <class T>
std::vector<T> max_plus_convolution_concave(const std::vector<T>& arbitrary,
const std::vector<T>& concave) {
auto add = [](const T& first, const T& second) { return first + second; };
return convolution_detail::structured_convolution(arbitrary, concave,
std::greater<>(), add);
}
template <class T>
std::vector<T> max_plus_convolution_concave(const std::vector<T>& arbitrary,
const std::vector<T>& concave,
const T& negative_infinity) {
return convolution_detail::structured_convolution_with_infinity(
arbitrary, concave, negative_infinity, std::greater<>());
}
template <class T>
std::vector<T> max_plus_convolution_concave_concave(const std::vector<T>& first,
const std::vector<T>& second) {
return convolution_detail::linear_structured_convolution(first, second, std::greater<>());
}
template <class T>
std::vector<T> max_plus_convolution_concave_concave(
const std::vector<T>& first, const std::vector<T>& second,
const T& negative_infinity) {
return convolution_detail::linear_structured_convolution_with_infinity(
first, second, negative_infinity, std::greater<>());
}
} // namespace convex
} // namespace m1une
#line 11 "convex/monge/all.hpp"
#line 1 "convex/slope_trick.hpp"
#line 7 "convex/slope_trick.hpp"
#include <queue>
#line 11 "convex/slope_trick.hpp"
namespace m1une {
namespace convex {
template <class T>
struct SlopeTrickArgmin {
std::optional<T> left;
std::optional<T> right;
};
template <class T>
class SlopeTrick {
static_assert(std::is_arithmetic_v<T> && std::is_signed_v<T>);
T _minimum = T();
T _left_offset = T();
T _right_offset = T();
std::priority_queue<T> _left;
std::priority_queue<T, std::vector<T>, std::greater<T>> _right;
T left_top() const {
return _left.top() + _left_offset;
}
T right_top() const {
return _right.top() + _right_offset;
}
void push_left(T value) {
_left.push(value - _left_offset);
}
void push_right(T value) {
_right.push(value - _right_offset);
}
public:
SlopeTrick() = default;
T minimum() const {
return _minimum;
}
int breakpoint_count() const {
return int(_left.size() + _right.size());
}
SlopeTrickArgmin<T> argmin() const {
SlopeTrickArgmin<T> result;
if (!_left.empty()) result.left = left_top();
if (!_right.empty()) result.right = right_top();
return result;
}
void add_constant(T value) {
_minimum += value;
}
void add_x_minus_a(T a) {
if (!_left.empty() && left_top() > a) {
T old = left_top();
_minimum += old - a;
_left.pop();
push_left(a);
push_right(old);
} else {
push_right(a);
}
}
void add_a_minus_x(T a) {
if (!_right.empty() && right_top() < a) {
T old = right_top();
_minimum += a - old;
_right.pop();
push_right(a);
push_left(old);
} else {
push_left(a);
}
}
void add_abs(T a) {
add_a_minus_x(a);
add_x_minus_a(a);
}
void clear_left() {
_left = std::priority_queue<T>();
}
void clear_right() {
_right = std::priority_queue<T, std::vector<T>, std::greater<T>>();
}
void prefix_minimum() {
clear_right();
}
void suffix_minimum() {
clear_left();
}
void shift(T delta) {
_left_offset += delta;
_right_offset += delta;
}
void shift(T left_delta, T right_delta) {
assert(left_delta <= right_delta);
_left_offset += left_delta;
_right_offset += right_delta;
}
T evaluate(T x) const {
T result = _minimum;
auto left = _left;
while (!left.empty()) {
T breakpoint = left.top() + _left_offset;
if (breakpoint > x) result += breakpoint - x;
left.pop();
}
auto right = _right;
while (!right.empty()) {
T breakpoint = right.top() + _right_offset;
if (x > breakpoint) result += x - breakpoint;
right.pop();
}
return result;
}
void merge(SlopeTrick other) {
add_constant(other._minimum);
while (!other._left.empty()) {
add_a_minus_x(other.left_top());
other._left.pop();
}
while (!other._right.empty()) {
add_x_minus_a(other.right_top());
other._right.pop();
}
}
void min_plus_convolve(SlopeTrick other) {
SlopeTrick result;
result._minimum = _minimum + other._minimum;
while (!_left.empty() && !other._left.empty()) {
result.push_left(left_top() + other.left_top());
_left.pop();
other._left.pop();
}
while (!_right.empty() && !other._right.empty()) {
result.push_right(right_top() + other.right_top());
_right.pop();
other._right.pop();
}
*this = std::move(result);
}
};
template <class T>
SlopeTrick<T> min_plus_convolution(SlopeTrick<T> first,
SlopeTrick<T> second) {
first.min_plus_convolve(std::move(second));
return first;
}
} // namespace convex
} // namespace m1une
#line 9 "convex/all.hpp"