53#ifndef DP_OPTIMIZATIONS_H
54#define DP_OPTIMIZATIONS_H
67namespace dp_optimization_detail {
70#if defined(_MSC_VER) && !defined(__clang__)
78 std::conditional_t<std::is_floating_point_v<T>,
85 if constexpr (std::numeric_limits<T>::has_infinity)
86 return std::numeric_limits<T>::infinity();
88 return std::numeric_limits<T>::max() / 4;
91template <
typename Target,
typename Source>
94 if (val >=
static_cast<Source
>(std::numeric_limits<Target>::max()))
95 return std::numeric_limits<Target>::max();
96 if (val <=
static_cast<Source
>(std::numeric_limits<Target>::min()))
97 return std::numeric_limits<Target>::min();
98 return static_cast<Target
>(val);
104template <
typename Cost>
136template <
typename Cost,
class Transition_Cost_Fn>
140 Transition_Cost_Fn transition_cost,
141 const Cost inf = dp_optimization_detail::default_inf<Cost>())
146 for (
size_t i = 0; i <= n; ++i)
154 split.reserve(groups + 1);
155 for (
size_t g = 0; g <= groups; ++g)
158 for (
size_t i = 0; i <= n; ++i)
163 for (
size_t g = 1; g <= groups; ++g)
165 for (
size_t i = 0; i <= n; ++i)
170 auto solve = [&](
auto &&self,
const size_t left,
const size_t right,
171 const size_t opt_left,
const size_t opt_right) ->
void
176 const size_t mid = std::midpoint(left, right);
177 const size_t k_end = std::min(mid - 1, opt_right);
180 size_t best_k = opt_left;
182 for (
size_t k = opt_left;
k <= k_end; ++
k)
187 const Cost tc = transition_cost(
k, mid);
189 if (tc >= inf or prev[
k] > inf - tc)
202 split[g](mid) = best_k;
205 self(self, left, mid - 1, opt_left, best_k);
207 self(self, mid + 1, right, best_k, opt_right);
210 solve(solve, g, n, g - 1, n - 1);
221template <
typename Cost>
251template <
typename Cost,
class Interval_Cost_Fn>
254 Interval_Cost_Fn interval_cost,
255 const Cost inf = dp_optimization_detail::default_inf<Cost>())
259 for (
size_t i = 0; i <= n; ++i)
262 for (
size_t j = 0; j <= n; ++j)
269 for (
size_t i = 0; i <= n; ++i)
272 for (
size_t j = 0; j <= n; ++j)
277 for (
size_t i = 0; i <= n; ++i)
283 dp(i)(i + 1) = Cost{};
284 opt(i)(i + 1) = i + 1;
288 for (
size_t len = 2; len <= n; ++len)
289 for (
size_t i = 0; i + len <= n; ++i)
291 const size_t j = i + len;
293 size_t left = opt[i][j - 1];
294 size_t right = opt[i + 1][j];
301 <<
"knuth_optimize_interval: invalid opt bounds at [" << i <<
", " << j <<
")";
303 const Cost
w = interval_cost(i, j);
306 size_t best_k = left;
308 for (
size_t k = left;
k <= right; ++
k)
310 const Cost d1 = dp[i][
k];
311 const Cost d2 = dp[
k][j];
313 if (d1 >= inf or d2 >= inf or
w >= inf or d1 > inf - d2 or (d1 + d2) > inf -
w)
344 const size_t n = weights.
size();
348 for (
size_t i = 0; i < n; ++i)
351 <<
"optimal_merge_knuth: prefix sum overflow";
355 return knuth_optimize_interval<size_t>(n, [&](
const size_t i,
const size_t j) ->
size_t
358 }, std::numeric_limits<size_t>::max() / 4);
372 static_assert(std::is_signed_v<T>,
"Convex_Hull_Trick requires a signed type");
384 return static_cast<T>(
static_cast<PromotedT
>(
slope) *
static_cast<PromotedT
>(x) +
396 return static_cast<long double>(b.intercept - a.intercept) /
397 static_cast<long double>(a.slope - b.slope);
418 :
lines_(std::move(other.lines_)),
starts_(std::move(other.starts_)),
419 cursor_(std::exchange(other.cursor_, 0))
450 lines_.swap(other.lines_);
452 std::swap(
cursor_, other.cursor_);
455 [[nodiscard]]
size_t size() const noexcept
462 return lines_.size() == 0;
490 <<
"Convex_Hull_Trick::add_line: slopes must be non-increasing";
493 if (ln.slope == last.slope)
495 if (ln.intercept >= last.intercept)
498 (void)
lines_.remove_last();
518 (void)
lines_.remove_last();
524 starts_.
append(-std::numeric_limits<long double>::infinity());
536 size_t hi =
lines_.size() - 1;
537 const auto xd =
static_cast<long double>(x);
540 if (
const size_t mid = std::midpoint(lo, hi + 1);
starts_[mid] <= xd)
545 return lines_[lo].value_at(x);
552 <<
"Convex_Hull_Trick::query_monotone: no lines available";
571 static_assert(std::is_integral_v<T>
and std::is_signed_v<T>,
572 "Li_Chao_Tree requires a signed integral coordinate/value type");
584 return static_cast<T>(
static_cast<PromotedT
>(
slope) *
static_cast<PromotedT
>(x) +
593 size_t left = std::numeric_limits<size_t>::max();
594 size_t right = std::numeric_limits<size_t>::max();
597 static constexpr size_t NIL = std::numeric_limits<size_t>::max();
612 const T mid = std::midpoint(
l,
r);
615 std::swap(line,
nodes_[idx].line);
645 auto ret =
static_cast<PromotedT
>(
nodes_[idx].line.value_at(x));
647 return static_cast<T>(ret);
649 const T mid = std::midpoint(
l,
r);
651 ret = std::min(ret,
static_cast<PromotedT
>(
query_impl(
nodes_[idx].left,
l, mid, x)));
653 ret = std::min(ret,
static_cast<PromotedT
>(
query_impl(
nodes_[idx].right, mid + 1,
r, x)));
655 return dp_optimization_detail::clamped_cast<T>(ret);
662 <<
"Li_Chao_Tree: invalid domain [" <<
x_left_ <<
", " <<
x_right_ <<
"]";
681 root_(std::exchange(other.root_,
NIL))
707 std::swap(
x_left_, other.x_left_);
708 std::swap(
x_right_, other.x_right_);
709 nodes_.swap(other.nodes_);
710 std::swap(
root_, other.root_);
744 <<
"Li_Chao_Tree::query: x=" << x <<
" outside domain [" <<
x_left_ <<
", " <<
x_right_ <<
"]";
752template <
typename Cost>
778template <
typename Cost>
782 const Cost inf = dp_optimization_detail::default_inf<Cost>())
784 const size_t n = base_cost.
size();
789 <<
"monotone_queue_min_dp: window must be > 0 when n > 1";
797 dp(0) = base_cost[0];
801 for (
size_t i = 1; i < n; ++i)
803 const size_t min_valid = i > window ? i - window : 0;
805 while (head < deque_idx.
size()
and deque_idx[head] < min_valid)
809 <<
"monotone_queue_min_dp: no valid predecessor for i=" << i;
811 const size_t best = deque_idx[head];
812 const Cost bc = base_cost[i];
813 if (dp[best] >= inf or bc >= inf or dp[best] > inf - bc)
816 dp(i) = dp[best] + bc;
820 while (deque_idx.
size() > head
and dp[deque_idx[deque_idx.
size() - 1]] >= dp[i])
853 static_assert(std::is_integral_v<T>
and std::is_signed_v<T>,
854 "min_weighted_squared_distance_1d requires signed integral T");
857 <<
"min_weighted_squared_distance_1d: xs and weights size mismatch";
859 const size_t n = xs.
size();
865 for (
size_t i = 1; i < n; ++i)
875 for (
size_t j = 0; j < n; ++j)
877 const auto px =
static_cast<PromotedT
>(xs[j]);
878 const T m =
static_cast<T>(
static_cast<PromotedT
>(-2) * px);
879 const T b =
static_cast<T>(px * px +
static_cast<PromotedT
>(weights[j]));
884 for (
size_t i = 0; i < n; ++i)
886 const auto px =
static_cast<PromotedT
>(xs[i]);
887 ret(i) =
static_cast<T>(px * px +
static_cast<PromotedT
>(lc.
query(xs[i])));
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
#define ah_runtime_error_if(C)
Throws std::runtime_error if condition holds.
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
void swap(Array &s) noexcept
Swap this with s
static Array create(const size_t n)
Create an array with n logical elements.
T & append(const T &data)
Append a copy of data
void reserve(size_t cap)
Reserves cap cells into the array.
Convex Hull Trick for minimum queries.
Convex_Hull_Trick(Convex_Hull_Trick &&other) noexcept
Take the lines of another hull, which is left empty, as clear() leaves it.
static long double intersection_x(const Line &a, const Line &b) noexcept
bool is_empty() const noexcept
T query_monotone(const T x)
Query minimum with non-decreasing x (amortized O(1)).
Convex_Hull_Trick & operator=(const Convex_Hull_Trick &other)=default
Copy the lines and the query cursor of another hull.
void reset_query_cursor() noexcept
T query(const T x) const
Query minimum value at arbitrary x (O(log n)).
Convex_Hull_Trick & operator=(Convex_Hull_Trick &&other) noexcept
Exchange this hull with another, which is left with the previous lines and cursor of this one.
size_t size() const noexcept
void swap(Convex_Hull_Trick &other) noexcept
Exchange in O(1) the lines and the cursors of this hull and another.
void add_line(const T slope, const T intercept)
Insert a new line; slopes must be non-increasing.
Array< long double > starts_
Convex_Hull_Trick()=default
Construct an empty hull.
Convex_Hull_Trick(const Convex_Hull_Trick &other)=default
Copy the lines and the query cursor of another hull.
Li Chao tree for min line queries on an integral x-domain.
void add_line(const T slope, const T intercept)
static constexpr size_t NIL
void swap(Li_Chao_Tree &other) noexcept
Exchange in O(1) the domains and the lines of this tree and another.
T query_impl(const size_t idx, const T l, const T r, const T x) const
bool is_empty() const noexcept
Li_Chao_Tree & operator=(Li_Chao_Tree &&other) noexcept
Exchange this tree with another, which is left with the previous domain and lines of this one.
Li_Chao_Tree & operator=(const Li_Chao_Tree &other)=default
Copy the domain and the lines of another tree.
Li_Chao_Tree(Li_Chao_Tree &&other) noexcept
Take the lines of another tree, which is left empty over the same domain.
Li_Chao_Tree(const Li_Chao_Tree &other)=default
Copy the domain and the lines of another tree.
void add_line_impl(const size_t idx, const T l, const T r, Line line)
size_t node_count() const noexcept
size_t new_node(const Line &line)
Li_Chao_Tree(const T x_left, const T x_right)
std::conditional_t< std::is_floating_point_v< T >, T, std::conditional_t<(sizeof(T)< 8), long long, _promoted_int_t > > promoted_t
__int128_t _promoted_int_t
constexpr T default_inf() noexcept
constexpr Target clamped_cast(Source val) noexcept
Main namespace for Aleph-w library functions.
DynList< T > intercept(const Container< T > &c1, const Container< T > &c2)
Return intersection of two containers as a DynList.
Array< T > min_weighted_squared_distance_1d(const Array< T > &xs, const Array< T > &weights)
Weighted squared-distance lower envelope on a line.
Divide_Conquer_DP_Result< Cost > divide_and_conquer_partition_dp(const size_t groups, const size_t n, Transition_Cost_Fn transition_cost, const Cost inf=dp_optimization_detail::default_inf< Cost >())
Optimize partition DP using divide-and-conquer optimization.
std::decay_t< typename HeadC::Item_Type > T
Knuth_Optimization_Result< size_t > optimal_merge_knuth(const Array< size_t > &weights)
Optimal adjacent merge cost via Knuth optimization.
static void prefix(Node *root, DynList< Node * > &acc)
Monotone_Queue_DP_Result< Cost > monotone_queue_min_dp(const Array< Cost > &base_cost, const size_t window, const Cost inf=dp_optimization_detail::default_inf< Cost >())
Optimize windowed min-transition DP with a monotone queue.
and
Check uniqueness with explicit hash + equality functors.
std::vector< std::string > & split(const std::string &s, const char delim, std::vector< std::string > &elems)
Split a std::string by a single delimiter character.
Knuth_Optimization_Result< Cost > knuth_optimize_interval(const size_t n, Interval_Cost_Fn interval_cost, const Cost inf=dp_optimization_detail::default_inf< Cost >())
Optimize interval DP with Knuth optimization.
T value_at(const T x) const noexcept
Result of divide-and-conquer partition DP optimization.
Array< Cost > last_row
Last DP layer (size n+1).
Array< Array< size_t > > split
Best split index per layer/state.
Cost optimal_cost
Final optimum at state (groups, n).
Result of Knuth interval-DP optimization.
Array< Array< Cost > > dp
Interval DP table.
Cost optimal_cost
Final optimum at interval [0, n).
Array< Array< size_t > > opt
Argmin table used by Knuth bounds.
T value_at(const T x) const noexcept
Result of monotone-queue windowed DP transition.
Array< Cost > dp
DP values.
Array< size_t > parent
Chosen predecessor index for each i.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Dynamic array container with automatic resizing.