# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
767538 | jeroenodb | Split the sequence (APIO14_sequence) | C++14 | 0 ms | 0 KiB |
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>
using namespace std;
#define int long long
#define INF (int)1e18
#define double long double
#define f first
#define s second
mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
struct line{
int m, c, i;
};
int eval(int x, line a){
return a.m * x + a.c;
}
//(c2 - c1) / (m1 - m2)
bool useless(line a, line b, line c){
// return intersect(a, c) >= intersect(b, c);
return (a.c - c.c) * (c.m - b.m) <= (b.c - c.c) * (c.m - a.m);
}
void Solve()
{
int n, k; cin >> n >> k;
vector <int> a(n + 1);
int sum = 0;
for (int i = 1; i <= n; i++){
cin >> a[i];
sum += a[i];
a[i] += a[i - 1];
}
k++;
// vector<vector<int>> dp(n + 1, vector<int>(k + 1, INF));
vector<vector<int32_t>> par(n + 1, vector<int32_t>(k + 1, -1));
deque<line> dq[k + 2];
# dp[0][0] = 0;
line ok;
ok.m = 0; ok.c = 0; ok.i = 0;
dq[0].push_back(ok);
//dp[i][j] = dp[i1][j - 1] + a[i1] ^ 2 - 2 * a[i1] * a[i] + a[i] ^ 2
for (int i = 1; i <= n; i++){
for (int j = k; j >= 1; j--){
// for (int i1 = 0; i1 < i; i1++){
// int val = dp[i1][j - 1] + (a[i] - a[i1]) * (a[i] - a[i1]);
// if (val < dp[i][j]){
// dp[i][j] = val;
// par[i][j] = i1;
// }
// }
if (dq[j - 1].size() == 0) continue;
int x = a[i];
while (dq[j - 1].size() > 1 && eval(x, dq[j - 1][0]) >= eval(x, dq[j - 1][1])) dq[j - 1].pop_front();
auto curdup = eval(x, dq[j - 1][0]) + a[i] * a[i];
par[i][j] = dq[j - 1][0].i;
ok.m = - 2 * a[i];
ok.c = curdp + a[i] * a[i];
ok.i = i;
while (dq[j].size() > 1 && useless(ok, dq[j].back(), dq[j][dq[j].size() - 2])) dq[j].pop_back();
dq[j].push_back(ok);
}
}
int ans = (sum * sum) - (dp[n][k]);
ans /= 2;
cout << ans << "\n";
vector <int> go;
int i = n;
while (par[i][k] != 0){
i = par[i][k];
k--;
go.push_back(i);
}
reverse(go.begin(), go.end());
for (auto x : go) cout << x << " ";
cout << "\n";
}
int32_t main()
{
auto begin = std::chrono::high_resolution_clock::now();
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
// cin >> t;
for(int i = 1; i <= t; i++)
{
//cout << "Case #" << i << ": ";
Solve();
}
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
cerr << "Time measured: " << elapsed.count() * 1e-9 << " seconds.\n";
return 0;
}