【斜率优化dp】bzoj 1597 土地购买

最近学习斜率优化!然而其实并不明白斜率是如何操作的……还好有小天使带我❤~而且斜率优化好像是有模板的样子,很多题都可以套用模板。
基本的dp方程:
dp[i]=min(dp[j]+land.x[i]*land.y[j+1]);

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct Node {
    double x, y;
}land[50005], temp[50005];
long long dp[50005];
int queue[50005], n, head = 0, tail = 1, num = 0;
bool cmp(const Node &a, const Node &b) {
    return a.x > b.x;
}
double getx(int k, int j) {
    return dp[k] - dp[j];
}
double gety(int k, int j) {
    return land[j + 1].x - land[k + 1].x;
}
int main() { 
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
        scanf("%lf%lf", &temp[i].x, &temp[i].y);
    sort(temp + 1, temp + n + 1, cmp);
    land[1].y = -1.0;
    for(int i = 1; i <= n; i++)
        if(temp[i].y > land[num].y) {
            num++;
            land[num].x = temp[i].x;
            land[num].y = temp[i].y;
        }
    for(int i = 1; i <= num; i++) {
        while(head + 1 < tail && getx(queue[head + 1], queue[head]) <= land[i].y * gety(queue[head + 1], queue[head]))
            head++;
        dp[i] = dp[queue[head]] + land[i].y * land[queue[head] + 1].x;
        while(head + 1 < tail && getx(i, queue[tail - 1])*gety(queue[tail - 1], queue[tail - 2]) <= getx(queue[tail - 1], queue[tail - 2]) * gety(i, queue[tail - 1]))
            tail--;
        queue[tail++] = i;
    }
    printf("%lld\n", dp[num]);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值