This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
//#pragma GCC optimize("unroll-loops")
//#pragma GCC optimize("Ofast")
//#pragma GCC optimize("-O3")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define vec vector
#define sz(x) ( int)x.size()
#define m_p make_pair
#define f first
#define s second
#define pb push_back
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
using namespace std;
typedef long long ll;
typedef pair<ll, int> pli;
typedef pair<int,ll> pil;
typedef pair<int,int> pii;
typedef unsigned long long ull;
auto rng=bind(uniform_int_distribution<int>(1,1000),mt19937(time(0)));
template<class T> bool umax(T &a,const T &b){return (a<b?a=b,1:0);}
template<class T> bool umin(T &a,const T &b){return (a>b?a=b,1:0);}
const int N=1e5+1;
const int K=100;
const int lg=(int)log2(N)+1;
int lft[N],rgt[N];
int dp[N][K],a[N];
int st[N][K];
signed main(){
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int n,k;
// n=100;k=30;
cin>>n>>k;
for(int i=0;i<n;i++) cin>>a[i];
{
vec<pii>vc;
vc.pb({2e9,-1});
for(int i=0;i<n;i++){
while(sz(vc) && vc.back().f<=a[i]) vc.pop_back();
lft[i]=vc.back().s;
vc.pb({a[i],i});
}
}
{
vec<pii>vc;
vc.pb({2e9,n});
for(int i=n-1;i>=0;i--){
while(sz(vc) && vc.back().f<=a[i]) vc.pop_back();
rgt[i]=vc.back().s;
vc.pb({a[i],i});
}
}
for(int i=0;i<=n;i++){
for(int j=0;j<=k;j++){
dp[i][j]=st[i][j]=1e9;
}
}
dp[0][0]=0;
st[0][0]=0;
for(int j=1;j<=k;j++){
for(int r=j;r<=n;r++){
int mx=-1;
for(int l=r-1;l>=(j-1);l--){
umax(mx,a[l]);
umin(st[r][j],mx+st[l][j-1]);
}
}
}
for(int j=1;j<=k;j++){
for(int i=0;i<=n;i++) dp[i][j]=2e9;
for(int i=n-1;i>=0;i--) umin(dp[i][j-1],dp[i+1][j-1]);
// for(int i=0;i<=n;i++) cerr<<dp[i][j-1]<<' ';
// cout<<endl;
for(int i=j-1;i<n;i++){
// cerr<<dp[i][j-1]
// for(int t=)
int k=lft[i]+1;
umin(dp[rgt[i]][j],dp[k][j-1]+a[i]);
// cerr<<dp[i][j]
}
}
// assert(dp[n][k]==st[n][k]);
cout<<st[n][k];
return 0;
}
/*
4 3
1 2 2 1
*/
# | 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... |