这是一道贪心算法的题目,因为题目要求花费最低,所以我想到区间贪心的思想,那么首先要将各个加油站的费用从小到大排序,然后根据汽车最多能走的距离计算所需要的花费,再将这些区间的花费加起来即可:
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXDIS = 30000 + 10;
const int MAXN = 500 + 10;
struct Station{
double price;
double distance;
Station(){}
Station(double p, double d): price(p), distance(d){}
};
Station arr[MAXN];
int d[MAXDIS];
bool cmp(Station x, Station y){
return x.price <= y.price;
}
int main(){
int Cmax, D, Davg, n;
while(scanf("%d%d%d%d", &Cmax, &D, &Davg, &n) != EOF){
for(int i = 0;i < n;i++) scanf("%lf %lf", &arr[i].price, &arr[i].distance);
sort(arr, arr + n, cmp);
fill(d, d + D, 0);
int max = Cmax * Davg; //加满油能走的最远距离
double total = 0.0; //记录总花费
for(int i = 0;i < n;i++){
int sum = 0;
int bound;
if(arr[i].distance + max > D) bound = D;
else bound = arr[i].distance + max;
for(int j = arr[i].distance;j < bound;j++){
if(!d[j]){
d[j] = 1;
sum++;
}
}
total += sum * arr[i].price / Davg;
}
int i;
for(i = 0;i <= D;i++){
if(!d[i]) break;
}
if(i < D) printf("The maximum travel distance = %.2lf\n", double(i));
else printf("%.2lf\n", total);
}
return 0;
}