fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. typedef long long ll;
  4.  
  5. using namespace std;
  6.  
  7. struct Line {
  8. mutable ll k, m, p;
  9. bool operator<(const Line& o) const { return k < o.k; }
  10. bool operator<(ll x) const { return p < x; }
  11. };
  12.  
  13. struct HullDynamic : multiset<Line, less<>> {
  14. // (for doubles, use inf = 1/.0, div(a,b) = a/b)
  15. const ll inf = 2e18;
  16. ll div(ll a, ll b) { // floored division
  17. return a / b - ((a ^ b) < 0 && a % b); }
  18. bool isect(iterator x, iterator y) {
  19. if (y == end()) { x->p = inf; return false; }
  20. if (x->k == y->k) x->p = x->m > y->m ? inf : -inf;
  21. else x->p = div(y->m - x->m, x->k - y->k);
  22. return x->p >= y->p;
  23. }
  24. void add(ll k, ll m) {
  25. auto z = insert({k, m, 0}), y = z++, x = y;
  26. while (isect(y, z)) z = erase(z);
  27. if (x != begin() && isect(--x, y)) isect(x, y = erase(y));
  28. while ((y = x) != begin() && (--x)->p >= y->p)
  29. isect(x, erase(y));
  30. }
  31. ll query(ll x) {
  32. assert(!empty());
  33. auto l = *lower_bound(x);
  34. return l.k * x + l.m;
  35. }
  36. };
  37. const int N = 2e5 + 5;
  38. ll dp[N];
  39. ll n;
  40. int main() {
  41. ios_base::sync_with_stdio(false);
  42. cin.tie(NULL); cout.tie(NULL);
  43. cin>>n;
  44. vector<ll>a(n + 1);
  45. for(int i = 1;i<=n;i++) cin>>a[i];
  46. vector<ll>pref(n + 1,0ll);
  47. for(int i = 1;i<=n;i++) pref[i] = pref[i - 1] + a[i];
  48. vector<ll>c(n + 1, 0ll);
  49. for(ll i = 1ll; i<=n;i++) c[i] = c[i - 1] + (a[i]*i);
  50.  
  51. HullDynamic cht;
  52. dp[0] = 0ll;
  53. dp[1] = a[1];
  54. cht.add(0ll, 0ll);
  55.  
  56. for(ll i = 2;i<=n;i++){
  57. dp[i] = cht.query(pref[i]);
  58. dp[i] += c[i];
  59. cht.add(1ll - i, (i- 1ll)*pref[i- 1] - c[i-1]);
  60.  
  61. }
  62. ll ans = 0ll;
  63. for(int i = 0; i<=n;i++) ans = max(ans, dp[i]);
  64. cout<<ans<<'\n';
  65.  
  66.  
  67. }
Success #stdin #stdout 0s 5320KB
stdin
3
-60 -70 -80


stdout
0