#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;
int a[maxn],dp[maxn][maxk];
stack<pair<int,int>> st[maxk];
multiset<int> s[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++)
{
s[i].insert(1e9+500);
dp[0][i] = 1e9+500;
st[i].push({1e9+500,0});
v[i].eb({0,1e9 + 500});
}
s[0].insert(0);
for(i = 1;i<=n;i++)
{
dp[i][0] = 1e9 + 500;
cin>>a[i];
for(j = 1;j<=k;j++)
{
dp[i][j] = 1e9 + 500;
if(j <= i)
{
while(st[j].top().fi <= a[i] && st[j].top().se >= j)
{
auto it = s[j].find(dp[st[j].top().se][j]);
if(it != s[j].end())s[j].erase(it);
st[j].pop();
}
auto it = lower_bound( all(v[j-1]) , make_pair(st[j].top().se+1,0) );
if(it != v[j-1].end())dp[i][j] = min(dp[i][j], it->se + a[i]);
dp[i][j] = min({dp[i][j], dp[ st[j].top().se ][ j - 1 ] + a[i], *s[j].begin() });
s[j].insert(dp[i][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... |