poj2431

本文地址:https://www.cnblogs.com/maplefighting/p/9119685.html

题目名称:Expedition

链接:http://poj.org/problem?id=2431

题意:有一辆卡车需要行驶 L 单位的距离,刚开始有 P 单位的油,每行驶 1 单位需要消耗 1 单位的油。路上有 N 个加油站,距离终点距离 Ai,能提供最多 Bi 单位的油。输出最少加油次数,若无法到达,输出 -1

思路:卡车在中途需要加油时,我们可以认为他可以之前经过没油加过油的加油站加,而且贪心的想,我们要加那个油量 Bi 最多的。

代码如下:

 1 #include<cstdio>
 2 #include<queue>
 3 #include<algorithm>
 4 using namespace std;
 5 typedef long long LL;
 6 struct Fuel {
 7     int a,b;
 8 } fuel[10005];
 9 bool cmp(Fuel a1,Fuel a2) {
10     return a1.a > a2.a;
11 }
12 int main() {
13     int n;
14     scanf("%d", &n);
15     for(int i = 1; i <= n; ++i) {
16         scanf("%d%d", &fuel[i].a, &fuel[i].b);
17     }
18     sort(fuel + 1, fuel + n + 1, cmp); //将数据从起点到终点排序
19     int L, P;
20     scanf("%d%d", &L, &P);
21     int tt = P;
22     n++;
23     fuel[0].a = L;
24     fuel[n].a = fuel[n].b = 0;
25     int sum = 0;
26     priority_queue<int> que;
27     for(int i = 1; i <= n; ++i) {
28         int d = fuel[i - 1].a - fuel[i].a;//printf("%d %d\n",fuel[i].a,fuel[i].b);
29       //
30         while(tt - d < 0) {
31             if(que.empty()) {
32                 puts("-1");
33                 return 0;
34             }
35             tt += que.top();
36             que.pop();
37             sum++;
38         }
39         tt -= d;
40         if(i != n){
41             que.push(fuel[i].b);
42         }
43     }
44     printf("%d\n", sum);
45     return 0;
46 }
View Code

猜你喜欢

转载自www.cnblogs.com/maplefighting/p/9119685.html