#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define all(v) (v).begin(), (v).end()
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, K;
cin >> n >> K;
vector<int> a(n + 1);
for (int i = 1; i <= n; i++)
cin >> a[i];
stack<int> s;
vector<int> L(n + 1);
for (int i = 1; i <= n; i++) {
while (!s.empty() && a[s.top()] < a[i]) s.pop();
L[i] = (!s.empty() ? s.top() : 0);
s.push(i);
}
vector<vector<ll>> dp(K + 1, vector<ll>(n + 1, (ll)1e18));
dp[0][0] = 0;
for (int i = 1; i <= K; i++) {
deque<int> v;
for (int j = 1; j <= n; j++) {
if (~L[j]) dp[i][j] = dp[i][L[j]];
while (!v.empty() && dp[i - 1][v.back()] > dp[i - 1][j - 1]) v.pop_back();
v.push_back(j - 1);
dp[i][j] = min(dp[i][j], dp[i - 1][*lower_bound(all(v), L[j])] + a[j]);
}
}
cout << dp[K][n];
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |