题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805458722734080
思路
这题有点难度的,也可能是因为这两天在准备班会和简历的关系吧,有一段时间没写代码了,导致这题写起来比较吃力,不过还是把算法笔记上的代码给看懂了。
画一下思维导图
代码
#include <iostream>#include <algorithm>#include <vector>using namespace std;const int maxn = 510;//加油站数量const int INF = 1000000000;struct station{double price, dis;}st[maxn];bool cmp(station a, station b){return a.dis < b.dis;}int main(){int n;double Cmax, D, Davg;scanf("%lf%lf%lf%d",&Cmax, &D, &Davg, &n);for(int i = 0; i < n; i++){scanf("%lf%lf",&st[i].price,&st[i].dis);}st[n].price = 0;st[n].dis = D;//放置终点sort(st, st + n, cmp);if(st[0].dis!=0){printf("The maximum travel distance = 0.00\n");} else {int now = 0;double ans = 0, nowTank = 0, MAX = Cmax * Davg;while(now < n){//选下一个加油站int k = -1;double priceMin = INF;for(int i = now + 1; i <= n && st[i].dis - st[now].dis <= MAX; i++){//距离在可行使范围内if(st[i].price < priceMin){//如果比当前油价低priceMin = st[i].price;k = i;//记录加油站//第一个低于当前油价的直接退出循环if(priceMin < st[now].price){break;}}}if(k == -1) break;//找不到结果那么退出循环//下面计算花费double need = (st[k].dis - st[now].dis) / Davg;if(priceMin < st[now].price){//若低于当前油价,那么只需要加足够到达K的油if(nowTank < need){ans += (need - nowTank)*st[now].price;nowTank = 0;//到达下一个加油站} else {nowTank -= need;}} else {//目的油站k比当前油价高,那么加满ans += (Cmax - nowTank) * st[now].price;//油箱剩多少油nowTank = Cmax - need;}now = k;}if (now == n){printf("%.2f\n",ans);} else {printf("The maximum travel distance = %.2f\n",st[now].dis + MAX);//路程是当前距离加油箱内油最远行驶距离}}return 0;}
