题目描述:传送门
题解:
斜率优化DP。
f[i]=f[j]+(i-j)*(i-j-1)/2+a[i] <=>
2*f[i]+2*i*j=2*f[j]+j2+j+(2*a[i]+i2-i)
b + ax = y
代码如下:
#include<cstdio>
#include<string>
using namespace std;
const int maxn=1000005;
int n,a[maxn],que[maxn];
long long f[maxn];
inline int read(){
int x=0; char ch=getchar();
while (ch<'0'||ch>'9') ch=getchar();
while (ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
return x;
}
double X(int x) {return 1.0*x;}
double Y(int x) {return 2.0*f[x]+1.0*x*x+x;}
double xl(int x,int y) {return (Y(x)-Y(y))/(X(x)-X(y));}
int main(){
n=read();
for (int i=1;i<=n;i++) a[i]=read();
int head=0,tail=0;
for (int i=1;i<=n;i++) {
while (head<tail&&xl(que[head],que[head+1])<2*i) head++;
f[i]=f[que[head]]+1.0*(i-que[head])*(i-que[head]-1)/2+a[i];
while (head<tail&&xl(que[tail-1],que[tail])>xl(que[tail],i)) tail--;
que[++tail]=i;
}
printf("%lld\n",f[n]);
return 0;
}