题目大意:给出N个加油站的油费以及距离出发点的距离,汽车油箱有容量上限,求出从出发点到达目的地的最少油费。如果不能到达目的地,输出最远能到达的距离。
个人觉得是相当复杂的一个模拟题,单步跟踪了好几次逻辑才写完整,考察的主要是贪心策略。要点列举如下:
① 目的地也作为一个加油站,油费为0,这样能保证在查找最低油费的加油站时一定能查找到目的地。
② 在当前所在的加油站往后看,在能到达的范围内,如果有比当前价格更低的,就去那个加油站。否则,找到在能到达的范围内的价格最低的加油站,并在当前加油站加满油,前往该加油站。
③ 如果第一个加油站不在起点处,直接输出0.00(测试点2)。
④ 在当前所在的加油站往后看,如果没有能到达的加油站,因为已经把目的地也设置为了加油站,那么说明到不了目的地,输出当前加油站的位置+加满油后的最大距离。
AC代码:
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
struct station
{
double distance;
double price;
station(double distance, double price):distance(distance), price(price){};
bool operator <(const station& other)
{
return this->distance < other.distance;
}
};
int main()
{
double CMAX, D, A, N;
scanf("%lf%lf%lf%lf", &CMAX, &D, &A, &N);
vector<station> v;
for (int i = 0; i < N; ++i)
{
double price;
double distance;
scanf("%lf%lf", &price, &distance);
v.push_back(station(distance, price));
}
v.push_back(station(D, 0));
sort(v.begin(), v.end());
if(v[0].distance > 0)
{
printf("The maximum travel distance = 0.00");
return 0;
};
double d = 0, C = 0;
int current = 0;
double cost = 0;
while(d < D)
{
int next = current;
if(v[current + 1].distance > v[current].distance + CMAX * A)
{
d = v[current].distance + CMAX * A;
break;
}
for (int i = current + 1; i < v.size() && v[current].distance + CMAX * A >= v[i].distance; ++i)
{
if(v[i].price <= v[current].price)
{
next = i;
break;
}
}
if(next != current)
{
if(v[next].distance - v[current].distance > C * A)
{
cost += (v[next].distance - v[current].distance - C * A) / A * v[current].price;
C = 0;
}
d = v[next].distance;
current = next;
}
else
{
next = -1;
double minPrice = 1e10;
for (int i = current + 1; i < v.size() && v[current].distance + CMAX * A >= v[i].distance; ++i)
{
if(v[i].price < minPrice)
{
next = i;
minPrice = v[i].price;
}
}
cost += (CMAX - C) * v[current].price;
C = CMAX - (v[next].distance - v[current].distance) / A;
d = v[next].distance;
current = next;
}
}
if(d == D) printf("%.2f", cost);
else printf("The maximum travel distance = %.2f", d);
return 0;
}

该博客介绍了PAT A1033题目的解决方案,这是一个涉及贪心策略和模拟的复杂问题。博主详细阐述了如何通过考虑目的地为加油站、寻找最低油费、动态规划和加满油的策略来确定从出发点到目的地的最小油费。如果无法到达目的地,则计算最远可达到的距离。博客内容包括关键步骤和AC代码。

703

被折叠的 条评论
为什么被折叠?



