PAT真题练习(甲级)1033 To Fill or Not to Fill (25 分)
原题网址:https://pintia.cn/problem-sets/994805342720868352/problems/994805458722734080
A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.
Input Specification:
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.
Output Specification:
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 300
Sample Output 1:
749.17
Sample Input 2:
50 1300 12 2
7.10 0
7.00 600
Sample Output 2:
The maximum travel distance = 1200.00
AC代码
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct Station {
int distance;
double price;
// 定义比较函数,根据加油站的距离进行排序
bool operator < (const Station &b) {
return distance < b.distance;
}
};
int main() {
int C, D, DA, N;
cin >> C >> D >> DA >> N;
vector<Station> vstation(N + 1);
for (auto i = 0; i < N;i++) {
cin >> vstation[i].price >> vstation[i].distance;
}
// 将终点看做一个价格为0的加油站
vstation[N].price = 0;
vstation[N].distance = D;
// 对加油站根据距离排序
sort(vstation.begin(), vstation.end());
// 如果初始位置没有站点,则直接输出
if (vstation[0].distance != 0) {
printf("The maximum travel distance = 0.00");
return 0;
}
int nstation = -1; // 下一个价格比当前站点小的站点
int estation = -1; // 能到达的最远站点
int cstation = 0; //当前站点
int max_dis = vstation[cstation].distance + C * DA; // 当前可运行到的最远距离
double cgas = 0; //当前剩余油量
double cprice = 0; //当前的花销
while (cstation != N) {
nstation = cstation;
estation = cstation;
max_dis = vstation[cstation].distance + C * DA;
for (auto i = cstation; i <= N;i++) {
if (vstation[i].distance > max_dis) break;
if (vstation[i].price < vstation[cstation].price) {
// 若存在比当前站点价格小的站点,则跳出循环(此时不关心最远站点)
nstation = i;
break;
}
estation = i;
}
// 若在可到达的最远距离内,不存在加油站,则不能继续前进,跳出循环
if (nstation == cstation && estation == cstation) break;
// 若不存在价格更小的加油站,则把油箱加满,以最远的加油站为下一个分析点
if (nstation == cstation) {
cprice += (C - cgas) * vstation[cstation].price;
cgas = C - (vstation[estation].distance - vstation[cstation].distance) * 1.0 / DA;
cstation = estation;
}
// 若存在价格更小的加油站,则加油至可到达该加油站
else {
cprice += ((vstation[nstation].distance - vstation[cstation].distance) * 1.0 / DA - cgas) * vstation[cstation].price;
cgas = 0;
cstation = nstation;
}
}
if (cstation == N) printf("%.2f", cprice);
else printf("The maximum travel distance = %.2f",float( max_dis));
}