#include <bits/stdc++.h>
using namespace std;
const int N = 100000 + 5;
const int K = 105;
const int INF = 0x3f3f3f3f;
int a[N];
int dp[K][N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
for (int i = 1; i <= n; ++i)
cin >> a[i];
memset(dp, 0x3f, sizeof dp);
// base cho i = 1: một nhóm → max trên tiền tố
dp[1][0] = 0;
for (int j = 1; j <= n; ++j)
dp[1][j] = max(dp[1][j - 1], a[j]);
// các lớp i >= 2
for (int i = 2; i <= k; ++i)
{
vector<pair<int, int>> st; // {best, idx}, best = min(dp[i-1][t]) của vùng mà idx làm max
st.reserve(n);
for (int j = i; j <= n; ++j)
{
int cur = dp[i - 1][j - 1]; // cắt ngay trước j
while (!st.empty() && a[st.back().second] <= a[j])
{
cur = min(cur, st.back().first); // nuốt vùng có max <= a[j]
st.pop_back();
}
int cand2 = st.empty() ? INF : dp[i][st.back().second]; // phần còn lại (max > a[j])
dp[i][j] = min(cur + a[j], cand2);
st.emplace_back(cur, j); // j đại diện vùng "max = a[j]"
}
}
cout << dp[k][n] << '\n';
return 0;
}
# | 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... |