斜率优化板题求调
查看原帖
斜率优化板题求调
177000
vicky2048_2楼主2023/9/26 20:39

rt

感觉自己写得很对,但连样例都过不了,一点都不牛

#include<bits/stdc++.h>
#define int long long
#define N 50005
using namespace std;
int n,l,a[N],sum[N],dp[N],en,st=1,cal(int,int);
void push(int),pop(int);
bool com(int,int,int);
struct node{
    int bh,x,y;
}que[N];
signed main(){
    scanf("%lld%lld",&n,&l);
    for(int i=1;i<=n;++i)
        scanf("%lld",&a[i]),sum[i]=sum[i-1]+a[i];
    dp[1]=(a[1]-l)*(a[1]-l);
    push(1);
    for(int i=2;i<=n;++i){
        pop(i);
        dp[i]=cal(que[st].bh,i);
        push(i);
    }
    printf("%lld",dp[n]);
    return 0;
}
void push(int no){
    que[N-1].x=sum[no],que[N-1].y=dp[no]+sum[no]*sum[no]+2*sum[no]*(l+1),que[N-1].bh=no;
    while(st<en&&com(en-1,en,N-1))
        --en;
    que[++en]=que[N-1];
}
bool com(int a,int b,int c){//k1>k2
    return (que[b].y-que[a].y)*(que[c].x-que[b].x)>(que[c].y-que[b].y)*(que[b].x-que[a].x);
}
void pop(int no){
    while(st<en&&cal(que[st].bh,no)>cal(que[st+1].bh,no))
        ++st;
}
int cal(int j,int i){
    return dp[j]+(dp[i]+sum[i]-dp[j]-sum[j]-(l+1))*(dp[i]+sum[i]-dp[j]-sum[j]-(l+1));
}
2023/9/26 20:39
加载中...