斜率优化dp求助!!!
查看原帖
斜率优化dp求助!!!
544279
wh__楼主2024/7/25 10:23

式子仔细推的,是上凸包没问题啊qwq 10pts。。。

#include<bits/stdc++.h>
typedef long long LL;
typedef long double LD;
using namespace std;
const int SIZE=1e6+10;
LL n,a,b,c;
LL P[SIZE],dp[SIZE];
LL q[SIZE],head=1,tail=0;
LL read()
{
    LL x=1,res=0;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')x=-1;ch=getchar();}
    while(isdigit(ch)){res=(res<<3)+(res<<1)+(ch^48);ch=getchar();}
    return x*res;
}
LL X(LL u){return P[u];}
LL Y(LL u){return (dp[u]+a*P[u]*P[u]-b*P[u]);}
LD slope(LL j1,LL j2){return (LD)(Y(j2)-Y(j1))/(LD)(X(j2)-X(j1));}
signed main()
{
    // freopen("data.in","r",stdin);
    // freopen("1.out","w",stdout);
    n=read(),a=read(),b=read(),c=read();
    for(int i=1;i<=n;i++)
    {
        LL x=read();
        P[i]=P[i-1]+x;
    }
    q[++tail]=0;
    for(int i=1;i<=n;i++)
    {
        while(head<tail && slope(head,head+1)<=2*a*P[i]) head++;
        LL j=q[head];
        LL X=P[i]-P[j];
        dp[i]=dp[j]+a*X*X+b*X+c;
        // printf("dp[%lld]=%lld\n",i,dp[i]);
        while(head<tail && slope(tail-1,tail)>=slope(tail-1,i)) tail--;
        q[++tail]=i;
    }
    printf("%lld",dp[n]);
    return 0;
}
2024/7/25 10:23
加载中...