您的位置:首页 > 其它

【POJ】2431-Expedition 优先队列+贪心

2017-10-31 11:22 357 查看
http://poj.org/problem?id=2431

车要行驶L单位距离。车上有P单位汽油,行驶1单位距离消耗1单位汽油。汽油耗尽车就无法继续前行。途中共有N个加油站,卡车的油箱无限大。给出每个加油站距离终点的距离和提供的油量,问卡车从起点到终点至少要加几次油?如果不能到达终点,输出-1。

由于N比较大,应该找一个高效的解法。稍微转换一下思考方式:在卡车开往终点的途中,只有在加油站才可以加油。但是,如果认为“在到达加油站i时,就获得了一次在之后的任何时候都可以加Bi单位汽油的权利”,在解决问题上也是一样的。而在之后需要加油时,就认为是在之前经过的加油站加的油就可以了。因为希望加油次数尽可能少,所以当燃料为0了之后再加油是最好的选择。基于贪心的思想,当燃料为0时,选择能加油量最大的加油站。所以可以用一个优先队列来保存经过的加油站的油量,当需要加油时,取出队列中的最大元素即可。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;

const int maxn=10005;

struct node{
int dis;
int fue;
}p[maxn];

int n,l,P;

bool cmp(struct node a,struct node b){
return a.dis>b.dis;
}

int main(){

cin >> n;
for (int i=0;i<n;i++){
cin >> p[i].dis >> p[i].fue;
}
sort(p,p+n,cmp);

cin >> l >> P;

priority_queue <int> q;
int num=0;
int index=0;
q.push(P);
while (l>0&&!q.empty()){
num++;
int now=q.top();
q.pop();
l-=now;
while (index<n&&l<=p[index].dis){
q.push(p[index++].fue);
}
}

if (l<=0) cout << num-1 << endl;
else cout << "-1" << endl;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: