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);
}
int32_t par[(int)(1e5 + 1)][202];
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++;
deque<line> dq[k + 2];
line ok;
ok.m = 0; ok.c = 0; ok.i = 0;
dq[0].push_back(ok);
int holy = 0;
//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();
int dp = 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 = dp + 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);
if (i == n && j == k) holy = dp;
}
}
int ans = (sum * sum) - (holy);
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;
}
# | 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... |