# include <bits/stdc++.h>
using namespace std;
#define int long long
int k,n,a[100005],lg2[1000005],dp[100005][105],b[400005][105],l[100005],res;
stack<int> g;
void build(int r)
{
for (int i = 1; i <= n; i++) b[i][0] = dp[i][r];
for (int j = 1; j <= lg2[n]; j++)
for (int i = 1; i + (1 << j) - 1 <= n; i++)
b[i][j] = min(b[i][j-1], b[i + (1 << (j-1))][j-1]);
}
long long getmin(int l, int r)
{
if (l > r) return 1e9;
int j = lg2[r - l + 1];
return min(b[l][j], b[r-(1<<j)+1][j]);
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
for (int i = 1; i <= n; i++)
{
while (!g.empty() and a[g.top()] <= a[i]) g.pop();
if (g.empty()) l[i] = 0;
else l[i] = g.top();
g.push(i);
}
for (int i = 2; i <= n; i++) lg2[i] = lg2[i/2] + 1;
for (int i =0; i <= n; i++) for (int j = 0; j <= k; j++) dp[i][j] = 1e9;
dp[0][0] = 0;
dp[1][1] = a[1];
for (int i = 2; i <= n; i++)
{
dp[i][1] = max(dp[i-1][1],a[i]);
}
for (int j = 1; j <= k; j++)
{
build(j-1);
for (int i = 1; i <= n; i++)
{
if (i < j) continue;
if (l[i] >= j) dp[i][j] = dp[l[i]][j];
dp[i][j] = min(dp[i][j], getmin(max(j-1,l[i]), i-1) + a[i]);
}
}
// dp[i][j] la so tien nho nhat xet den vi tri i va da chia dc j doan
cout << dp[n][k];
}
| # | 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... |