1033 To Fill or Not to Fill (25 分)
思路
该题是找出最便宜路线的价格,不能到达终点就输出最大到达路径即可。
注意细节:起点没有加油站,直接输出最大路径为0
具体做法:把终点设置为一个加油站,花费为0,距离最远。
在可以到达的前提下,寻找比当前更便宜的加油站,算好到达所用花费,若无比当前更便宜,需把油箱加满。
题型类似:这类贪心,寻找花费最少,需要用到sort,再用循环。
代码
#include<bits/stdc++.h>
using namespace std;
struct stu{
double price;
double num;
}stud[1005];
bool cmp(stu a, stu b)
{
return a.num<b.num;
if(a.num==b.num)return a.price<b.price;
}
bool cmp2(stu a, stu b)
{
return a.price<b.price;
}
int main()
{
double C ; //油箱最大容量
double Dis ;//距离
double dis ; //每单元油跑多远
int N;//油站数量
cin>>C>>Dis>>dis>>N;
for(int i=0;i<N;i++)
{
cin>>stud[i].price>>stud[i].num;
}
stud[N].price = 0;
stud[N].num = Dis;
sort(stud,stud+N+1,cmp);
if(stud[0].num != 0)
cout<<"The maximum travel distance = 0.00"<<endl;
else{
int now = 0;
double ans =0 , nowTank = 0,Maxdis = C *dis ;
while(now<N)
{
int k = -1;
double Minprice = 100000000;
for(int i = now+1 ;i<=N&& stud[i].num - stud[now].num<=Maxdis ; i++)
{
if(stud[i].price < Minprice)
{
Minprice =stud[i].price ;
k = i;
if(Minprice < stud[now].price)
break;
}
}
//cout<<now<<endl;
if(k==-1)
break;
double need = (stud[k].num - stud[now].num) / dis;
//cout<<k<<" "<<now<<endl;
//cout<<stud[k].num - stud[now].num<<endl;
//cout<<need<<endl;
if(Minprice < stud[now].price)
{
if(nowTank<need)
{
ans += (need - nowTank)* stud[now].price;
//cout<<ans<<endl;
nowTank = 0 ;
}
else{
nowTank -=need;
}
}
else
{
ans += (C - nowTank)*stud[now].price;
//cout<<ans<<endl;
nowTank = C - need;
}
//cout<<now<<endl;
now = k;
}
if(now == N)
printf("%.2f\n",ans);
else
printf("The maximum travel distance = %.2f\n",stud[now].num +Maxdis);
}
}