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.
Input Specification:
Each input file contains one test case. 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.
Output Specification:
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.
Sample Input 1: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 300Sample Output 1:
749.17Sample Input 2:
50 1300 12 2 7.10 0 7.00 600Sample Output 2:
The maximum travel distance = 1200.00
PAT甲级里面最难的几道之一了,核心思路有,但是编码能力不足,一部分细节写不出来,看了晴神的解法,感慨晴神的思路清晰,行云流水般就AC了本题,看来还是自己逻辑思路不够清晰,所以才会纠结局部细节。PAT做到现在,这是第三道让我觉得有难度的题目,赶紧刷完PAT去刷OI了。
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
struct gas {
double sta, unit;
}a[505];
bool cmp(gas a, gas b) {
return a.sta < b.sta;
}
int main(){
double cmax, dis, davg;
int n;
scanf("%lf%lf%lf%d", &cmax, &dis, &davg, &n);
double p = cmax*davg;
for (int i = 0; i < n; i++)
scanf("%lf%lf", &a[i].unit, &a[i].sta);
a[n].unit = 0;
a[n].sta = dis;
sort(a, a + n, cmp);
if (a[0].sta != 0) printf("The maximum travel distance = 0.00\n");
else {
int now = 0;
double tpri = 0, tank = 0, minp;
while (now < n) {
int k = -1;
minp = 1000000000000;
for (int i = now + 1; i <= n && (a[i].sta - a[now].sta <= p); i++) {
if (a[i].unit < minp) {
minp = a[i].unit;
k = i;
if (minp < a[now].unit) {
//tank = 0;
break;
}
//tank = p;
}
}
if (k == -1) {
//printf("%d", now);
break; }
double haoyou = (a[k].sta - a[now].sta) / davg;
if (a[k].unit < a[now].unit) {
if (haoyou > tank) {
tpri += (haoyou - tank)*a[now].unit;
tank = 0;
}
else {
tank -= haoyou;
}
}
else {
tpri += (cmax - tank)*a[now].unit;
tank = cmax - haoyou;
}
now = k;
}
//printf("%d", now);
if (now == n) printf("%.2f", tpri);
else printf("The maximum travel distance = %.2f", a[now].sta + p);
}
return 0;
}