1. 程式人生 > >POJ2431-Expedition【優先佇列+貪心】

POJ2431-Expedition【優先佇列+貪心】

題目大意:卡車每走一公里就消耗一單位的汽油,初始時給你p單位油,你要到達l距離的終點。其中路上有n個補給點可以加油,並且油箱容量無限大,問你最少可以停車幾次。

思路:因為油箱無限大,所以我們可以這麼認為,我們路過一個加油站之後,我們在之後的路上隨時可以選擇加那個加油站的油,而且肯定是一次加完B_i,所以我們從汽車初始狀態開始開,到沒油了,看看路上路過有加油站沒,選路過過油最多的,加上,繼續這樣。最後加油次數一定是最少的

#include<cstdio>
#include<queue>
#include <iostream>
#include<algorithm>
using namespace std;
const int maxn=10005;
struct node
{
    int d,f;
};
node a[maxn];

bool cmp(node x,node y)
{
    return x.d>y.d;
}
int main()
{
    int n,l,p;
    while(scanf("%d",&n)!=EOF)
    {
        priority_queue<int> q;
        for(int i=0;i<n;++i)
            scanf("%d%d",&a[i].d,&a[i].f);
        sort(a,a+n,cmp);
        scanf("%d%d",&l,&p);
        int ans=0;
        q.push(p);
        int index=0;
        while(l>0 && !q.empty())
        {
            ++ans;
            int temp=q.top();
            q.pop();
            l-=temp;
            while(index<n && l<=a[index].d)
            {
                q.push(a[index].f);
                ++index;
            }
        }
        if(l<=0)
            printf("%d\n",ans-1);
        else
            printf("-1\n");
    }
    return 0;
}