This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#pragma GCC optimize("O3")
#pragma GCC target("avx2")
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
struct dsu {
vector<int> parent, rank;
vector<int> 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<int> 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;
multiset<int> S;
vector<vector<int>> events(N + 1);
for (int i = 0; i <= N; i++) {
for (auto val : events[i]) {
S.erase(S.find(val));
}
new_dp[i] = S.empty() ? INF : *S.begin();
if (i == N) {
continue;
}
while (!st.empty() && dp[st.top()] > dp[i]) {
sets.unite(st.top(), i);
st.pop();
}
int val = sets.min_val[sets.get(stleft[i] + 1)] + A[i];
S.insert(val);
if (stright[i] < N) {
events[stright[i] + 1].push_back(val);
}
st.push(i);
}
dp = new_dp;
}
cout << dp.back() << "\n";
}
# | 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... |