贪心,及优先队列或堆的使用。当路过一个城市或加油站时,不一定需要立刻加油,而可以将其保存在一个优先队列中。当没有油时,再取出优先队列的头加入等量的油,加油的先后是等价的。以加油站为分段点考虑,并将距离转化为距起点的距离。距离需要排序,输入并不保证有序,否则会wrong answer。
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
int n;
struct City
{
int a, b;
}city[10010];
bool cmp(const City& x, const City& y)
{
return x.a < y.a;
}
int l, p;
void solve() // use the priority queue
{
int ans = 0, tank = p, pos = 0;
priority_queue<int> q;
for (int i = 0; i <= n; i++)
{
int d = city[i].a - pos; // distance to next city
while (tank < d) // need to go to the gas station
{
if (q.empty()) // no gas station to use
{
printf("-1\n"); // cannot go to the final city
return;
}
// need to use the gas station
tank += q.top();
ans++;
q.pop();
}
// already get to the next city
tank -= d;
pos = city[i].a;
q.push(city[i].b);
}
printf("%d\n", ans);
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d%d", &city[i].a, &city[i].b);
scanf("%d%d", &l, &p);
for (int i = 0; i < n; i++)
city[i].a = l - city[i].a;
city[n].a = l;
city[n].b = 0;
// without sort will cause wrong answer.
sort(city, city + n + 1, cmp);
solve();
}