#include <bits/stdc++.h>
using namespace std;
#define all(v) v.begin(),v.end()
#define eb push_back
#define ll long long
#define fi first
#define se second
int t,n,i,k,j;
const int maxn = 1e6 + 10,maxk = 110,inf = 1e9 + 500;
int a[maxn],dp[maxn][maxk];
struct bruh
{
int va,mn,id;
};
stack<bruh> st[maxk];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cin>>n>>k;
for(i = 1;i<=k;i++)
{
dp[0][i] = inf;
st[i].push({inf,0,0});
}
dp[0][0] = 0;
st[0].push({inf,0,0});
for(i = 1;i<=n;i++)
{
dp[i][0] = inf;
cin>>a[i];
for(j = k;j>=1;j--)
{
dp[i][j] = inf;
if(j <= i)
{
int tmp = inf;
while(st[j].top().va <= a[i] && st[j].size() > j + 1)
{
tmp = min(tmp,st[j].top().mn);
st[j].pop();
}
st[j].top().mn = min(st[j].top().mn,tmp);
tmp = inf;
while(st[j-1].top().va <= a[i] && st[j-1].size() > j)
{
// cout<<i<<' '<<j<<" eliminate "<<st[j-1].top().id<<'\n';
tmp = min(tmp,st[j-1].top().mn);
st[j-1].pop();
}
st[j-1].top().mn = min(st[j-1].top().mn,tmp);
// cout<<i<<' '<<j<<' '<<st[j].top().id<<' '<<st[j].top().va<<'\n';
dp[i][j] = st[j-1].top().mn + a[i];
if(st[j].top().va > a[i])dp[i][j] = min(dp[i][j],dp[st[j].top().id][j]);
}
st[j].push({a[i],dp[i][j],i});
}
}
// for(j = 0;j<=k;j++)
// {
// for(i = 0;i<=n;i++)
// {
// cout<<(dp[i][j] >= 1e9 ? -1 : dp[i][j])<<' ';
// }
// cout<<'\n';
// }
cout<<dp[n][k];
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... |