贪心 5

来源:互联网 发布:2017信用卡淘宝套现 编辑:程序博客网 时间:2024/06/05 06:10
/*
int -2147438648~+2147438647,1后面9个0还是ok的
题目1437:To Fill or Not to Fill
题目描述:
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.
输入:
For each case, the first line contains 4 positive numbers: Cmax (<= 100), the maximum capacity of the tank; D (<=30000), the distance between Hangzhou and the destination city; Davg (<=20), the average distance per unit gas that the car can run; and N (<= 500), the total number of gas stations. Then N lines follow, each contains a pair of non-negative numbers: Pi, the unit gas price, and Di (<=D), the distance between this station and Hangzhou, for i=1,...N. All the numbers in a line are separated by a space.
输出:
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.
样例输入:
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
50 1300 12 2
7.10 0
7.00 600
样例输出:
749.17
The maximum travel distance = 1200.00
*/
/*
利用贪心法,每次走一站,记录当前距离,当前油箱油量。
贪心策略:
在当前站向前看,如果一次可行驶最大距离内有较便宜的加油站,加油量到可以行驶到第一个最


便宜的站点
如果最大距离以内当前站最便宜,加满油
如果任意一站到下一站的距离超过最大距离,则无法到达
特殊情况:初始站点没有加油站
*/
#include <stdio.h>
#include <algorithm>
#include <math.h>
using namespace std;
struct station{
double pi; //该加油站单位油的价格
int di;//杭州到此加油站的距离
bool operator < (const station &b) const {
return di < b.di;
}
}buf[501];
int main(){
int cmax,//油箱容量
d,//从杭州到目的地的距离
davg,//每单位油可以行驶的距离
n,//加油站个数
i;
while(scanf("%d%d%d%d",&cmax,&d,&davg,&n) != EOF){
double sum=0;
int k=0;
for(i=0;i<n;i++){
scanf("%lf%d",&buf[i].pi,&buf[i].di);
}
buf[n].di = d;
buf[n].pi = 1000000.0;
int muxd = cmax * davg; //加满油可以行驶的距离
sort(buf,buf+n);
double remained_gas = 0;//剩余油量
for(i=0;i<n;i++){
if(buf[0].di != 0){
printf("The maximum travel distance = 0.00\n");
break;}
else{
k=i+1;
if(i != 0)
remained_gas -= ((double)(buf[i].di-buf[i-1].di))/davg; //每到一个新的加油站,就开始新的判断
for(;k<n && buf[k].pi >= buf[i].pi;k++)
continue;//直到k>=n || buf[k].pi<buf[i].pi时才停止k++
if(buf[k].di - buf[i].di > muxd){
sum += (cmax-remained_gas)*buf[i].pi;
remained_gas = cmax;
}
else{
double tmp;
tmp=((double)(buf[k].di-buf[i].di))/davg - remained_gas;
if(tmp>0){
//fabs(tmp)>1e-5,1e-5 = 10^(-5) = 0.00001,1e是数字1不是字母l
sum += tmp * buf[i].pi;
remained_gas=((double)(buf[k].di-buf[i].di))/davg;


}
}
if(buf[i+1].di - buf[i].di > muxd){
printf("The maximum travel distance = %.2lf\n",(double)(buf[i].di+muxd));
break;
}
}
}
if(i==n) printf("%.2lf\n",sum);
}

return 0;
}
0 0
原创粉丝点击