Description
有个物品,每个物品长度为
,现在要把这
个物品划分成若干组,每组中的物品编号是连续的,规定每组的长度
,费用为
,求最小费用.
Input
第一行输入两个整数和
,接下来
行输入
.
Output
一行表示最小费用.
Sample Input
5 4
3
4
2
1
4
Sample Output
1
HINT
Solution
表示将前
个物品分组所需最小费用.
会
,考虑斜率优化.
当且
时,
尽量将分离,设
,得
的前提是
整理得
设
则
(若存在,因为
单调递增,所以
一定比
优,即
可以删去)
所以每次取元素时,将满足的
出队(因为
比
优),然后取队首为
.
#include<set>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<cstdio>
#include<vector>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define N 50001
using namespace std;
typedef long long ll;
ll f[N],s[N],q[N],h,t,l,n;
inline ll sqr(ll k){
return k*k;
}
inline ll x(ll k){
return k+s[k];
}
inline ll y(ll k){
return f[k]+sqr(x(k));
}
inline double cmp(ll p,ll q){
return (double)(y(q)-y(p))/(double)(x(q)-x(p));
}
inline ll g(ll k){
return k+s[k]-l;
}
inline void init(){
scanf("%lld%lld",&n,&l);
for(ll i=1;i<=n;i++){
scanf("%lld",&s[i]);
s[i]+=s[i-1];
}
for(ll i=1,k;i<=n;i++){
k=g(i)<<1;
while(h<t&&cmp(q[h],q[h+1])<k) h++;
f[i]=f[q[h]]+sqr(x(q[h])-g(i)+1);
while(h<t&&cmp(q[t],i)<cmp(q[t-1],q[t]))
t--;
q[++t]=i;
}
printf("%lld\n",f[n]);
}
int main(){
freopen("toy.in","r",stdin);
freopen("toy.out","w",stdout);
init();
fclose(stdin);
fclose(stdout);
return 0;
}