解法一:贪心

将终点视为一个价格为0的加油站,对所有加油站按照距离排序。
考虑起点处无加油站的情况。
加油的贪心策略如下。

  • 和当前位置相比,如果最大可及范围有价格更加便宜的加油站,则选择最近的前往,在当前位置加油至足够到达即可
  • 如果没有更便宜的加油站,在当前位置加满油,然后行驶到相对最便宜的加油站
  • 如果没有加油站了,说明无法到达终点,加满油计算最大行驶距离。 ```cpp

    include

using namespace std; const double EPS = 1e-6;

class Station { public: double price; double dis;

  1. Station() {}
  2. Station(double price, int dis) : price(price), dis(dis) {}

};

bool cmp(Station o1, Station o2) { return o1.dis < o2.dis; }

Station stations[505];

int main() { ios::sync_with_stdio(false); cin.tie(0); cout << fixed << setprecision(2);

  1. double C_max, D, D_avg;
  2. int N;
  3. cin >> C_max >> D >> D_avg >> N;
  4. for (int i = 0; i < N; ++i) {
  5. cin >> stations[i].price >> stations[i].dis;
  6. }
  7. sort(stations, stations + N, cmp);
  8. // 终点视为价格为0的加油站
  9. stations[N].price = 0.0;
  10. stations[N].dis = D;
  11. N++;
  12. // 出发点没有加油站
  13. if (stations[0].dis != 0) {
  14. cout << "The maximum travel distance = 0.00\n";
  15. return 0;
  16. }
  17. double gas = 0.0;
  18. double cost = 0.0;
  19. double cur = 0.0;
  20. double end;
  21. int curIndex = 0;
  22. while (cur < D) {
  23. // 找范围内最便宜的加油站
  24. end = cur + C_max * D_avg;
  25. // 是否有下一个加油站可达
  26. bool flag = false;
  27. int cheapStation = curIndex + 1;
  28. for (int i = curIndex + 1; i < N && stations[i].dis <= end; ++i) {
  29. flag = true;
  30. if (stations[i].price <= stations[cheapStation].price) {
  31. cheapStation = i;
  32. if (stations[cheapStation].price < stations[curIndex].price) {
  33. break;
  34. }
  35. }
  36. }
  37. if (!flag) {
  38. cout << "The maximum travel distance = " << end << '\n';
  39. return 0;
  40. }
  41. if (stations[cheapStation].price > stations[curIndex].price) {
  42. // 当前加油站最便宜, 直接加满
  43. // 然后跑到可及范围内最便宜的加油站
  44. cost += (C_max - gas) * stations[curIndex].price;
  45. gas = C_max - (stations[cheapStation].dis - cur) / D_avg;
  46. cur = stations[cheapStation].dis;
  47. curIndex = cheapStation;
  48. } else {
  49. // 可及范围有更便宜的加油站
  50. // 加油确保能跑到即可
  51. double need = (stations[cheapStation].dis - cur) / D_avg;
  52. if (gas < need) {
  53. cost += (need - gas) * stations[curIndex].price;
  54. gas = 0.0;
  55. } else {
  56. gas -= need;
  57. }
  58. cur = stations[cheapStation].dis;
  59. curIndex = cheapStation;
  60. }
  61. }
  62. cout << cost << '\n';

} ```