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;
class sparse_table {
public:
sparse_table(vector<int>&a) : n(a.size()) {
lg.resize(1 + n);
lg[0] = lg[1] = 0;
for (int i = 2; i <= n; i++)
lg[i] = lg[i / 2] + 1;
mx.assign(n, vector<int>(1 + lg[n]));
for (int j = 0; j <= lg[n]; j++)
for (int i = 0; i <= n - (1 << j); i++)
if (j == 0) mx[i][j] = a[i];
else mx[i][j] = max(mx[i][j-1], mx[i+(1<<(j-1))][j-1]);
}
int query(int l, int r) {
int d = lg[r-l+1];
return max(mx[l][d], mx[r-(1<<d)+1][d]);
}
private:
int n;
vector<int> lg;
vector<vector<int>> mx;
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<int> a(1 + n);
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
sparse_table st(a);
vector<vector<long long>> dp(1 + n, vector<long long>(1 + k, 1e18));
for (int i = 1; i <= n; i++) {
dp[i][1] = st.query(1, i);
}
int K = k;
for (int k = 2; k <= K; k++) {
stack<pair<int, long long>> st;
for (int i = 1; i <= n; i++) {
long long mn = dp[i - 1][k - 1];
while (!st.empty() && a[st.top().first] <= a[i]) {
mn = min(mn, st.top().second);
st.pop();
}
if (!st.empty())
dp[i][k] = min(dp[i][k], dp[st.top().first][k]);
dp[i][k] = min(dp[i][k], mn + a[i]);
st.push({i, mn});
}
}
cout << dp[n][k] << '\n';
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... |