PAT甲级-贪心类型-1033 To Fill or Not to Fill解题思路

1033 To Fill or Not to Fill (25 分)

在这里插入图片描述
在这里插入图片描述

思路

该题是找出最便宜路线的价格,不能到达终点就输出最大到达路径即可。

注意细节:起点没有加油站,直接输出最大路径为0

具体做法:把终点设置为一个加油站,花费为0,距离最远。
在可以到达的前提下,寻找比当前更便宜的加油站,算好到达所用花费,若无比当前更便宜,需把油箱加满。

题型类似:这类贪心,寻找花费最少,需要用到sort,再用循环。

代码

#include<bits/stdc++.h>
using namespace std;

struct stu{
    double price;
    double num;
}stud[1005];

bool cmp(stu a, stu b)
{
    return a.num<b.num;
    if(a.num==b.num)return a.price<b.price;
}

bool cmp2(stu a, stu b)
{
    return a.price<b.price;
}

int main()
{
    double C ; //油箱最大容量
    double Dis ;//距离
    double dis ; //每单元油跑多远
    int N;//油站数量
    
    cin>>C>>Dis>>dis>>N;

    for(int i=0;i<N;i++)
    {
        cin>>stud[i].price>>stud[i].num;
    }

    stud[N].price = 0;
    stud[N].num = Dis;

    sort(stud,stud+N+1,cmp);

    
    if(stud[0].num != 0)
        cout<<"The maximum travel distance = 0.00"<<endl;
    else{
        int now = 0;
        double ans =0 ,  nowTank = 0,Maxdis = C *dis ; 

        while(now<N)
        {
            int k = -1;
            double Minprice = 100000000;
            for(int i = now+1 ;i<=N&& stud[i].num - stud[now].num<=Maxdis ; i++)
            {
                if(stud[i].price < Minprice)
                {
                    Minprice =stud[i].price ;
                    k =  i;
                    

                    if(Minprice < stud[now].price)
                        break;
                }
            }
            //cout<<now<<endl;
            
            if(k==-1)
                break;

            double need = (stud[k].num - stud[now].num) / dis;
            //cout<<k<<" "<<now<<endl;
            //cout<<stud[k].num - stud[now].num<<endl;
            //cout<<need<<endl;

            if(Minprice < stud[now].price)
            {
                if(nowTank<need)
                {
                    ans += (need - nowTank)* stud[now].price;
                    //cout<<ans<<endl;
                    nowTank = 0 ;
                }
                else{
                    nowTank -=need;
                }
            }
            else
            {
                ans += (C - nowTank)*stud[now].price;
                //cout<<ans<<endl;
                nowTank = C - need;
            }
            //cout<<now<<endl;
            now = k;
        }
        if(now == N)
            printf("%.2f\n",ans);
        else
            printf("The maximum travel distance = %.2f\n",stud[now].num +Maxdis);

            

        }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

wujiekd

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

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

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

打赏作者

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

抵扣说明:

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

余额充值