fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. typedef pair<ll,ll> pll;
  5. const int maxN = 3005;
  6. struct Line {
  7. ll m, b, c;
  8. ll operator()(ll x){
  9. return m * x + b;
  10. }
  11. };
  12. struct CHT {
  13. Line dq[2*maxN];
  14. int fptr, bptr;
  15. void clear(){
  16. dq[0] = {0, 0, 0};
  17. fptr = 0; bptr = 1;
  18. }
  19.  
  20. bool pop_back(Line& L, Line& L1, Line& L2){
  21. ll v1 = (L.b - L2.b) * (L2.m - L1.m);
  22. ll v2 = (L2.m - L.m) * (L1.b - L2.b);
  23. return (v1 == v2 ? L.c > L1.c : v1 < v2);
  24. }
  25.  
  26. bool pop_front(Line& L1, Line& L2, ll x){
  27. ll v1 = L1(x);
  28. ll v2 = L2(x);
  29. return (v1 == v2 ? L1.c < L2.c : v1 > v2);
  30. }
  31.  
  32. void insert(Line L){
  33. while(bptr-fptr >= 2 && pop_back(L, dq[bptr-1], dq[bptr-2])) bptr--;
  34. dq[bptr++] = L;
  35. }
  36.  
  37. pll query(ll x){
  38. while(bptr-fptr >= 2 && pop_front(dq[fptr], dq[fptr+1], x)) fptr++;
  39. return {dq[fptr](x), dq[fptr].c};
  40. }
  41. };
  42.  
  43. CHT cht;
  44. int N, K, cnt[maxN];
  45. ll pre[maxN], dp[maxN];
  46.  
  47. int main(){
  48. scanf("%d %d", &N, &K);
  49. for(int i = 1; i <= N; i++){
  50. scanf("%lld", &pre[i]);
  51. pre[i] += pre[i-1];
  52. dp[i] = pre[i]*pre[i];
  53. }
  54. for(int k = 1; k <= K-1; k++){
  55. cht.clear();
  56. for(int i = 1; i <= k; i++)
  57. cht.insert({-2*pre[i], dp[i]+pre[i]*pre[i], cnt[i]});
  58. for(int i = k+1; i <= N; i++){
  59. pll P = cht.query(pre[i]);
  60. cht.insert({-2*pre[i], dp[i]+pre[i]*pre[i], cnt[i]});
  61. dp[i] = pre[i]*pre[i] + P.first;
  62. cnt[i] = P.second + 1;
  63. }
  64. }
  65.  
  66. printf("%lld\n", dp[N]);
  67. }
  68.  
Success #stdin #stdout 0.01s 5216KB
stdin
Standard input is empty
stdout
0