HDU 3045 Picnic Cows (斜率优化DP)

思路:设dp[i]为考虑前i个cows的最小值。s[i] 为从第1个到第i个的moos和。

那么方程为dp[i] = min(dp[i],dp[j] + s[i] - s[j] - (i - j)*a[j+1])。

然后斜率优化将复杂度降为O(n)。


这个题!!!一定要注意初值!!!一定要注意状态从什么地方开始转移!!!以后的所有DP题也是!!!


我的代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>

using namespace std;
typedef long long LL;
const int maxn = 400005;

LL n,t,k,a[maxn],dp[maxn],s[maxn];
LL q[maxn],hd,tl;

void init(){
    s[0] = a[0] = 0;
}

LL getDP(LL j,LL k){
    return dp[k] + s[j] - s[k] - (j - k)*a[k+1];
}
LL getUp(LL j,LL k){
    return (dp[k] - s[k] + k*a[k+1]) - (dp[j] - s[j] + j*a[j+1]);
}
LL getDown(LL j,LL k){
    return a[k+1] - a[j+1];
}

void solve(){
    LL i,j;
    hd = tl = 0;
    q[tl++] = t;
    for(j=t;j<2*t;j++) dp[j] = s[j] - j*a[1];
    for(j=2*t;j<=n;j++){
        while(hd+1<tl && (getUp(q[hd],q[hd+1])
            <= j*getDown(q[hd],q[hd+1]))) hd++;
        dp[j] = getDP(j,q[hd]);
        //cout<<getUp(q[tl-1],j-t+1)<<" "<<getUp(q[tl-2],q[tl-1])<<endl;
        while(hd+1<tl && getUp(q[tl-1],j-t+1)*getDown(q[tl-2],q[tl-1])
                <= getUp(q[tl-2],q[tl-1])*getDown(q[tl-1],j-t+1)) tl--;
        q[tl++] = j-t+1;
        //cout<<j<<" "<<q[hd]<<" "<<q[tl-1]<<" "<<dp[j]<<endl;
    }
    printf("%I64d\n",dp[n]);
}

int main(){
    while(~scanf("%I64d%I64d",&n,&t)){
        k = n / t;
        init();
        LL i;
        for(i=1;i<=n;i++) scanf("%I64d",&a[i]);
        sort(a+1,a+n+1);
        for(i=1;i<=n;i++) s[i] = s[i-1] + a[i];
        solve();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值