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>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
#define all(v) v.begin(), v.end()
#define pb push_back
#define ss second
#define ff first
#define vt vector
using namespace std;
//using namespace __gnu_pbds;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<double, int> pdi;
const ll inf = 1e18;
const int mod = 1e9+7;
const int maxn = 3e3 + 1;
void solve() {
int n, k;
cin >> n >> k;
int a[n + 1], p[n + 1];
ll dp[n + 1][k + 2], from[n + 1][k + 2];
p[0] = 0;
for(int i = 1; i <= n; i++){
cin >> a[i];
p[i] = a[i] + p[i - 1];
}
for(int i = 1; i <= n; i++){
dp[i][1] = (p[n] - p[i]) * p[i];
}
dp[0][1] = 0;
for(int t = 2; t <= k + 1; t++){
dp[0][t] = 0;
deque<pair<pll, pll>> dq;
dq.push_back({{dp[t - 1][t - 1], p[t - 1]}, {0, t - 1}});
from[t - 1][t] = t - 2;
for(int i = 0; i < t; i++)dp[i][t] = -inf;
for(int i = t; i <= n; i++){
while(!dq.empty() && dq.back().ss.ff > p[n] - p[i])dq.pop_back();
dp[i][t] = dq.back().ff.ff + (p[n] - p[i]) * p[i] - (dq.back().ff.ss * (p[n] - p[i]));
from[i][t] = dq.back().ss.ss;
ll x = dp[i][t - 1], y = p[i];
while(!dq.empty()){
pll nw = dq.front().ff;
ll it = dq.front().ss.ss;
dq.pop_front();
if(y == nw.ss)continue;
ll z = (x - nw.ff) / (y - nw.ss);
if(dq.empty() || z < dq.front().ss.ff){
dq.push_front({nw, {z, it}});
break;
}
}
dq.push_front({{x, y}, {0, i}});
}
}
cout << dp[n][k + 1] << '\n';
int x = n;
while(k > 0){
cout << from[x][k + 1] << ' ';
x = from[x][k + 1];
k--;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int times = 1;
//cin >> times;
for(int i = 1; i <= times; i++) {
solve();
}
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... |