【牛客网】KY155 To Fill or Not to Fill

在这里插入图片描述
这是一道贪心算法的题目,因为题目要求花费最低,所以我想到区间贪心的思想,那么首先要将各个加油站的费用从小到大排序,然后根据汽车最多能走的距离计算所需要的花费,再将这些区间的花费加起来即可:

#include<iostream>
#include<algorithm>

using namespace std;

const int MAXDIS = 30000 + 10;
const int MAXN = 500 + 10;

struct Station{
    double price;
    double distance;
    Station(){}
    Station(double p, double d): price(p), distance(d){}
};
Station arr[MAXN];
int d[MAXDIS];

bool cmp(Station x, Station y){
    return x.price <= y.price;
}

int main(){
    int Cmax, D, Davg, n;
    while(scanf("%d%d%d%d", &Cmax, &D, &Davg, &n) != EOF){
        for(int i = 0;i < n;i++) scanf("%lf %lf", &arr[i].price, &arr[i].distance);
        sort(arr, arr + n, cmp);
        fill(d, d + D, 0);
        int max = Cmax * Davg;  //加满油能走的最远距离
        double total = 0.0;  //记录总花费
        for(int i = 0;i < n;i++){
            int sum = 0;
            int bound;
            if(arr[i].distance + max > D) bound = D;
            else bound = arr[i].distance + max;
            for(int j = arr[i].distance;j < bound;j++){
                if(!d[j]){
                    d[j] = 1;
                    sum++;
                }
            }
            total += sum * arr[i].price / Davg;
        }
        int i;
        for(i = 0;i <= D;i++){
            if(!d[i]) break;
        }
        if(i < D) printf("The maximum travel distance = %.2lf\n", double(i));
        else printf("%.2lf\n", total);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花无凋零之时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值