DP/斜率优化
嗯……第三道斜率优化的题目了。
定义 $s[i]=\sum_{k=1}^{i} x[k] $
方程:$f[i]=max\{ f[j]+a*(s[i]-s[j])^2+b*(s[i]-s[j])+c \} $
对于 $ j > k $
若决策 j 比 k 更优:\[ \begin{aligned} {f[j] + a*(s[i]-s[j])^2+b*(s[i]-s[j])+c} &> {f[k]+a*(s[i]-s[k])^2+b*(s[i]-s[k])+c} \\ {f[j]-f[k]+a*(s[j]^2-s[k]^2)-b*(s[j]-s[k])} &> {2a*s[i]*(s[j]-s[k])} \\ \frac{ f[j]-f[k]+a*(s[j]^2-s[k]^2)-b*(s[j]-s[k]) } { 2a*(s[k]-s[j]) } &> {s[i]} \end{aligned} \]
/**************************************************************
Problem: 1911
User: Tunix
Language: C++
Result: Accepted
Time:1260 ms
Memory:28616 kb
****************************************************************/ //BZOJ 1911
#include<cmath>
#include<vector>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define rep(i,n) for(int i=0;i<n;++i)
#define F(i,j,n) for(int i=j;i<=n;++i)
#define D(i,j,n) for(int i=j;i>=n;--i)
#define pb push_back
using namespace std;
int getint(){
int v=,sign=; char ch=getchar();
while(ch<''||ch>''){ if (ch=='-') sign=-; ch=getchar();}
while(ch>=''&&ch<=''){ v=v*+ch-''; ch=getchar();}
return v*=sign;
}
const int N=1e6+;
typedef long long LL;
/******************tamplate*********************/
LL f[N],x[N],s[N];
int q[N],a,b,c;
double slop(int k,int j){
return double(f[j]-f[k]+a*(s[j]*s[j]-s[k]*s[k])+b*(s[k]-s[j]))/
double(*a*(s[j]-s[k]));
}
int main(){
#ifndef ONLINE_JUDGE
freopen("1911.in","r",stdin);
freopen("1911.out","w",stdout);
#endif
int n=getint();
a=getint(),b=getint(),c=getint();
F(i,,n){ x[i]=getint(); s[i]=s[i-]+x[i];}
int l=,r=;
F(i,,n){
while(l<r && slop(q[l],q[l+])<s[i])l++;
int t=q[l];
f[i]=f[t]+a*((s[i]-s[t])*(s[i]-s[t]))+b*(s[i]-s[t])+c;
while(l<r && slop(q[r-],q[r])>slop(q[r],i))r--;
q[++r]=i;
}
printf("%lld\n",f[n]);
return ;
}
1911: [Apio2010]特别行动队
Time Limit: 4 Sec Memory Limit: 64 MB
Submit: 3036 Solved: 1367
[Submit][Status][Discuss]
Description
Input
Output
Sample Input
4
-1 10 -20
2 2 3 4
-1 10 -20
2 2 3 4
Sample Output
9