传送门
首先把数组差分,那么就是要在差分数组中找 k k k个不相邻的数,使它们的和最小。
首先有一个暴力的DP做法: f ( i , j , 0 / 1 ) f(i,j,0/1) f(i,j,0/1)表示前 i i i个数,选了 j j j个,第 i i i个数不选/选,和最小是多少。 f ( i , j , 0 ) = min ( f ( i − 1 , j , 0 ) , f ( i − 1 , j , 1 ) ) , f ( i , j , 1 ) = f ( i − 1 , j − 1 , 0 ) + d i f(i,j,0)=\min(f(i-1,j,0),f(i-1,j,1)),f(i,j,1)=f(i-1,j-1,0)+d_i f(i,j,0)=min(f(i−1,j,0),f(i−1,j,1)),f(i,j,1)=f(i−1,j−1,0)+di这些转移都不必多说
但是这样复杂度是 O ( n k ) O(nk) O(nk)的并不能过。解决方法是按套路写个wqs二分优化把 j j j那一维降掉就行了。
#include
#include
#include
#include
template <typename T> inline void read(T& x) {
int f = 0, c = getchar(); x = 0;
while (!isdigit(c)) f |= c == '-', c = getchar();
while (isdigit(c)) x = x * 10 + c - 48, c = getchar();
if (f) x = -x;
}
template <typename T, typename... Args>
inline void read(T& x, Args&... args) {
read(x); read(args...);
}
template <typename T> void write(T x) {
if (x < 0) x = -x, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + 48);
}
template <typename T> inline void writeln(T x) { write(x); puts(""); }
template <typename T> inline bool chkmin(T& x, const T& y) { return y < x ? (x = y, true) : false; }
template <typename T> inline bool chkmax(T& x, const T& y) { return x < y ? (x = y, true) : false; }
typedef long long LL;
const int maxn = 1e5 + 207;
const LL inf = 1e10;
int n, K;
LL d[maxn];
// f[i][0] = min(f[i-1][0], f[i-1][1])
// f[i][1] = f[i-1][0] + d[i] - mid
struct Data {
int cnt;
LL f;
Data() : cnt(0), f(0) {}
Data(int a, LL b) : cnt(a), f(b) {}
};
Data dp[maxn][2];
inline bool operator<(const Data &lhs, const Data &rhs) {
return lhs.f < rhs.f || (lhs.f == rhs.f && lhs.cnt < rhs.cnt);
}
inline void solve(LL mid) {
for (int i = 0; i <= n; ++i)
dp[i][0] = dp[i][1] = Data();
for (int i = 1; i <= n; ++i) {
dp[i][0] = std::min(dp[i - 1][0], dp[i - 1][1]);
dp[i][1] = Data(dp[i - 1][0].cnt + 1, dp[i - 1][0].f + d[i] - mid);
}
}
int main() {
read(n, K);
for (int i = 0; i < n; ++i) read(d[i]);
for (int i = n - 1; i; --i) d[i] -= d[i - 1];
d[0] = 0; --n;
LL left = 0, right = inf, ans;
while (left <= right) {
LL mid = (left + right) >> 1;
solve(mid);
const Data &mn = std::min(dp[n][0], dp[n][1]);
if (mn.cnt <= K)
ans = mn.f + mid * K, left = mid + 1;
else right = mid - 1;
}
writeln(ans);
return 0;
}