Heap:Expedition(POJ 2431)

                  

                  远征队

  题目大意:一部车要从一个地方走到另一个地方,开始的时候车的油箱有P升油,汽车每走1个距离消耗1升油,没有油汽车无法行驶,路上有加油站,可以为汽车加油,设汽车的油缸是无限大小的,问你汽车能否走到终点?如果可以,需要用到最小的加油站的数目是多少?

  这一题可以这么理解,因为我们只用最小的加油站数目,那么我们可以只用每次都加最大油量就可以了,我们可以认为汽车经过的加油站都像势能一样储存起来,随时可以加油

  那么这样过后,我们只用维护一个最大堆就可以了,也算是一个贪婪算法吧

  

 1 #include <iostream>
 2 #include <functional>
 3 #include <queue>
 4 #define MAX_N 10001
 5 
 6 using namespace std;
 7 
 8 typedef struct gas
 9 {
10     int gas_pos;
11     int gas_sum;
12 }GS;
13 
14 GS state[MAX_N];
15 void Search(const int, const int, const int);
16 int fcmop(const void *a, const void *b)
17 {
18     return (*(GS *)b).gas_pos - (*(GS *)a).gas_pos;
19 }
20 
21 int main(void)
22 {
23     int N, L, P;
24     while (~scanf("%d", &N))
25     {
26         for (int i = 0; i < N; i++)//读入加油站的油量
27             scanf("%d%d", &state[i].gas_pos, &state[i].gas_sum);
28         scanf("%d%d", &L, &P);
29         state[N].gas_pos = 0; state[N].gas_sum = 0;//把终点看成油站
30         qsort(state, N, sizeof(GS), fcmop);//记得成从远到近(距离终点)
31         Search(L, N, P);
32     }
33     return 0;
34 }
35 
36 void Search(const int L, const int N, const int P)
37 {
38     priority_queue < int, vector<int>, less<int> > que;
39     int i, ans = 0, tank = P, now_state = 0 , dist;
40 
41     for (i = 0; i <= N; i++)
42     {
43         dist = (L - state[i].gas_pos) - now_state;//下一个油站到现在的距离
44         while (tank - dist < 0)//如果不支持到
45         {
46             if (que.empty())//没有油站给加油了,直接不能走到终点
47             {
48                 cout << -1 << endl;
49                 return;
50             }
51             tank += que.top();
52             que.pop();
53             ans++;
54         }
55         que.push(state[i].gas_sum);//相当于是势能,储存起来
56         tank -= dist;
57         now_state = (L - state[i].gas_pos);
58     }
59     cout << ans << endl;
60 }
原文地址:https://www.cnblogs.com/Philip-Tell-Truth/p/4851756.html