【bzoj 1911】【Apio2010】特别行动队 dp+单调队列斜率优化

1911: [Apio2010]特别行动队

Time Limit: 4 Sec Memory Limit: 64 MB
Submit: 3263 Solved: 1477
[Submit][Status][Discuss]
Description

Input

Output

Sample Input

4

-1 10 -20

2 2 3 4
Sample Output

9
HINT

思路:
1。s[i]–》前缀和,dp[i]代表到第i个的最优解;
2.对于方程:dp[i]=max{dp[j]+a*(s[i]-s[j])(s[i]-s[j])+b(s[i]s[j])+c}
  

!!!   证 j2>j1时若决策 j 比 k 更优:                                   
dp[j2]+a∗(s[i]−s[j2])^2+b∗(s[i]−s[j2])+c
>dp[j1]+a∗(s[i]−s[j1])^2−b∗(s[j]−s[j1])

即f[j2]-f[j1]+a*(s[j2]s[j2]-s[j1]*s[j1])+b(s[j2]-s[j1]))/(2*a*(s[j2]-s[j1]))>s[i]时可维护队列的单调性;

#include<iostream>
#include<stdio.h>
#define LL long long 
using namespace std;
int n,a,b,c;
int aa;
LL s[1000005];
LL f[1000005];
int q[1000005];
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(2*a*(s[j]-s[k]));
 }
int main()
{
    scanf("%d%d%d%d",&n,&a,&b,&c);
    for(int i=1;i<=n;i++)           scanf("%d",&aa),s[i]=s[i-1]+aa, f[i]=a*(s[i]*s[i])+b*s[i]+c;
    int l=0,r=0;
    for(int i=1;i<=n;i++)
    {
        while(l<r&&slop(q[l],q[l+1])<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-1],q[r])>slop(q[r],i))r--;
        q[++r]=i;
    }   
    printf("%lld",f[n]);     
}

你可能感兴趣的:(dp)