这一题坑比较多,需要考虑很多细节。例如要考虑到起始station的距离为不为0,如果不为0,就要直接输出。还有要考虑到到最近的符合条件station的距离是否超出汽车行驶的最大距离。
算法步骤:
- 建立结构体存储station的信息
- 构建比较函数
- 将输入数据存储到station数组中
- 根据距离进行排序
- 循环遍历数组,获取最大行程范围内的最低价的station
- 比较最低价和起始站点的价格。如果较低的话,则将油箱加到刚好到station用完;如果较高的话,则将油箱加满
- 判断车辆是否能行驶到目的地
关键点:
- 判断是否能从起始点出发
- 判断能否行驶到行驶范围内最近的车站
- 终点信息需要存储到数组中
核心代码:
for (int i = now + 1; i <= n && (stations[i].distance - stations[now].distance) <= maxdisance; i++)
{
if (priceMin > stations[i].price)
{
cout << i << ":" << stations[i].price<<endl;
priceMin = stations[i].price;
next = i;
}
if (priceMin < stations[now].price)
{
break;
}
}
代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
//将station按距离排序
//标志所处station位置
//比较最大里程范围内的station价格
//若小于起始点价格,比较现有tank内的存量和need
//若大于 ,油箱加满
struct station
{
double distance;
double price;
} stations[510];
bool cmp(station a, station b)
{
return a.distance < b.distance;
}
int main()
{
double cmax, d, davg;
int n;
scanf("%lf %lf %lf %d", &cmax, &d, &davg, &n);
for (int i = 0; i < n; i++)
{
scanf("%lf %lf", &stations[i].price, &stations[i].distance);
}
//这里要记得存储终点信息
stations[n].price = 0;
stations[n].distance = d;
sort(stations, stations + n, cmp);
double maxdisance = cmax * davg;
int now = 0;
double total = 0, nowtank = 0;
//这里有个坑,假如出发地不是从0开始
if (stations[0].distance != 0)
{
printf("The maximum travel distance = 0.00\n");
}
else
{
while (now < n)
{
int next = -1;
double priceMin = INT32_MAX;
//next范围应该是包括第n个
for (int i = now + 1; i <= n && (stations[i].distance - stations[now].distance) <= maxdisance; i++)
{
if (priceMin > stations[i].price)
{
priceMin = stations[i].price;
next = i;
}
if (priceMin < stations[now].price)
{
break;
}
}
//next=-1,最近车站在最大行程范围外
if (next == -1)
{
break;
}
double need = (stations[next].distance - stations[now].distance) / davg;
if (priceMin < stations[now].price)
{
if (need > nowtank)
{
total += (need - nowtank) * stations[now].price;
nowtank = 0;
}
else
{
nowtank -= need;
}
}
else
{
total += (cmax - nowtank) * stations[now].price;
nowtank = cmax - need;
}
now = next;
}
if (now == n)
{
printf("%.2lf", total);
}
else
{
//如果未能到达目的地,则计算最远行程,这是在现有车站范围内
printf("The maximum travel distance = %.2lf", maxdisance + stations[now].distance);
}
}
}