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>
#define x first
#define y second
#define pb push_back
#define all(a) (a).begin(), (a).end()
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
const int maxn = 1e5 + 5;
const double inf = 1e18, eps = 1e-9;
struct line {double a, b, p, idx;};
int n, k;
int A[maxn];
double pref[maxn];
double dp[maxn], dp1[maxn];
int opt[maxn][205];
vector<line> lines;
double getX(double a1, double b1, double a2, double b2) {
return (b1 - b2) / (a2 - a1);
}
void addLine(double a, double b, double idx) {
double p = -inf;
while(lines.size()) {
p = getX(a, b, lines.back().a, lines.back().b);
if(p < lines.back().p) lines.pop_back();
else break;
}
lines.pb({a, b, p, idx});
}
pair<double, int> getAns(double x) {
int lo = 0, hi = (int)lines.size() - 1, ans = 0;
while(lo <= hi) {
int mid = (lo + hi) / 2;
if(lines[mid].p <= x) ans = mid, lo = mid + 1;
else hi = mid - 1;
}
return {lines[ans].a * x + lines[ans].b, (int)lines[ans].idx};
}
int main() {
scanf("%d%d", &n, &k);
for(int i = 0;i < n;i++) scanf("%d", A + i);
pref[0] = A[0];
for(int i = 1;i < n;i++) pref[i] = pref[i - 1] + A[i];
double ans = 0;
for(int i = 1;i < k + 1;i++) {
addLine(pref[i - 1], dp[i - 1] - pref[i - 1] * pref[i - 1], i - 1);
for(int j = i;j < n;j++) {
pair<double, int> p = getAns(pref[j]);
dp1[j] = p.x;
opt[j][i] = p.y;
addLine(pref[j], dp[j] - pref[j] * pref[j], j);
}
for(int j = i;j < n;j++) dp[j] = dp1[j];
ans = dp[n - 1];
lines.clear();
}
printf("%lld\n", (ll)ans);
int pos = n - 1;
for(int i = k;i >= 1;i--)
printf("%d ", opt[pos][i] + 1), pos = opt[pos][i];
return 0;
}
Compilation message (stderr)
sequence.cpp: In function 'int main()':
sequence.cpp:50:7: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
50 | scanf("%d%d", &n, &k);
| ~~~~~^~~~~~~~~~~~~~~~
sequence.cpp:51:32: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
51 | for(int i = 0;i < n;i++) scanf("%d", A + i);
| ~~~~~^~~~~~~~~~~~~
# | 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... |