poj2431(優先隊列+貪心)


題目鏈接http://poj.org/problem?id=2431

題目大意:一輛卡車,初始時,距離終點L,油量為P,在起點到終點途中有n個加油站,每個加油站油量有限,而卡車的油箱容量無限,卡車在行車途中,每走一個單位的距離消耗一個單位的油量,給定n個加油站距離終點的距離以及油存儲量。問卡車是否能到達終點,如果可達,最少需要加多少次油,否則輸出-1.

例:

輸入:

4
4 4
5 2
11 5
15 10
25 10

輸出:

2

 

解題思路:采用貪心的思想,卡車當然在不加油的情況下走的越遠越好了,而當它沒油時,我們再判斷卡車在經過的途中的加油站,哪個加油站加的油最多,選油量最多的,這樣后面加油次數也越少,然后又繼續行駛,當它又沒油了的時候,繼續選它從起點到該點所經過的加油站油量最多的加油。

 

做法先將加油站到終點的距離由遠到近排下序,這樣離起點就是由近到遠。就是每經過一個加油站就將該加油站的油量壓入優先隊列中,然后每次沒油的時候,去隊首元素加油即可。

附上代碼:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<queue>
 6 using namespace std;  7 int n,l,p;  8 struct node{  9     int dis; 10     int fuel; 11     bool operator<(const node &a)const
12  { 13         return dis>a.dis; 14  } 15 }stop[10005]; 16 priority_queue<int> que; 17 
18 int main() 19 { 20     cin>>n; 21     for(int i=0;i<n;i++) 22         cin>>stop[i].dis>>stop[i].fuel; 23     cin>>l>>p; 24     int ans=0; 25     sort(stop,stop+n); 26  que.push(p); 27     int temp=0; 28     while(l>0&&!que.empty()) 29  { 30         ans++; 31         l-=que.top();  //加油 
32  que.pop(); 33         while(l<=stop[temp].dis&&temp<n)  //將經過的加油站壓入優先隊列中 
34             que.push(stop[temp++].fuel); 35  } 36     if(l>0) cout<<"-1"<<endl;  //l>0說明到不了終點 
37     else cout<<ans-1<<endl;  //減去1初始時油箱的油也被計算成一次加油了 
38     return 0; 39 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM