P5017 摆渡车

题目描述

一个旅行家想驾驶汽车以最少的费用从一个城市到另一个城市(假设出发时油箱是空的)。给定两个城市之间的距离D1、汽车油箱的容量C(以升为单位)、每升汽油能行驶的距离D2、出发点每升汽油价格P和沿途油站数N(N可以为零),油站i离出发点的距离Di、每升汽油价格Pi(i=1,2,…,N)。计算结果四舍五入至小数点后两位。如果无法到达目的地,则输出“No Solution”。

输入格式

第一行,D1CD2P,N。

接下来有N行。

i+1行,两个数字,油站i离出发点的距离Di和每升汽油价格Pi

输出格式

所需最小费用,计算结果四舍五入至小数点后两位。如果无法到达目的地,则输出“No Solution”。

输入输出样例

输入 #1
275.6 11.9 27.4 2.8 2
102.0 2.9
220.0 2.2
输出 #1
26.95

说明/提示

N≤6,其余数字≤500

思路

这道题目应该算是妥妥的贪心+模拟吧……

算法原理如下:

1.枚举途中经过的加油站,每经过一个加油站,计算一次花费;

2.在一个加油站所需要加的油,就是能够支持它到达下一个油价比它低的加油站的量;

3.如果在这个加油站即使加满油,都不能到达一个比它油价低的加油站,就把油箱加满,前往能够到达的加油站中油价最低的那个;

4.如果在这个加油站即使加满油,都不能到达任意一个加油站,也不能到达终点城市,说明无解;

代码

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;

const int oo=1e9;
const int N=510;

int n;
double D1,D2,C,P;
double res,ans,maxx;

struct node {
	double co, dis;
	bool friend operator <(const node& a, const node& b) {
		return a.dis<b.dis;
	}
} p[N];

int work(int now) {
	int flag=oo;
	double d=p[now].dis;
	for(int i=now+1; i<=n&&p[i].dis-d<=maxx; i++) {
		if(p[i].co < p[now].co) {
			ans+=((p[i].dis-d-res)/D2)*p[now].co;
			res=0;
			return i;
		}
		if(flag==oo||p[i].co<p[flag].co)
			flag = i;
	}
	if(D1-p[now].dis<=maxx) {
		ans+=((D1-p[now].dis-res)/D2)*p[now].co;
		return oo;
	}
	if(flag==oo) {
		printf("No Solution\n");
		return -1;
	} else {
		ans+=C*p[now].co;
		res+=(maxx-(p[flag].dis-d));
		return flag;
	}
}

int main() {
	scanf("%lf%lf%lf%lf%d", &D1, &C, &D2, &P, &n);
	p[0].dis=0, p[0].co=P;
	for(int i=1; i<=n; i++)
		scanf("%lf%lf", &p[i].dis, &p[i].co);
	sort(p,p+n+1);
	maxx=C*D2;
	int k=0,t;
	do {
		t=work(k),k=t;
		if(t==-1)
			return 0;
	} while(t!=oo);
	printf("%.2lf", ans);
	return 0;
}

 

posted @ 2019-11-09 15:30  双子最可爱啦  阅读(229)  评论(0编辑  收藏  举报