首页 > 代码库 > PAT 1033. To Fill or Not to Fill
PAT 1033. To Fill or Not to Fill
#include <cstdio>#include <cstdlib>#include <vector>#include <algorithm>using namespace std;int main() { int N; double mcap, dist, davg; scanf("%lf%lf%lf%d", &mcap, &dist, &davg, &N); double price, idist; vector<pair<double, double> > stations(N + 1); for (int i=0; i<N; i++) { scanf("%lf%lf", &price, &idist); stations[i].first = idist; stations[i].second= price; } // virtual station to indicate the end stations[N].first = dist; stations[N].second= 1e300; sort(stations.begin(), stations.end()); double tank = 0, cur_dist = 0, cur_price = 0; if (stations[0].first > 0) { printf("The maximum travel distance = %.2lf", cur_dist); return 0; } double money = 0; int cur_stat = 0; int cheap_stat = -1; double cheap_price = 0; while (cur_dist < dist && (cur_stat) < N) { double next_dist = stations[cur_stat + 1].first; double max_dist = mcap * davg + cur_dist; // can‘t reach next station if (max_dist < next_dist) { cur_dist = max_dist; break; } // can reach next station // find first min gas price from cur_stat/cheap_stat within the reach range if (cheap_stat < cur_stat) { // last cheap station we calculated has past by cheap_stat = cur_stat; cheap_price= stations[cur_stat].second; } for (int i=cheap_stat; i<N && stations[i].first <= max_dist; i++) { if (stations[i].second < cheap_price) { cheap_stat = i; cheap_price= stations[i].second; break; } } // cheaper station is cur_stat if (cheap_stat == cur_stat) { // from here we can reach end station if (max_dist >= dist) { money += cheap_price * (dist - cur_dist) / davg; cur_dist = dist; break; } // can‘t reach the end station // we should fill full tank money += (mcap - tank) * cheap_price; tank = mcap; } else { // cur_stat is not the cheaper station, // just fill enough gas, go to the cheaper one double gas_need = (stations[cheap_stat].first - cur_dist) / davg; if (gas_need > tank) { // we have to fill gas here money += (gas_need - tank) * stations[cur_stat].second; tank = gas_need; } else { // we have the enough gas already } } // now we have enough gas // drive to the next station tank -= (next_dist - cur_dist) / davg; cur_stat++; cur_dist = next_dist; } if (cur_dist < dist) { printf("The maximum travel distance = %.2lf", cur_dist); } else { printf("%.2lf", money); } return 0;}
写得有点烦
PAT 1033. To Fill or Not to Fill
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。