解题过程的小记录,如有错误欢迎指出。
难度:四星(贪心好难哦orz,此题多复习看看吧哭了)
题目分析
在一条成直线的路上错落这加油站,加油站中的油价有高有低,找出到终点的最低价格加油方案,如果不能达到最终站点,则输出最远能行驶的距离
注意点
- 因为刚开始的油箱是空的,如果不存在距离为0的加油站点,则最远能行驶的距离是0(有一个测试点是关于这个的
- 只有当距离下一个加油站即使加满油也到不了的情况出现时,才会停止,且最远距离要算到加满后行驶出的最远距离
- 本题中除了站点数,其余最好都设置为double型,避免小数取整出错
我的解题过程
思路
(参考晴神)
首先要算出范围(加满油最远能行驶的距离)
- 把终点设置为一个油费为0(这样就会在选择的时候优先去),距离为目的地距离的站点
- 在范围中找出最近的比当前站点便宜的点,加油只加开到那个站点的油
- 如果范围中不存在比当前站点便宜的油,则把油箱加满(注意:此处在计算油费的时候别忘记要减去油箱中本来就有的油),然后去剩下站点中油费最便宜的站点(如果出现两个相同价格,则越远越好)
bug
- 一开始毫无思路,无从着手,看了晴神的思路再开始自己写
- 和给出的样例比对,费用的计算出了点问题,因为忽略了油箱剩下油
代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct station {
double price, DtoHZ;
};
int comp1(station s1, station s2) {
return s1.DtoHZ < s2.DtoHZ;
}
int main()
{
double tank, distance, unit;
int n;
cin >> tank >> distance >> unit >> n;
vector<station> s(n + 1);
for (int i = 0; i < n; i++) {
cin >> s[i].price >> s[i].DtoHZ;
}
s[n].price = 0;//目的地设为最终站点
s[n].DtoHZ = distance;
sort(s.begin(), s.end(), comp1);
if (s[0].DtoHZ != 0) {
cout << "The maximum travel distance = 0.00";
return 0;
}
double longest = tank*unit;
double howfar = 0;//记录当前距离
int ipos = 0;//记录当前所在的加油站
double nowgas = 0;//记录当前的汽油存量
double fee = 0;//记录总共花销
while (ipos != n) {
if (s[ipos + 1].DtoHZ - s[ipos].DtoHZ > longest) {
howfar = s[ipos].DtoHZ + longest;
printf("The maximum travel distance = %.2f", howfar);
return 0;
}
bool flag = false;
for (int i = ipos + 1; i <= n; i++) {//找出在可以开到的范围内最近的比自己便宜的点
if (s[i].DtoHZ - s[ipos].DtoHZ > longest) {
flag = true;
break;
}
if (s[i].price < s[ipos].price) {
if (nowgas*unit > s[i].DtoHZ-s[ipos].DtoHZ ) {
nowgas = nowgas - (s[i].DtoHZ - s[ipos].DtoHZ) / unit;
}
else {
fee += ((s[i].DtoHZ - s[ipos].DtoHZ) / unit - nowgas)*s[ipos].price;
nowgas = 0;
}
ipos = i;
break;
}
}
if (flag) {//在可以开到的范围内没有低于现在油价的点,则找出可以开到的范围内的最低油价(越远越好
fee += (tank - nowgas)*s[ipos].price;
nowgas = tank;
int nextpos = ipos + 1;
int i = ipos + 2;
for (i; i <= n; i++) {
if (s[i].DtoHZ - s[ipos].DtoHZ > longest) {
break;
}
if (s[nextpos].price > s[i].price) {
nextpos = i;
}
}
nowgas -= (s[nextpos].DtoHZ - s[ipos].DtoHZ) / unit;
ipos = nextpos;
}
}
printf("%.2f", fee);
return 0;
}
dalao的代码
全部代码因版权原因不放出来,大家可以自行去柳神博客购买或者参考晴神的上机笔记~
借鉴点
- 可以设置一个临时变量need来存放每次需要的油量,可以提高代码的可读性