#include <bits/stdc++.h>
using namespace std;
#define int long long
const int INF = 1e18;
const int mxN = 100005;
const int mxK = 105;
int a[mxN], dp[mxN][mxK], mn[mxN];
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(nullptr); cout.tie(nullptr);
int N, K;
cin >> N >> K;
memset(dp, INF, sizeof(dp));
for(int i = 1; i <= N; ++i) cin >> a[i];
for(int i = 0; i <= N; ++i) dp[i][0] = 0;
for(int i = 1, mx = 1; i <= N; ++i){
mx = max(mx, a[i]);
dp[i][1] = mx;
}
vector<int> mn(N + 1, INF);
for(int k = 2; k <= K; ++k){
stack<int> st;
for(int i = 1; i <= N; ++i){
mn[i] = INF;
while(st.size() && a[st.top()] <= a[i]){
dp[i][k] = min(dp[i][k], dp[st.top() - 1][k - 1] + a[i]);
mn[i] = min({mn[i], dp[st.top()][k - 1], mn[st.top()]});
dp[i][k] = min(dp[i][k], mn[i] + a[i]);
st.pop();
}
if(st.size()){
dp[i][k] = min(dp[i][k], dp[st.top()][k]); // extend
dp[i][k] = min(dp[i][k], dp[st.top()][k - 1] + a[i]); // from st.top() + 1, to i
dp[i][k] = min(dp[i][k], dp[st.top() - 1][k - 1] + a[st.top()]); // (st.top() -> i)
// dp[i][k] = min(dp[i][k], mn[st.top()] + a[i]); mn[i] not equal to dp[st.top()][k - 1]
}
dp[i][k] = min(dp[i][k], dp[i - 1][k - 1] + a[i]);
st.push(i);
}
}
cout << dp[N][K] << "\n";
return 0;
}
Compilation message (stderr)
blocks.cpp: In function 'int main()':
blocks.cpp:14:16: warning: overflow in conversion from 'long long int' to 'int' changes value from '1000000000000000000' to '-1486618624' [-Woverflow]
14 | memset(dp, INF, sizeof(dp));
| ^~~
# | 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... |