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>
using namespace std;
#define fi first
#define se second
typedef long long ll;
typedef pair<ll, ll> ii;
const int N = 1e5 + 7, M = 107;
int n, k, a[N], L[N], dp[N][M];
stack<int> st;
int T[N][M];
void upd(int i, int j, int v) {
    for (; i <= n; i += i & -i)
        T[i][j] = min(T[i][j], v);
}
int get(int i, int l, int r) {
    int res = 2e9;
    while (l <= r) {
        if (r - (r & -r) >= l) {
            res = min(res, T[r][i]);
            r -= r & -r;
        }
        else {
            res = min(res, dp[r][i]);
            --r;
        }
    }
    return res;
}
int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    cin >> n >> k;
    for (int i = 1; i <= n; i++) cin >> a[i];
    memset(dp, 0x3f, sizeof dp);
    memset(T, 0x3f, sizeof T);
    dp[0][1] = 0;
    for (int i = 1; i <= n; i++) {
        dp[i][1] = max(dp[i - 1][1], a[i]);
        upd(i, 1, dp[i][1]);
    }
    for (int i = 1; i <= n; i++) {
        while (st.size() && a[st.top()] <= a[i]) st.pop();
        if (st.empty()) {
            for (int j = 2; j <= k; j++) {
                dp[i][j] = get(j - 1, 1, i) + a[i];
                upd(i, j, dp[i][j]);
            }
        }
        else {
            for (int j = 2; j <= k; j++) {
                dp[i][j] = min(get(j - 1, st.top() + 1, i) + a[i], dp[L[i] - 1][j - 1] + a[L[i]]);
                upd(i, j, dp[i][j]);
            }
        }
        st.push(i);
        // f(i, j) = min(f(k - 1, j - 1) + max(a[k]..a[i]))
    }
    cout << dp[n][k];
}
| # | 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... |