#include <bits/stdc++.h>
using namespace std;
#define for_(i, s, e) for (int i = s; i < (int) e; i++)
#define for__(i, s, e) for (ll i = s; i < e; i++)
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
#define endl '\n'
int main() {
#ifndef ONLINE_JUDGE
//freopen("test.in", "r", stdin);
#endif
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, k; cin >> n >> k;
vector<ll> nums(n);
for_(i, 0, n) cin >> nums[i];
vector<ll> prev(n), curr(n, 1e15);
prev[n-1] = nums[n-1];
for (int i = n-2; i >= 0; i--) prev[i] = max(nums[i], prev[i+1]);
for_(l, 1, k) {
stack<vector<ll>> s; // {max val index, min prev val till next max}
curr[n-l-1] = nums[n-l-1] + prev[n-l];
s.push({n-l-1, prev[n-l]});
for (int i = n-l-2; i >= 0; i--) {
ll mn = prev[i+1], ans = prev[i+1]+nums[i];
while (s.size()) {
if (nums[s.top()[0]] <= nums[i]) {
mn = min(mn, s.top()[1]);
s.pop();
} else {
ans = min(ans, curr[s.top()[0]]);
break;
}
}
s.push({i, mn});
curr[i] = min(ans, nums[i] + mn);
}
swap(prev, curr);
curr.assign(n, 1e15);
}
ll ans = 1e15;
for_(i, 0, n) ans = min(ans, prev[i]);
cout << ans << endl;
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
384 KB |
Output is correct |
2 |
Incorrect |
0 ms |
384 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
2 ms |
384 KB |
Output is correct |
2 |
Incorrect |
1 ms |
384 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
1 ms |
384 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
17 ms |
768 KB |
Output is correct |
2 |
Correct |
6 ms |
1408 KB |
Output is correct |
3 |
Correct |
23 ms |
2304 KB |
Output is correct |
4 |
Correct |
225 ms |
2304 KB |
Output is correct |
5 |
Correct |
670 ms |
4828 KB |
Output is correct |
6 |
Incorrect |
25 ms |
4608 KB |
Output isn't correct |
7 |
Halted |
0 ms |
0 KB |
- |