*1033. To Fill or Not to Fill

不加target==n这个条件测试点1会出现超时=皿=没找到原因。

很有价值的贪心题目!

#include <stdio.h>
#define INFINITY 10000
/*有时候不用加满油,只要加够向终点的油即可*/
typedef struct Station {
	float price;
	float dist;
}Station;
Station GasS[501];
int FindTarget(int loc, float MaxDist,int n);

int main()
{
	int  n,i,j,loc,target;
	float StationP, StationD, gas = 0, MaxDist, cost = 0,cpct, D, Davg;
	scanf("%f %f %f %d", &cpct, &D, &Davg, &n);
	for (i = 0; i < n; i++) {
		scanf("%f %f", &StationP, &StationD);
		j = i;
		while(j>0&& (GasS[j - 1].dist>StationD)) {
			GasS[j].dist = GasS[j - 1].dist;
			GasS[j].price = GasS[j - 1].price;
			j--;
		}
		GasS[j].dist = StationD;
		GasS[j].price = StationP;;
	}
	GasS[n].dist = D;
	GasS[n].price = 0;/*添加终点*/

	if (GasS[0].dist != 0) {
		printf("The maximum travel distance = 0.00");
		return 0;
	}
	loc = 0;
	MaxDist = Davg*cpct;/*加满油时可行驶的最大距离*/
	while (1) {
		target = FindTarget(loc,MaxDist, n);
		if(target==-1||target==n)/*loc==最后一个加油站*/
			if (MaxDist >= D - GasS[loc].dist) {
				cost += ((D - GasS[loc].dist) / Davg - gas)*GasS[loc].price;
				printf("%0.2f", cost);
				break;
			}else {
				printf("The maximum travel distance = %0.2f", GasS[loc].dist + MaxDist);
				break;
			}

		else if (GasS[target].price < GasS[loc].price) {/*加最少的油开过去,*/
			if (gas < (GasS[target].dist - GasS[loc].dist) / Davg) {/*油箱油不够*/
				cost += ((GasS[target].dist - GasS[loc].dist) / Davg - gas)*GasS[loc].price;
				gas = 0;/*到目的站时油箱已空*/
			}
			else 
				gas -= (GasS[target].dist - GasS[loc].dist) / Davg;
		
		}else {
			cost += (cpct - gas)*GasS[loc].price;
			gas =cpct- (GasS[target].dist - GasS[loc].dist) / Davg;
		}
		loc = target;
	}
	return 0;
}

int FindTarget(int loc, float MaxDist,int n)
{
	int target,Min=-1;
	float MinPrice = INFINITY;
	for (target = loc + 1; target < n+1; target++) {
		if (GasS[target].dist > GasS[loc].dist + MaxDist)
			break;
		if (GasS[target].price < GasS[loc].price)
			return target;
		if (GasS[target].price < MinPrice) {
			MinPrice = GasS[target].price;
			Min = target;
		}
	}
	return Min;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值