This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/* Problem URL: https://oj.uz/problem/view/APIO14_sequence
Tags: dp, convex hull optimization */
#include <iostream>
#include <vector>
#include <deque>
#include <stack>
using namespace std;
const int N = 100005;
long long a[N];
struct Line {
long long a, b;
int idx;
long long GetCost(long long x) {
return a * (x - a) + b;
}
};
bool Check(Line& l1, Line& l2, Line& l3) {
return 1.0 * (l3.b - l1.b) * (l1.a - l2.a) < 1.0 * (l2.b - l1.b) * (l1.a - l3.a);
}
int main() {
int n, k;
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<long long> sums(n + 1);
for (int i = 0; i < n; i++) {
sums[i + 1] = sums[i] + a[i];
}
vector<long long> dp1(n + 1);
vector<long long> dp2(n + 1);
vector<vector<int>> splits(k, vector<int>(n + 1));
for (int i = 0; i < k; i++) {
deque<Line> lines;
for (int j = 0; j <= n; j++) {
while (lines.size() > 1 && lines[0].GetCost(sums[j]) <= lines[1].GetCost(sums[j])) {
lines.pop_front();
}
if (!lines.empty()) {
dp2[j] = lines[0].GetCost(sums[j]);
splits[i][j] = lines[0].idx;
}
Line l({sums[j], dp1[j], j});
while (lines.size() > 1 && Check(lines[0], lines[1], l)) {
lines.pop_back();
}
lines.push_back(l);
}
dp1 = dp2;
}
cout << dp2[n] << endl;
stack<int> st;
for (int i = k - 1, j = n; i >= 0; i--) {
j = splits[i][j];
st.push(j);
}
while (!st.empty()) {
cout << st.top() << ' ';
st.pop();
}
}
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |