1033. 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:

Each input file contains one test case. For each case, the first line contains 4 positive numbers: Cmax(<= 100), the maximum capacity of the tank; D (<=30000), the distance between Hangzhou and the destination city; Davg(<=20), the average distance per unit gas that the car can run; and N (<= 500), the total number of gas stations. Then N lines follow, each contains a pair of non-negative numbers: Pi, the unit gas price, and Di(<=D), the distance between this station and Hangzhou, for i=1,…N. All the numbers in a line are separated by a space.

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.

纠结了我一下午,总算是各种加加减减搞清楚了

#include <stdio.h>#include <stdlib.h>#include <vector>#include <algorithm>using namespace std;typedef struct{float price;int dis,period;}Gas;vector<Gas> gas;float sum;bool cmp (Gas a,Gas b);int main (){int cop,distance,per,num,i;scanf("%d %d %d %d",&cop,&distance,&per,&num);Gas temp;int far=cop*per;//最多跑多远吗for( i=0;i<num;i++){scanf("%f %d",&temp.price,&temp.dis);gas.push_back(temp);}sort(gas.begin(),gas.end(),cmp);sum=0.0f;if( gas[0].dis!=0){printf("The maximum travel distance = %.2f\n",sum);return 0;}for( i=0;i<num-1;i++){gas[i].period=gas[i+1].dis-gas[i].dis;if( gas[i].period>far){sum+=far;printf("The maximum travel distance = %.2f\n",sum);return 0;}sum+=gas[i].period;}gas[i].period=distance-gas[i].dis;if( gas[i].period>far){sum+=far;printf("The maximum travel distance = %.2f\n",sum);return 0;} // sum+=gas[i].period;float cost,min=gas[0].price;//最小的价格int now,left;now=gas[0].period;sum=now;//当前走的总路程left=far-gas[0].period;//还可以走的路程cost=now*gas[0].price;//在这个站的花费for( i=1;i<num;i++){if( gas[i].price<=min)//在这个站加油{min=gas[i].price;//更新最小价格now=gas[i].period;left=far-now;cost+=now*gas[i].price;}else{if( gas[i].period<=left)//继续之前的加油{now+=gas[i].period;left=far-now;cost+=gas[i].period*min;}else//开始新的加油{cost+=left*min;min=gas[i].price;now=(gas[i].period-left);cost+=gas[i].price*now;left=left-now;}}}printf("%.2f\n",cost/per);system("pause");return 0;}bool cmp (Gas a,Gas b){return a.dis<b.dis;}

,木已成舟便要顺其自然

1033. To Fill or Not to Fill

相关文章:

你感兴趣的文章:

标签云: