PAT 1033. To Fill or Not to Fill

本文介绍了PAT编程竞赛中的一道题目1033,重点探讨了如何运用贪心算法解决此类问题。作者强调在实际考试中熟练掌握贪心算法的重要性,并分享了自己的解题思路。
摘要由CSDN通过智能技术生成

主要参考【贪心】PAT 1033. To Fill or Not to Fill (25)


感觉这样的题目在实际考试中真的要特别熟练掌握贪心算法才能写出来,所以我基本上是照抄的。。。。可怜


#include<cstdio>
#include<algorithm>

using namespace std;

typedef struct {
    int pos;
    double price;
}gasstation;

gasstation gasst[502];

bool cmp (gasstation a, gasstation b) {
    if(a.pos < b.pos)
        return true;
    return false;
}

int main()
{
    int Cmax, D, Davg, N, i;

    scanf("%d %d %d %d", &Cmax, &D, &Davg, &N);
    for(i=0; i<N; i++)
        scanf("%lf %d", &gasst[i].price, &gasst[i].pos);
    sort(gasst, gasst + N, cmp);

    int cur_station = 0;
    double cur_gas = 0;
    double cur_cost = 0;
    bool arrived = false;
    double max_run_dist = Cmax * Davg;

    while(!arrived) {
        bool has_station = false;
        bool has_cheaper = false;
        double cheapest_price = 10000;
        int cheapest_id;
        for(i=cur_station+1; i<N; i++) {
            if(gasst[i].pos - gasst[cur_station].pos <= max_run_dist) {
                has_station = true;
                if(gasst[i].price < gasst[cur_station].price) {
                    has_cheaper = true;
                    double dist = gasst[i].pos - gasst[cur_station].pos;

                    // guarteed to be greater than 0 ?
                    double needgas = dist / Davg - cur_gas;

                    cur_gas = 0;
                    cur_cost += (needgas * gasst[cur_station].price);
                    cur_station = i;
                    break;
                }

                if(gasst[i].price < cheapest_price) {
                    cheapest_price = gasst[i].price;
                    cheapest_id = i;
                }
            }
            else
                break;
        }

        if(!has_cheaper && max_run_dist >= (D - gasst[cur_station].pos)) {
            double dist = D - gasst[cur_station].pos;
            double needgas = dist / Davg - cur_gas;
            cur_cost += needgas * gasst[cur_station].price;
            printf("%.2lf\n", cur_cost);
            return 0;
        }

        // 肯定是在最便宜的地方加,以为既要达到终点又要加油
        if(has_station && !has_cheaper) {
            double needgas = Cmax - cur_gas;
            cur_cost += needgas * gasst[cur_station].price;
            double dist = gasst[cheapest_id].pos - gasst[cur_station].pos;
            cur_gas = Cmax - dist / Davg;
            cur_station = cheapest_id;
        } else if(!has_station) {
            printf("The maximum travel distance = %.2lf\n", gasst[cur_station].pos + max_run_dist);
            return 0;
        }
    }

    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值