1. 程式人生 > >POJ 2431 (優先隊列)

POJ 2431 (優先隊列)

include i++ 鏈接 color 獲得 name com tps 最好

題目鏈接:https://vjudge.net/problem/POJ-2431

思路:

  “ 在卡車行駛途中, 只有經過加油站才能加油。” 我們不妨轉變思路, 理解成“當卡車駛過加油站時就獲得了加油的權利”,在之後需要加油時, 就認為是在之前經過加油站時加的油即可。

  那麽我們何時加油呢, 最好的辦法當然是選擇能加最多油的加油站了(選擇一次加大量的油, 可以減少加油次數),這時就要用到優先隊列了。

  下面是代碼:

 1 #include <cstdio>
 2 #include <iostream>
 3
#include <queue> 4 #include <algorithm> 5 using namespace std; 6 7 struct gas 8 { 9 int dis; 10 int fule; 11 }a[10005]; 12 13 bool cmp(gas A, gas B) 14 { 15 return A.dis<B.dis; 16 } 17 18 priority_queue<int> que; 19 20 int main() 21 { 22 int
n,L,P; 23 cin>>n; 24 for(int i=0; i<n; i++) 25 { 26 cin>>a[i].dis>>a[i].fule; 27 } 28 cin>>L>>P; 29 for(int i=0; i<n; i++) 30 { 31 a[i].dis = L-a[i].dis; 32 } 33 sort(a, a+n, cmp); 34 a[n].dis=L; 35
a[n].fule=0; 36 n++;//關鍵 37 int position=0, count=0, tank=P;//所在位置, 加油次數, 剩余油量 38 for(int i=0; i<n; i++) 39 { 40 int d=a[i].dis - position; 41 while(tank-d<0) 42 { 43 if(que.empty()) 44 { 45 puts("-1"); 46 return 0; 47 } 48 tank += que.top();//加油 49 que.pop(); 50 count++; 51 } 52 tank -= d; 53 position = a[i].dis; 54 que.push(a[i].fule);//關鍵 55 } 56 cout<<count<<endl; 57 58 return 0; 59 }

註釋中的兩個關鍵點要註意, 自己慢慢體會吧。

題外話:

  最近比賽被吊打, 所以準備重新系統性學習。 看到這題是七個月前AC的, 不禁百感交集, 感覺這半年來並沒有怎麽提升啊。 果然還是不夠“刻意練習”!!!

技術分享圖片

POJ 2431 (優先隊列)