PAT甲级_1033 To Fill or Not to Fill (25 分)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44705116/article/details/102674037

1、1033 To Fill or Not to Fill (25 分)

题目大意:给出几个加油站与终点,求出花费最少路径。

考查贪心算法,每次到达加油站时,观察能到达范围内价格最便宜的加油站,将油加至刚好能够到达该站为止;若没有比当前站更便宜的,加满油去次便宜的站;

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int INF = 9999999;
struct station
{
	double dis, price;
};

bool cmp1(station a, station b) {
	return a.dis < b.dis;
}

int main() {
	double d, davg, cmax;
	int n;
	scanf("%lf %lf %lf %d", &cmax, &d, &davg, &n);
	vector<station> sta(n + 1);
	sta[0] = { d, 0.0 };
	for (int i = 1; i <= n; i++) {
		scanf("%lf %lf", &sta[i].price, &sta[i].dis);
	}
	sort(sta.begin(), sta.end(), cmp1);
	double nowdis = 0.0, nowprice = sta[0].price, leftdis = 0.0, sumprice = 0.0;
	if (sta[0].dis != 0) {
		printf("The maximum travel distance = 0.00");
		return 0;
	}
	while (nowdis < d) {
		double fulldis = nowdis + cmax * davg, minprice = INF;
		int flag = 0, md=0;
		for (int i = 1; i <= n && sta[i].dis <= fulldis; i++) {
			if (sta[i].dis <= nowdis) {
				continue;
			}
			if (sta[i].price < nowprice) {
				sumprice += (sta[i].dis - nowdis - leftdis) * nowprice / davg;
				nowprice = sta[i].price;
				leftdis = 0.0;
				nowdis = sta[i].dis;
				flag = 1;
				break;
			}
			if (sta[i].price < minprice) {
				minprice = sta[i].price;
				md = i;
			}
		}
		if (minprice != INF && flag == 0) {
			sumprice += nowprice * (cmax - leftdis / davg);
			leftdis = cmax * davg - sta[md].dis + nowdis;
			nowprice = sta[md].price;
			nowdis = sta[md].dis;
		}
		if (minprice == INF && flag == 0) {
			printf("The maximum travel distance = %.2f", nowdis + cmax * davg);
			return 0;
		}
	}
	printf("%.2f", sumprice);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44705116/article/details/102674037