sum[i]=∑ij=0c[j]
d[i]=min{d[j]+M+(sum[i]−sum[j])2 | j<i }
若d[a]+M+(sum[i]−sum[a])2<d[b]+M+(sum[i]−sum[b])2
d[a]+sum[a]2−(d[b]+sum[b]2)<2sum[i]∗(sum[a]−sum[b])
令y[j]=d[j]+sum[j]2,x[j]=2sum[j]
令g[a][b]=y[a]−y[b]x[a]−x[b]
则若a比b更优(选择a点值比b点更小)−>g[a][b]<sum[i]
在选择d[i]=min{d[j]+M+(sum[i]−sum[j])2 | j<i }中的j时
考虑维护一个g[a][b]单调队列
假如当前可选的答案队列中有j1,j2,j3,...(j1<j2<j3)可选,若g[j2][j1]<sum[i],则j2点必然优于j1,而且sum[k]>=sum[i] (k>i),a点可以丢弃了,不可能再成为答案
一直按照次策略删除,则直到g[j2][j1]>sum[i]时,j1为当前队列中最优的解
假如将i放进答案队列中,若g[i][jm]<g[jm][jm−1]
若g[i][jm]<sum[i],i优于jm,且sum[k]>=sum[i] (k>i),i优于jm
若g[i][jm]>=sum[i],g[jm][jm−1]>g[i][jm]>=sum[i],此时jm−1优于jm
所以,当g[i][jm]<g[jm][jm−1]时,jm不再可能成为答案,删去
不断地删,直到g[i][jm]>g[jm][jm−1]时,将i放入队列尾部即可
每个点只会进出队列一次,复杂度O(n)
//hdu3507
#include<stdio.h>
#include<bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define MEM(a,x) memset(a,x,sizeof(a))
#define lowbit(x) ((x)&-(x))
using namespace std;
const int inf = 1e9+7;
const int N = 500000 + 50;
int sum[N],d[N];
//[ Y(k)-Y(j) ] / [ X(k)-X(j) ] < Val(i)
int Y(int i){//分子
return d[i]+sum[i]*sum[i];
}
int X(int i){//分母
return 2*sum[i];
}
int Val(int i){
return sum[i];
}
bool judge(int a,int b,int i){//b优于a? g[b][a]<val[i]
return Y(b)-Y(a)<=Val(i)*(X(b)-X(a));
}
//g[d][c]=( Y(d)-Y(c) ) / ( X(d)-X(c) )
bool maintain(int a,int b,int c){//将c放入队列 需要删除b? return g[c][b]<=g[b][a]
return (Y(c)-Y(b))*(X(b)-X(a))<=(Y(b)-Y(a))*(X(c)-X(b));
}
int getDp(int j,int i,int val){
return d[j]+val+(sum[i]-sum[j])*(sum[i]-sum[j]);
}
int dp(int n,int m){
deque<int>que;
que.push_front(0);
for(int i=1;i<=n;++i){
while(que.size()>=2&&judge(que[0],que[1],i)){
que.pop_front();
}
d[i]=getDp(que[0],i,m);
while(que.size()>=2&&maintain(que[que.size()-2],que.back(),i)){
que.pop_back();
}
que.push_back(i);
}
return d[n];
}
int main(){
//freopen("/home/lu/code/r.txt","r",stdin);
//freopen("/home/lu/code/w.txt","w",stdout);
int n,m;
while(~scanf("%d%d",&n,&m)){
sum[0]=d[0]=0;
for(int i=1;i<=n;++i){
scanf("%d",&sum[i]);
sum[i]+=sum[i-1];
}
printf("%d\n",dp(n,m));
}
return 0;
}