HNOI2008玩具装箱

时间:2023-03-08 16:30:09

斜率优化

# include <stdio.h>
# include <stdlib.h>
# include <iostream>
# include <string.h>
# include <algorithm>
# define Sqr(x) (1LL * (x) * (x))
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll; IL ll Read(){
RG char c = getchar(); RG ll x = 0, z = 1;
for(; c > '9' || c < '0'; c = getchar()) z = c == '-' ? -1 : 1;;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + c - '0';
return x * z;
} const int MAXN(50010);
int n, L, Q[MAXN], head, tail;
ll f[MAXN], sum[MAXN], INF, b[MAXN], a[MAXN]; IL double K(RG int i, RG int j){
RG ll y1 = Sqr(b[i]) + f[i], y2 = Sqr(b[j]) + f[j], x1 = 2 * b[i], x2 = 2 * b[j];
return 1.0 * (y2 - y1) / (x2 - x1);
} int main(){
n = Read(); L = Read();
for(RG int i = 1; i <= n; i++){
sum[i] = sum[i - 1] + Read();
b[i] = sum[i] + i; a[i] = b[i] - L - 1;
}
Fill(f, 127); INF = f[0]; f[0] = Q[0] = 0;
for(RG int i = 1; i <= n; i++){
while(head < tail && K(Q[head], Q[head + 1]) <= a[i]) head++;
RG int j = Q[head];
f[i] = f[j] + Sqr(a[i] - b[j]);
while(head < tail && K(Q[tail - 1], Q[tail]) >= K(Q[tail], i)) tail--;
Q[++tail] = i;
}
printf("%lld\n", f[n]);
return 0;
}