PAT (Advanced) 1033. To Fill or Not to Fill (25)

#include <iostream>
#include <algorithm>
#include <iomanip>

using namespace std;

struct gas_station
{
	double price, dist;
}gs[501];

bool cmp(const gas_station &a, const gas_station &b)
{
	return a.dist < b.dist;
}

int main()
{
	double Cmax, D, Davg;
	int N;
	cin >> Cmax >> D >> Davg >> N;

	for (int i = 0; i < N; i++)
	{
		cin >> gs[i].price >> gs[i].dist;
	}
	sort(gs, gs + N, cmp);
	if (gs[0].dist != 0)
	{
		cout << "The maximum travel distance = 0.00" << endl;
		return 0;
	}

	bool arrived = false; 
	int cur_index = 0;
	double residue = 0, needgas = 0;
	double total_cost = 0;
	double max_run_dist = Cmax * Davg;
	
	while (!arrived)
	{
		bool more_gs = false;
		bool cheaper = false;
		double cheapest_price = 10000;
		int cheapest_index;
		for (int i = cur_index + 1; i < N; i++)
		{
			
			if (gs[i].dist - gs[cur_index].dist <= max_run_dist)
			{
				more_gs = true;
				if (gs[i].price < gs[cur_index].price)
				{
					cheaper = true;
					needgas = (gs[i].dist - gs[cur_index].dist) / Davg - residue;
					residue = 0;
					total_cost += needgas * gs[cur_index].price;
					cur_index = i;
					break;
				}
				if (gs[i].price < cheapest_price)
				{
					cheapest_price = gs[i].price;
					cheapest_index = i;
				}
			}
			else
				break;
		}
		if (!cheaper && D - gs[cur_index].dist <= max_run_dist)
		{
			needgas = (D - gs[cur_index].dist) / Davg - residue;
			total_cost += needgas * gs[cur_index].price;
			cout << fixed << setprecision(2) << total_cost << endl;
			return 0;
		}
		if (!cheaper && more_gs)
		{
			needgas = Cmax - residue;
			total_cost += needgas * gs[cur_index].price;
			residue = Cmax - (gs[cheapest_index].dist - gs[cur_index].dist) / Davg;
			cur_index = cheapest_index;
		}
		else if (!more_gs)
		{
			cout << "The maximum travel distance = " << fixed << setprecision(2) << gs[cur_index].dist + max_run_dist << endl;
			return 0;
		}
	}
}
参考: http://www.cnblogs.com/XBWer/p/3866486.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值