【PAT】【贪心】加油还是不加,是个问题,开车从杭州到其他城市,路上有些加油站,设计最便宜的路线

本文介绍了一道编程问题,要求设计一个算法来规划从杭州到其他城市的最低油费路线,考虑汽车油箱容量限制和沿途不同加油站的价格。通过实例展示了如何利用排序和贪心策略找出最优路径或最大行驶距离。

https://pintia.cn/problem-sets/994805342720868352/problems/994805458722734080
1033 To Fill or Not to Fill (25 分)
With highways available, driving a car from Hangzhou to any other city is easy. But since the tank capacity of a car is limited, we have to find gas stations on the way from time to time. Different gas station may give different price. You are asked to carefully design the cheapest route to go.

在这里插入图片描述

Output Specification:
For each test case, print the cheapest price in a line, accurate up to 2 decimal places. It is assumed that the tank is empty at the beginning. If it is impossible to reach the destination, print The maximum travel distance = X where X is the maximum possible distance the car can run, accurate up to 2 decimal places.

Sample Input 1:
50 1300 12 8
6.00 1250
7.00 600
7.00 150
7.10 0
7.20 200
7.50 400
7.30 1000
6.85 300
Sample Output 1:
749.17
Sample Input 2:
50 1300 12 2
7.10 0
7.00 600
Sample Output 2:
The maximum travel distance = 1200.00


#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

struct fillOil {
	double gasPrice;
	int distance;
};

bool cmpStaion(fillOil a, fillOil b) {
	if (a.distance == b.distance)
	{
		return a.gasPrice < b.gasPrice;
	}
	else {
		return a.distance < b.distance;
	}
}

double fillOrNotFill(int maxCapacity, int distance, int avgrun, fillOil* stations, int nStations) {
	sort(stations, stations + nStations, cmpStaion);//按照距离从近到远排序
	if (stations[0].distance != 0)
	{
		// 车没油,也加不了油,哪里也去不了了
		cout << "The maximum travel distance = 0.00";
		return 0.0;
	}


	int canRun = maxCapacity * avgrun; //加满油最远到的距离
	int nowIndex = 0;  // 当前所在的位置距离杭州距离
	int stationIndex = 1, nowStationIndex = 0; //现在在第一个加油站,

	double leftOil = 0; //在便宜的油站,加到的多余的油
	double cheaperPrice = stations[nowStationIndex].gasPrice;//便宜价格
	int toNextDistance = 0; //到下一个站的距离
	double needOil = 0;//到下一个站需要的油

	double cost = 0;
	bool findCheap = false;//是否找到更便宜的

	//还没有到最后一个站,而且也没到终点
	while (stationIndex < nStations && nowIndex < distance)
	{
		cheaperPrice = stations[nowStationIndex].gasPrice;
		toNextDistance = 0;
		findCheap = false;
		while (stationIndex < nStations && (nowIndex + canRun) >= stations[stationIndex].distance)
		{
			//查找加满油能跑到的距离里,是否有更便宜的油
			if (cheaperPrice > stations[stationIndex].gasPrice)
			{
				toNextDistance = stations[stationIndex].distance - stations[nowStationIndex].distance; //距离
				needOil = toNextDistance / (double)avgrun; // 加到下一站需要的油
				if (leftOil - needOil > -1e-9) //剩下的油还够用
				{
					//cost += 0;//不花钱了
					leftOil -= needOil;
				}
				else {
					needOil = needOil - leftOil; //更新需要的油量
					leftOil = 0; // 剩下的油量
					cost += needOil * stations[nowStationIndex].gasPrice; //保存到下一站花销
				}
				findCheap = true;
				stationIndex++;
				break; // 找到更便宜的,就不用再找了
			}
			stationIndex++;
		}	

		stationIndex--;
		//没找到更便宜的,直接加满到下一个最远能到的点
		if (stationIndex < nStations && findCheap == false)
		{
			// 如果可以到终点,直接去; 
			if (distance - nowIndex <= canRun)
			{
				toNextDistance = distance - nowIndex;
				needOil = toNextDistance / (double)avgrun; // 加到能到的最远的一站需要的油
				if (leftOil - needOil > -1e-9) //剩下的油还够用
				{
					//cost += 0;//不花钱了
					leftOil -= needOil;
				}
				else {
					needOil = needOil - leftOil; //更新需要的油量
					leftOil = 0; // 剩下的油量
					cost += needOil * stations[nowStationIndex].gasPrice; //保存到下一站花销
				}
			}
			else {
				// 否则加满油,并且跑到当前能到达的最后一站去加油
				toNextDistance = stations[stationIndex].distance - stations[nowStationIndex].distance; //距离

				needOil = maxCapacity; // 因为当前已经是最便宜了,直接加满
				if (leftOil - needOil > -1e-9) //剩下的油还够用
				{
					//cost += 0;//不花钱了
					leftOil -= needOil;
				}
				else {
					needOil = needOil - leftOil; //更新需要的油量
					leftOil = 0; // 剩下的油量
					cost += needOil * stations[nowStationIndex].gasPrice; //保存到下一站花销
				}
				// 只有没找到更便宜的油站时,才需要加满油
				needOil = maxCapacity;
				leftOil = maxCapacity - toNextDistance / (double)avgrun; //到当前能到达的最后一站后,还有油
			}
		}

		nowIndex += toNextDistance;
		nowStationIndex = stationIndex;
		stationIndex++;//从下个站开始找比当前站便宜了
	}

	if (nowIndex >= distance)
	{
		printf("%.2f\n", cost);
		return cost;
	}
	else if (nowStationIndex < nStations)
	{
		//已经到了最后一站,能跑多远跑多远吧
		toNextDistance = canRun + nowIndex < distance ? canRun : distance - nowIndex; //距离
		needOil = toNextDistance / (double)avgrun; // 加到能到的最远的一站需要的油
		cost += needOil * stations[nowStationIndex].gasPrice; //保存花销
		nowIndex += toNextDistance;
		if (nowIndex >= distance)
		{
			printf("%.2f\n", cost);
			return cost;
		}
		else {
			printf("The maximum travel distance = %.2f\n", (double)nowIndex);
		}
	}
	else {
		cout << "出现异常情况";
	}

	return cost;
}


void Test_fillOrNotFill() {
	int maxCapacity = 0, distance = 0, avgRun = 0, stations = 0;
	cin >> maxCapacity >> distance >> avgRun >> stations;
	fillOil* fillStations = new fillOil[stations];
	for (int i = 0; i < stations; i++)
	{
		cin >> fillStations[i].gasPrice >> fillStations[i].distance;
	}
	fillOrNotFill(maxCapacity, distance, avgRun, fillStations, stations);
}

int main()
{
	Test_fillOrNotFill();
}

### 关于 PAT 考试中的田忌赛马问题 #### 田忌赛马问题描述 田忌赛马是一个经典的贪心算法题目,在这个问题中,给定了两组数据分别代表齐王和田忌的马的速度。比赛规则是双方各派出一匹马来进行一对一的比赛,胜利者得一分。目标是在已知对方马匹速度的情况下,通过合理的安排己方马匹出场顺序来获得尽可能多的分数。 #### 解题思路分析 对于此类问题可以采用如下策略: - 将两个数组按照从大到小排序。 - 使用双指针方法比较两端的大值或小值来进行匹配决策。 - 如果当前强的对手能赢,则让弱的一匹去送死;如果不能赢,则用自己强的一匹对抗之。 这种方法能够保证每次都能做出局部优的选择从而达到全局优的效果[^1]。 #### Python 示例代码实现 下面给出一段基于上述思想编写的Python程序用于模拟该过程: ```python def horse_racing(tian, wang): tian.sort(reverse=True) wang.sort(reverse=True) score = 0 while tian and wang: if tian[-1] > wang[-1]: # 当田忌快的马比齐王快还快时,派这匹马上场赢得这一局 score += 1 tian.pop() wang.pop() elif tian[0] < wang[0]: # 否则,当田忌慢的马输给齐王慢的时候, # 让它上场输掉这一轮保存实力更强的马 tian.pop(0) wang.pop() else: break return score if __name__ == "__main__": n = int(input()) tian = list(map(int, input().split())) wang = list(map(int, input().split())) result = horse_racing(tian[:], wang[:]) print(result) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值