HDU4258_Covered Walkway【单调队列优化DP】

参考文章:http://www.cnblogs.com/Canon-CSU/p/3425801.html

题意:一些数字,要用区间覆盖他们,,诶个区间的花费是c*(x-y),求最小总花费

分析:开始一直没有想DP,只是想从每一段区间的左右端点数值只差的平方要小于C,各种水然后各种WA。。看过题解后,发现思路也不难想。

   对于某个数a[i]来说其最小花费就是f[i]=min(f[j]+(a[i]-a[j+1])^2)。并且可以推出①对于一个y>x若是y优于x则

           2*a[i]*(a[y + 1] - a[x + 1]) >= f[y] - f[x] + 1ll * a[y + 1] * a[y + 1] - 1ll * a[x + 1] * a[x + 1]

           并且②令左边为L,右边为R,有R/L越小则y越优于x,根据这样的结论,这题就可以用一个双端队列,通过对队首利用①,队尾利用②维护队列的单调性。

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<vector>
#include<cstring>
#define N 1000005
#define inf 0xfffffff
using namespace std;
typedef __int64 ll;
int q[N], a[N];
ll f[N];

ll getL(int x, int y){
    return (a[y + 1] - a[x + 1]);
}

ll getR(int x, int y){
    return f[y] - f[x] + 1ll * a[y + 1] * a[y + 1] - 1ll * a[x + 1] * a[x + 1];
}

int main(){
    int n, c;
    while(scanf("%d%d", &n, &c) && (n || c)){
        int head = 1, tail = 1;q[1] = 0;
        for(int i = 1;i <= n;i ++){
            scanf("%d", &a[i]);
        }
        for(int i = 1;i <= n;i ++){
            while(head < tail){
                if(2ll * a[i] * getL(q[head], q[head + 1]) >= getR(q[head], q[head + 1]))head ++;
                else break;
            }
            f[i] = f[q[head]] + 1ll * (a[i] - a[q[head] + 1]) * (a[i] - a[q[head] + 1]) + c;
            while(head < tail){
                ll x = getL(q[tail], i) * getR(q[tail - 1], q[tail]);
                ll y = getL(q[tail - 1], q[tail]) * getR(q[tail], i);
                if(x >= y)tail --;
                else break;
            }
            q[++ tail] = i;
        }
        printf("%I64d\n", f[n]);
    }
    return 0;
}<strong>
</strong>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值