POJ 2431

d,p记录当前距离与总油量,初始化就是题目给的值,然后每次从能到达的点中选择一个油量最多的点与p相加,即现在p代表去该点加油后又乘时光机回到原来位置的总油量~

结束条件为:1、没有可以到达加油站了。2、d<=p,即能到终点了。

#include<cstdio>

#include<cstring>

#include<algorithm>

#include<queue>

using namespace std;

struct data

{

    int dis,val;

    bool operator<(const data &next)const

    {

        return val<next.val;

    }

}po[10005];

bool comp(data a,data b)

{

    return a.dis>b.dis;

}

int main()

{

    int n;

    while(scanf("%d",&n)!=EOF)

    {

        for(int i=0;i<n;i++)

            scanf("%d%d",&po[i].dis,&po[i].val);

        int d,p,cnt=0;

        scanf("%d%d",&d,&p);

        sort(po,po+n,comp);

        priority_queue<data> Q;

        int k=0;

        while(k<n&&d-p<=po[k].dis)

            Q.push(po[k++]);

        while(p<d&&!Q.empty())

        {

            cnt++;

            data a=Q.top();

            Q.pop();

            p+=a.val;

            while(k<n&&d-p<=po[k].dis)

                Q.push(po[k++]);

        }

        if(p<d)

            printf("-1\n");

        else

            printf("%d\n",cnt);

    }

    return 0;

}

  

你可能感兴趣的:(poj)