cpp-library

This documentation is automatically generated by competitive-verifier/competitive-verifier

View the Project on GitHub shino16/cpp-library

:heavy_check_mark: dp/knuth_merge.hpp

Depends on

Verified with

Code

#pragma once
#include "prelude.hpp"

// O(n^2)
// Starts with dp(l, r) = 0 (r - l <= 1) and
// dp(l, r) = min { dp(l, k) + dp(k, r) + cost(l, r) : l < k < r }
// Requires cost(b,c) <= cost(a,d) and
//          cost(a,c) + cost(b,d) <= cost(a,d) + cost(b,c)
// for a < b < c < d (wider is worse).
template <class F>
auto knuth_merge_dp(int n, F cost) {
  using T = decltype(cost(0, 0));
  vector<vector<T>> dp(n + 1, vector<T>(n + 1, numeric_limits<T>::max() / 2));
  vector<int> opt(n + 2), opt2(n + 2);
  repr(k, n + 1) {
    dp[k][k] = T(0), opt[k] = k;
    if (k + 1 <= n) dp[k][k + 1] = T(0);
    rep2(i, k + 2, n + 1) rep2(j, max(k + 1, opt2[i - 1]), min(i, opt[i] + 1)) {
      if (dp[k][i] > dp[k][j] + dp[j][i] + cost(k, i))
        dp[k][i] = dp[k][j] + dp[j][i] + cost(k, i), opt2[i] = j;
    }
    swap(opt, opt2);
  }
  return dp;
}
#line 2 "prelude.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vector<int>>;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using vc = vector<char>;
#define rep2(i, m, n) for (auto i = (m); i < (n); i++)
#define rep(i, n) rep2(i, 0, n)
#define repr2(i, m, n) for (auto i = (n); i-- > (m);)
#define repr(i, n) repr2(i, 0, n)
#define all(x) begin(x), end(x)
auto ndvec(int n, auto e) { return vector(n, e); }
auto ndvec(int n, auto ...e) { return vector(n, ndvec(e...)); }
auto comp_key(auto&& f) { return [&](auto&& a, auto&& b) { return f(a) < f(b); }; }
auto& max(const auto& a, const auto& b) { return a < b ? b : a; }
auto& min(const auto& a, const auto& b) { return b < a ? b : a; }
#if __cpp_lib_ranges
namespace R = std::ranges;
namespace V = std::views;
#endif
#line 3 "dp/knuth_merge.hpp"

// O(n^2)
// Starts with dp(l, r) = 0 (r - l <= 1) and
// dp(l, r) = min { dp(l, k) + dp(k, r) + cost(l, r) : l < k < r }
// Requires cost(b,c) <= cost(a,d) and
//          cost(a,c) + cost(b,d) <= cost(a,d) + cost(b,c)
// for a < b < c < d (wider is worse).
template <class F>
auto knuth_merge_dp(int n, F cost) {
  using T = decltype(cost(0, 0));
  vector<vector<T>> dp(n + 1, vector<T>(n + 1, numeric_limits<T>::max() / 2));
  vector<int> opt(n + 2), opt2(n + 2);
  repr(k, n + 1) {
    dp[k][k] = T(0), opt[k] = k;
    if (k + 1 <= n) dp[k][k + 1] = T(0);
    rep2(i, k + 2, n + 1) rep2(j, max(k + 1, opt2[i - 1]), min(i, opt[i] + 1)) {
      if (dp[k][i] > dp[k][j] + dp[j][i] + cost(k, i))
        dp[k][i] = dp[k][j] + dp[j][i] + cost(k, i), opt2[i] = j;
    }
    swap(opt, opt2);
  }
  return dp;
}
Back to top page