1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include<bits/stdc++.h>
using namespace std; #define ll long long const int maxn = 5e4; long long Q[maxn], dp[maxn], s[maxn];
long long f(int j) { return dp[j] + (j + s[j]) * (j + s[j]); }
double Slope(long long j, long long k) { return double(f(k) - f(j)) / (k + s[k] - j - s[j]); }
int main() { ll n, L; while (~scanf("%lld%lld", &n, &L)) { for (int i = 1; i <= n; i++) { int tmp; scanf("%d", &tmp); s[i] = s[i - 1] + tmp; }
int Left = 1, Right = 1; Q[1] = 0; dp[0] = 0; for (int i = 1; i <= n; i++) { while (Left < Right && Slope(Q[Left], Q[Left + 1]) <= 2 * (s[i] + i - L - 1)) Left++; int j = Q[Left]; dp[i] = dp[j] + (i - j - 1 + s[i] - s[j] - L) * (i - j - 1 + s[i] - s[j] - L); while (Left < Right && Slope(Q[Right - 1], Q[Right]) >= Slope(Q[Right], i)) Right--; Q[++Right] = i; } printf("%lld\n", dp[n]); } return 0; }
|