PAT甲1033 To Fill or Not to Fill (25)(25 分)

本文介绍了一个基于结构体和排序算法的最优加油策略实现方案。该算法通过读取最大油箱容量、总距离、平均油耗及加油站信息等输入参数,利用预处理数组记录加油站的有效覆盖范围,并采用排序算法优化选择成本最低的加油站,最终输出完成旅程所需的最小费用或最大可行行驶距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

struct station
{
    double price;
    int st;
    int ed;
    bool flag;
}sta[510];

int pre[31000];
int post[31000];
int Cmax,D,Davg,N;

bool cmp(station a,station b)
{
    return a.price<b.price;
}

int main()
{
    scanf("%d%d%d%d",&Cmax,&D,&Davg,&N);
    memset(pre,-1,sizeof(pre));
    memset(post,-1,sizeof(post));
    int Dmax=Davg*Cmax;
    for(int i=0;i<N;i++)
    {
        scanf("%lf%d",&sta[i].price,&sta[i].st);
        sta[i].ed=min(D,sta[i].st+Dmax);
        sta[i].flag=false;
    }
    int totalD=0;
    bool start=false;
    double totalpay=0;
    sort(sta,sta+N,cmp);
    for(int i=0;i<N;i++)
    {
        while(post[sta[i].st]!=-1&&post[sta[i].st]!=sta[i].st)
        {
            sta[i].st=post[sta[i].st];
        }
        while(pre[sta[i].ed]!=-1&&pre[sta[i].ed]!=sta[i].ed)
        {
            sta[i].ed=pre[sta[i].ed];
        }
        if(sta[i].ed>=sta[i].st)
        {
            totalpay+=(sta[i].ed-sta[i].st)*1.0/Davg*sta[i].price;
            totalD+=sta[i].ed-sta[i].st;
            for(int j=sta[i].st;j<=sta[i].ed;j++)
            {
                pre[j]=sta[i].st;
                post[j]=sta[i].ed;
            }
            if(sta[i].st==0)
            {
                start=true;
            }
            if(totalD>=D)
            {
                break;
            }
        }
        else
        {
            continue;
        }
    }
    if(start==false)
    {
        printf("The maximum travel distance = 0.00");
    }
    else
    {
        if(totalD<D)
        {
            printf("The maximum travel distance = %.2f",totalD*1.0);
        }
        else
        {
            printf("%.2f",totalpay);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值