不加target==n这个条件测试点1会出现超时=皿=没找到原因。
很有价值的贪心题目!
#include <stdio.h>
#define INFINITY 10000
/*有时候不用加满油,只要加够向终点的油即可*/
typedef struct Station {
float price;
float dist;
}Station;
Station GasS[501];
int FindTarget(int loc, float MaxDist,int n);
int main()
{
int n,i,j,loc,target;
float StationP, StationD, gas = 0, MaxDist, cost = 0,cpct, D, Davg;
scanf("%f %f %f %d", &cpct, &D, &Davg, &n);
for (i = 0; i < n; i++) {
scanf("%f %f", &StationP, &StationD);
j = i;
while(j>0&& (GasS[j - 1].dist>StationD)) {
GasS[j].dist = GasS[j - 1].dist;
GasS[j].price = GasS[j - 1].price;
j--;
}
GasS[j].dist = StationD;
GasS[j].price = StationP;;
}
GasS[n].dist = D;
GasS[n].price = 0;/*添加终点*/
if (GasS[0].dist != 0) {
printf("The maximum travel distance = 0.00");
return 0;
}
loc = 0;
MaxDist = Davg*cpct;/*加满油时可行驶的最大距离*/
while (1) {
target = FindTarget(loc,MaxDist, n);
if(target==-1||target==n)/*loc==最后一个加油站*/
if (MaxDist >= D - GasS[loc].dist) {
cost += ((D - GasS[loc].dist) / Davg - gas)*GasS[loc].price;
printf("%0.2f", cost);
break;
}else {
printf("The maximum travel distance = %0.2f", GasS[loc].dist + MaxDist);
break;
}
else if (GasS[target].price < GasS[loc].price) {/*加最少的油开过去,*/
if (gas < (GasS[target].dist - GasS[loc].dist) / Davg) {/*油箱油不够*/
cost += ((GasS[target].dist - GasS[loc].dist) / Davg - gas)*GasS[loc].price;
gas = 0;/*到目的站时油箱已空*/
}
else
gas -= (GasS[target].dist - GasS[loc].dist) / Davg;
}else {
cost += (cpct - gas)*GasS[loc].price;
gas =cpct- (GasS[target].dist - GasS[loc].dist) / Davg;
}
loc = target;
}
return 0;
}
int FindTarget(int loc, float MaxDist,int n)
{
int target,Min=-1;
float MinPrice = INFINITY;
for (target = loc + 1; target < n+1; target++) {
if (GasS[target].dist > GasS[loc].dist + MaxDist)
break;
if (GasS[target].price < GasS[loc].price)
return target;
if (GasS[target].price < MinPrice) {
MinPrice = GasS[target].price;
Min = target;
}
}
return Min;
}