PAT1033 To Fill or Not to Fill
With highways available, driving a car from Hangzhou to any other city is easy. But since the tank capacity of a car is limited, we have to find gas stations on the way from time to time. Different gas station may give different price. You are asked to carefully design the cheapest route to go.
Input Specification:
Output Specification: For each test case, print the cheapest price in a line, accurate up to 2 decimal places. It is assumed that the tank is empty at the beginning. If it is impossible to reach the destination, print The maximum travel distance = X where X is the maximum possible distance the car can run, accurate up to 2 decimal places.
Sample Input 1:
50 1300 12 8 6.00 1250 7.00 600 7.00 150 7.10 0 7.20 200 7.50 400 7.30 1000 6.85 300
Sample Output 1:
749.17
Sample Input 2:
50 1300 12 2 7.10 0 7.00 600
Sample Output 2:
The maximum travel distance = 1200.00
解題思路: 思路參考自https://www.jianshu.com/p/00905ef1d79e 主要考察貪心,注意到過程最優導致全域性最優,就到第個站最優時,到第個站也是最優的。 貪心的具體策略:
1.從當前站尋找下一個第一次小於當前油費的車站 2.如果沒找到,看當前站+加滿油後能不能到達終點,如果能,輸出總費用,結束。 3,如果還不能到達終點站,從當前站加滿油到下一個能到達的區域性最小站,同時記錄剩餘的油量。
最後注意一個小case: 如果出發點不從0開始,那麼最遠達到的距離為0,因為在0處油箱是空的qwq
#include <iostream>
#include<cstdio>
#include<algorithm>
#define MAX 0xffffff
using namespace std;
struct Station{
int dis;
double price;
}t[505];
bool cmp(Station &a,Station &b){
return a.dis<b.dis;
}
int main(int argc, char** argv) {
int Cmax,D,Davg,N;
scanf("%d%d%d%d",&Cmax,&D,&Davg,&N);
for(int i=0;i<N;i++){
scanf("%lf %d",&t[i].price,&t[i].dis);
}
sort(t,t+N,cmp);
if(t[0].dis!=0){//出發點不從0開始,這時候沒有油,跑不動==.==
printf("The maximum travel distance = 0.00");
return 0;
}
double left=0,cos=0;
int last=-1,flag2=0,cnt=0;
for(int i=0;i<N;){
int flag=0;
for(int j=i+1;j<N&&t[i].dis+Cmax*Davg>=t[j].dis;j++){
if(t[j].price<t[i].price){
cos+=((t[j].dis-t[i].dis)/(Davg+0.0)-left)*t[i].price;
left=0;//走到下一個station時剩餘的油
last=j;
flag=1;
break;
}
}
if(!flag){//沒找到
if(t[i].dis+Cmax*Davg>=D){
cos+=((D-t[i].dis)/(Davg+0.0)-left)*t[i].price;
left=0,flag2=1;
printf("%.2lf",cos);
return 0;
}else{
double minPrice=MAX;
int ind=i;
for(int k=i+1;k<N&&t[i].dis+Cmax*Davg>=t[k].dis;k++){
if(t[k].price<minPrice){
minPrice=t[k].price;
ind=k;
}
}
cos+=(Cmax-left)*t[i].price;
left=Cmax-(t[ind].dis-t[i].dis)/(Davg+0.0);
last=ind;
}
}
i=last;
cnt++;
if(cnt>=N) break;
}
if(!flag2){
printf("The maximum travel distance = %.2lf",t[last].dis+Cmax*Davg+0.0);
}
return 0;
}