#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
struct dsu {
vector<int> parent, rank;
vector<long long> min_val;
dsu(int n) : parent(n), rank(n, 1) {
iota(parent.begin(), parent.end(), 0);
}
int get(int u) {
return parent[u] == u ? u : (parent[u] = get(parent[u]));
}
void unite(int u, int v) {
u = get(u), v = get(v);
if (u != v) {
if (rank[u] < rank[v]) {
swap(u, v);
}
rank[u] += rank[v];
parent[v] = u;
min_val[u] = min(min_val[u], min_val[v]);
}
}
};
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int N, K;
cin >> N >> K;
vector<int> A(N);
for (int &value : A) {
cin >> value;
}
vector<int> stleft(N), stright(N);
for (int i = 0; i < N; i++) {
stleft[i] = i - 1;
while (stleft[i] != -1 && A[stleft[i]] < A[i]) {
stleft[i] = stleft[stleft[i]];
}
}
for (int i = N - 1; i >= 0; i--) {
stright[i] = i + 1;
while (stright[i] != N && A[stright[i]] <= A[i]) {
stright[i] = stright[stright[i]];
}
}
vector<long long> dp(N + 1, INF), new_dp;
dp[0] = 0;
for (int k = 0; k < K; k++) {
new_dp.assign(N + 1, INF);
stack<int> st;
dsu sets(N);
sets.min_val = dp;
for (int i = 0; i <= N; i++) {
while (!st.empty() && dp[st.top()] > dp[i]) {
sets.unite(st.top(), i);
st.pop();
}
long long val = sets.min_val[sets.get(stleft[i] + 1)] + A[i];
new_dp[stright[i]] = val;
st.push(i);
}
for (int i = N; i > 0; i--) {
new_dp[i - 1] = min(new_dp[i - 1], new_dp[i]);
}
dp = new_dp;
}
cout << dp.back() << "\n";
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
344 KB |
Output is correct |
2 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
348 KB |
Output is correct |
2 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
344 KB |
Output is correct |
2 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
344 KB |
Output is correct |
2 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |