主要参考【贪心】PAT 1033. To Fill or Not to Fill (25)
感觉这样的题目在实际考试中真的要特别熟练掌握贪心算法才能写出来,所以我基本上是照抄的。。。。
#include<cstdio>
#include<algorithm>
using namespace std;
typedef struct {
int pos;
double price;
}gasstation;
gasstation gasst[502];
bool cmp (gasstation a, gasstation b) {
if(a.pos < b.pos)
return true;
return false;
}
int main()
{
int Cmax, D, Davg, N, i;
scanf("%d %d %d %d", &Cmax, &D, &Davg, &N);
for(i=0; i<N; i++)
scanf("%lf %d", &gasst[i].price, &gasst[i].pos);
sort(gasst, gasst + N, cmp);
int cur_station = 0;
double cur_gas = 0;
double cur_cost = 0;
bool arrived = false;
double max_run_dist = Cmax * Davg;
while(!arrived) {
bool has_station = false;
bool has_cheaper = false;
double cheapest_price = 10000;
int cheapest_id;
for(i=cur_station+1; i<N; i++) {
if(gasst[i].pos - gasst[cur_station].pos <= max_run_dist) {
has_station = true;
if(gasst[i].price < gasst[cur_station].price) {
has_cheaper = true;
double dist = gasst[i].pos - gasst[cur_station].pos;
// guarteed to be greater than 0 ?
double needgas = dist / Davg - cur_gas;
cur_gas = 0;
cur_cost += (needgas * gasst[cur_station].price);
cur_station = i;
break;
}
if(gasst[i].price < cheapest_price) {
cheapest_price = gasst[i].price;
cheapest_id = i;
}
}
else
break;
}
if(!has_cheaper && max_run_dist >= (D - gasst[cur_station].pos)) {
double dist = D - gasst[cur_station].pos;
double needgas = dist / Davg - cur_gas;
cur_cost += needgas * gasst[cur_station].price;
printf("%.2lf\n", cur_cost);
return 0;
}
// 肯定是在最便宜的地方加,以为既要达到终点又要加油
if(has_station && !has_cheaper) {
double needgas = Cmax - cur_gas;
cur_cost += needgas * gasst[cur_station].price;
double dist = gasst[cheapest_id].pos - gasst[cur_station].pos;
cur_gas = Cmax - dist / Davg;
cur_station = cheapest_id;
} else if(!has_station) {
printf("The maximum travel distance = %.2lf\n", gasst[cur_station].pos + max_run_dist);
return 0;
}
}
return 0;
}