poj2431 Expedition 优先队列

来源:互联网 发布:js类库如jquery 编辑:程序博客网 时间:2024/05/21 13:55
 group of cows grabbed a truck and ventured on an expedition deep into the jungle. Being rather poor drivers, the cows unfortunately managed to run over a rock and puncture the truck's fuel tank. The truck now leaks one unit of fuel every unit of distance it travels. 

To repair the truck, the cows need to drive to the nearest town (no more than 1,000,000 units distant) down a long, winding road. On this road, between the town and the current location of the truck, there are N (1 <= N <= 10,000) fuel stops where the cows can stop to acquire additional fuel (1..100 units at each stop). 

The jungle is a dangerous place for humans and is especially dangerous for cows. Therefore, the cows want to make the minimum possible number of stops for fuel on the way to the town. Fortunately, the capacity of the fuel tank on their truck is so large that there is effectively no limit to the amount of fuel it can hold. The truck is currently L units away from the town and has P units of fuel (1 <= P <= 1,000,000). 

Determine the minimum number of stops needed to reach the town, or if the cows cannot reach the town at all. 

题意:某人驾车从A起点到B终点,AB是一条直线,中间有n个加油站,L是长度,P是初始汽车的油量。数据给出的是加油站距终点的距离和加油站能够供给的油量。问最少要加多少次油到终点。不能到则输出-1.

题解:首先先把加油站距终点的距离修改保存为“加油站到起点的距离”,这样便于计算。然后利用优先队列,将走过的路程上面的加油站全部放在队列里面,如果油量空了就取出优先队列中最大的,表示“已经在次加油站加过油”。这样就容易去计算最小的加油次数。

#include<iostream>#include<cstring>#include<cstdlib>#include<cstdio>#include<queue>#include<algorithm>using namespace std;struct node{    int k;    int f;};node a[10005];bool cmp(node a,node b){    return a.k<b.k;}int main(){    int n,l,p,ans;    while(cin>>n)    {        for(int i=0;i<n;i++)        {            cin>>a[i].k>>a[i].f;        }        cin>>l>>p;        for(int i=0;i<n;i++)            a[i].k=l-a[i].k;        a[n].k=l,a[n].f=0;        sort(a,a+n,cmp);//将加油站距起点的距离按照从小到大排列。        priority_queue<int>q;        int tmp=0;//当前位置        ans=0;        int flag;//能否到达终点的标记        for(int i=0;i<=n;i++)        {            flag=0;            int t=a[i].k-tmp;            while(p<t)//如果不能到达下一站,就取队列元素            {                if(q.empty())                {                    cout<<"-1"<<endl;                    flag=1;                    break;                }                else                {                    p+=q.top();                    q.pop();                    ans++;                }            }            p-=t;            tmp=a[i].k;            q.push(a[i].f);            if(flag)                break;        }        if(!flag)            cout<<ans<<endl;    }}