【樹的算法】之求最少加油次數

#include <iostream>
#include <queue>
using namespace std;
/**
 * 原題:一輛卡車需要行駛L單位的距離,開始時卡車有P單位的汽油,每開1單位距離會消耗1單位汽油。
 * 汽油耗盡就無法再行駛,已知一路上有N個加油站,第i個加油站距離起點A[i]個單位,並且可供B[i]單位的汽油。
 * 假設卡車的燃料箱可以容納無限的汽油。問:該卡車是否可以到達終點,如果可以,輸出最小要加多少次油,否則輸出-1
 */
#define L 25
#define P 10
#define N 4

static int A[N+1] = {10,14,20,21};
static int B[N+1] = {10, 5, 2, 4};

/**
 * 思路:
 * 可以用優先隊列來解決(c++的優先隊列取出的是最大值)
 */
void solve(){

    //爲了方便計算,把終點也當成加油站
    A[N] = L;
    B[N] = 0;

    int tank = P;       //燃料箱剩餘汽油量
    int addTime = 0;    //加汽油的次數
    int pos = 0;        //當前離起點的距離

    priority_queue<int> que;

    for (int i = 0; i <= N; ++i) {

        int distance = A[i] - pos;
        tank -= distance;
        while (tank < 0){
            if (que.empty()){
                cout << "-1" << endl;
                return;
            }
            tank += que.top();
            que.pop();
            addTime++;
        }
        que.push(B[i]);
        pos += distance;
    }
    cout << addTime << endl;
}

int main() {
    solve();
    return 0;
}

運行結果:

2



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章