一、题目内容
题目描述:
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>
using namespace std
;
struct Station
{
float price
;
float dis
;
float end
;
bool operator < (const Station
& A
) const{
return dis
< A
.dis
;
}
}buf
[502];
int main(){
int n
;
float cmax
,ddis
,davg
;
while(scanf("%f %f %f %d",&cmax
,&ddis
,&davg
,&n
)!=EOF){
for(int i
=0;i
<n
;i
++){
scanf("%f %f",&buf
[i
].price
,&buf
[i
].dis
);
if(buf
[i
].dis
+cmax
*davg
>=ddis
){
buf
[i
].end
=ddis
;
}else{
buf
[i
].end
=buf
[i
].dis
+cmax
*davg
;
}
}
sort(buf
,buf
+n
);
float ability
=0;
float totalprice
=0;
if(buf
[0].dis
>0){
printf("The maximum travel distance = 0.00\n");
continue;
}
for(int i
=0;i
<n
;){
int j
=i
+1;
if(buf
[j
].dis
>buf
[i
].end
){
printf("The maximum travel distance = %.2f\n",buf
[i
].end
);
break;
}
if(i
==n
-1&&ddis
>buf
[i
].end
){
printf("The maximum travel distance = %.2f\n",buf
[i
].end
);
break;
}
if(buf
[j
].dis
==buf
[i
].end
){
totalprice
+=(cmax
*davg
-ability
)/davg
*buf
[i
].price
;
ability
=0;
i
=j
;
continue;
}
int flag
=0;
if(i
<n
-1){
while(j
<=n
-1&&buf
[j
].dis
<=buf
[i
].end
){
if(buf
[j
].price
<=buf
[i
].price
){
flag
=1;
totalprice
+=(buf
[j
].dis
-buf
[i
].dis
-ability
)/davg
*buf
[i
].price
;
i
=j
;
ability
=0;
break;
}
j
++;
}
}
int k
=i
+1;
float min
=buf
[k
].price
;
int mink
=k
;
if(flag
==0){
if(buf
[i
].end
==ddis
){
totalprice
+=(ddis
-ability
-buf
[i
].dis
)/davg
*buf
[i
].price
;
printf("%.2f\n",totalprice
);
break;
}
for(;k
<j
;k
++){
if(buf
[k
].price
<min
){
min
=buf
[k
].price
;
mink
=k
;
}
}
totalprice
+=(cmax
*davg
-ability
)/davg
*buf
[i
].price
;
ability
=buf
[i
].end
-buf
[mink
].dis
;
i
=mink
;
}
}
}
}