#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];
stack<pair<int,int>> st[maxk];
vector<pair<int,int>> v[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});
v[i].eb({0,-100000});
}
v[0].eb({0,-100000});
for(i = 1;i<=n;i++)
{
dp[i][0] = inf;
cin>>a[i];
for(j = k;j;j--)
{
dp[i][j] = inf;
if(j <= i)
{
while(st[j].top().fi <= a[i] && st[j].size() > j)
{
st[j].pop();
}
if(i == j)
{
dp[i][j] = dp[i-1][j-1] + a[i];
}
auto it = lower_bound(all(v[j-1]) , make_pair(st[j].top().se,0));
dp[i][j] = min(dp[i][j],it->se + a[i]);
// for(int l = i-1;l >= st[j].top().se;l--)dp[i][j] = min(dp[i][j] , dp[l][j-1] + a[i]);
if(st[j].top().fi > a[i])dp[i][j] = min(dp[i][j], dp[ st[j].top().se ][j]);
}
st[j].push({a[i],i});
while(v[j].back().fi <=i && v[j].back().se >= dp[i][j])v[j].pop_back();
v[j].eb({i,dp[i][j]});
}
}
// 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... |