您的位置:首页 > 其它

浙大PAT 1033题 1033. To Fill or Not to Fill

2014-02-09 12:04 99 查看
/*
用贪心算法:贪心思路如下:
首先对输入数据按距离升序排序,从A站点开始,记加满油后最大行驶距离为max, 从A站点到A+max距离内搜索:
1. 若搜索到第一个油价小于A的站点,则在A加油量为刚好保证能从A走到该站点。
2. 若没有1里面的站点但是有终点,则A加油量为刚好保证能从A走到该终点。
3. 若不是1,2情况但是此范围内有别的加油站,则在A加满油走到那些站点中油价最低的一个。
4. 不是1,2,3情况,肯定是在此范围为没有任何站点,则最大行驶距离为A+max.
注意:有个case是陷阱,没有距离为0的站点,则汽车无法行驶。油量不一定是整数!注意记录剩余油量!
过程中到达某个油站时油箱可能会有多余的由(到下个油站一定用完),而终点时油箱一定没油。
此题的测试数据不严,就2时加满油也能通过。
*/
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
double price;
double dis;
}Station;
int cmp(const void* ta,const void* tb){
Station* a=(Station*)ta;
Station* b=(Station*)tb;
return a->dis-b->dis;
}
int main(){
int i,j,n;
double cmax,d,davg;
Station sta[510];
scanf("%lf %lf %lf %d",&cmax,&d,&davg,&n);
for(i=0;i<n;i++){
scanf("%lf %lf",&sta[i].price,&sta[i].dis);
}
sta
.price=0;
sta
.dis=d;
qsort(sta,n+1,sizeof(Station),cmp);
if(sta[0].dis!=0){
printf("The maximum travel distance = 0.00\n");
return 0;
}
double maxdis=cmax*davg;
int s=0;
double tfee=0;
double leftgas=0;
while(sta[s].dis<d){
double maxfee=-1;
int maxindex=-1,fstindex=-1;
for(i=s+1;i<=n&&(sta[i].dis-sta[s].dis<=maxdis);i++){
if(maxfee==-1||(sta[i].price<maxfee)){
maxfee=sta[i].price;
maxindex=i;
}
if(fstindex==-1&&(sta[i].price<sta[s].price)){
fstindex=i;
}
}
if(maxindex==-1&&fstindex==-1) break;
if(fstindex==-1){
if(d-sta[s].dis<=maxdis){
tfee+=(((d-sta[s].dis)/davg-leftgas)*sta[s].price);
leftgas=0;
s=n;
}
else{
tfee+=((cmax-leftgas)*sta[s].price);
leftgas=cmax-((sta[maxindex].dis-sta[s].dis)/davg);
s=maxindex;
}
}
else{
tfee+=(((sta[fstindex].dis-sta[s].dis)/davg-leftgas)*sta[s].price);
leftgas=0;
s=fstindex;
}
}
if(sta[s].dis==d) printf("%.2lf\n",tfee);
else printf("The maximum travel distance = %.2lf\n",sta[s].dis+maxdis);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: