cpp-library

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

View the Project on GitHub shino16/cpp-library

:heavy_check_mark: dp/d_and_c.hpp

Depends on

Verified with

Code

#pragma once
#include "prelude.hpp"

// O(k n log(n))
// Minimizes cost of k-partitions of [0, n) with k <= max_k
// (k == max_k if cost(i,i) == inf).
// Requires cost(a,c) + cost(b,d) <= cost(a,d) + cost(b,c)
// for a < b < c < d (wider is worse).
template <class F>
auto d_and_c_dp(int max_k, int n, F cost) {
  using T = decltype(cost(0, 0));
  vector<T> dp(n + 1), nxt(n + 1);
  rep(i, n + 1) dp[i] = cost(0, i);
  auto rec = [&](auto&& f, int l, int r, int optl, int optr) -> void {
    if (l == r) return;
    int m = (l + r) / 2;
    T best = numeric_limits<T>::max() / 2;
    int opt = -1;
    rep2(j, optl, min(m, optr) + 1) {
      if (best > dp[j] + cost(j, m)) best = dp[j] + cost(j, m), opt = j;
    }
    nxt[m] = best;
    f(f, l, m, optl, opt);
    f(f, m + 1, r, opt, optr);
  };
  rep2(k, 1, max_k) rec(rec, 0, n + 1, 0, n - 1), swap(dp, nxt);
  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/d_and_c.hpp"

// O(k n log(n))
// Minimizes cost of k-partitions of [0, n) with k <= max_k
// (k == max_k if cost(i,i) == inf).
// Requires cost(a,c) + cost(b,d) <= cost(a,d) + cost(b,c)
// for a < b < c < d (wider is worse).
template <class F>
auto d_and_c_dp(int max_k, int n, F cost) {
  using T = decltype(cost(0, 0));
  vector<T> dp(n + 1), nxt(n + 1);
  rep(i, n + 1) dp[i] = cost(0, i);
  auto rec = [&](auto&& f, int l, int r, int optl, int optr) -> void {
    if (l == r) return;
    int m = (l + r) / 2;
    T best = numeric_limits<T>::max() / 2;
    int opt = -1;
    rep2(j, optl, min(m, optr) + 1) {
      if (best > dp[j] + cost(j, m)) best = dp[j] + cost(j, m), opt = j;
    }
    nxt[m] = best;
    f(f, l, m, optl, opt);
    f(f, m + 1, r, opt, optr);
  };
  rep2(k, 1, max_k) rec(rec, 0, n + 1, 0, n - 1), swap(dp, nxt);
  return dp;
}
Back to top page