poj

http://poj.org/problem?id=2431

你需要驾驶一辆卡车做一次长途旅行,但是卡车每走一单位就会消耗掉一单位的油,如果没有油就走不了,为了修复卡车,卡车需要被开到距离最近的城镇,在当前位置和城镇之间有n个加油站可以加油。

为了减少危险,需要最少的加油次数,卡车的油箱可以看作无限大,卡车初始距离城镇L单位,自身有P单位的油。

注意输入的距离是与城镇的距离不是与开始点的距离。转换一下就好。

思想:把经过的所有加油站都加入优先队列,当燃料不足时就取出优先队列的最大元素,用来给卡车加油,如果优先队列也是空的,就不能到达终点。

#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 10000 + 10;
int L, P, N;
struct node
{
    int x,y;  //x是与初始点的距离   y是这个加油站有多少油
    bool operator < (const node &a) const
    {
        return x < a.x;  //按与初始点的距离排序
    }
}f[maxn];

void solve() {
    f[N].x = L;  //把终点也加入,但是油 为0  为了方便处理
    f[N].y = 0;
    N++;

    priority_queue<int> que;

    int ans = 0, pos = 0, tank = P;  // ans: 加油次数  , pos:现在所在位置  ,tank:邮箱中汽油的量 
    for(int i = 0; i < N; i++) {
        int d = f[i].x - pos;  //接下来要前进的距离
        while(tank - d < 0) {   //如果油不够 就不断加油
            if(que.empty()) {
                puts("-1");
                return;
            }
            tank += que.top();
            que.pop();
            ans++;
        }
        tank -= d;
        pos = f[i].x;
        que.push(f[i].y);
    }
    printf("%d
", ans);
}

int main()
{
    scanf("%d",&N);
    for(int i = 0; i < N; i++) {
        scanf("%d%d",&f[i].x,&f[i].y);
    }
    scanf("%d%d",&L,&P);
    for(int i = 0; i < N; i++) {
        f[i].x = L - f[i].x;
    }
    sort(f,f+N);
    solve();
    return 0;
}
原文地址:https://www.cnblogs.com/nowandforever/p/4480102.html