poj 2431 Expedition

求最少的加油次數,貪心的思想每次加油都儘可能加多的油。所以經過的加油站的油存在一個最大堆裏,加油後pop()

在poj 3253裏實現過堆了,就用了priority_queue

一個讓代碼稍微簡潔一些的技巧是添加第N+1個加油站,距離0, 油量0


/*
PROG: Expedition
LANG: C++11 
*/
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <climits>
#include <ctype.h>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <deque>
#include <set>
#include <map>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <time.h>

using namespace std;
#define mst(a,b) memset(a,b,sizeof(a))

typedef long long ll;
const int N = 100010;
const ll MOD = 1000000007;
const int INF = 0x7fffffff;

struct node{
    int a;
    int b;
} st[N];

bool cmp(node n1, node n2){
    return n1.a < n2.a;
}

int main()
{
    int n, i, L, P;
    cin >> n;
    for(i = 0; i < n; i++){
        scanf("%d%d", &st[i].a, &st[i].b);
    }
    cin >> L >> P;
    for(i = 0; i < n; i++){
        st[i].a = L - st[i].a;
    }
    st[n].a = L; st[n].b = 0;
    sort(st, st+n, cmp);
    priority_queue<int> pqueue;
    int rem = P, cnt = 0;
    for(i = 0; i <= n ; i++){
        if(st[i].a <= rem){
            pqueue.push(st[i].b);
        }
        else{
            // 選油多的加油站加油,一直到夠到達這個加油站爲止
            while(!pqueue.empty() && rem < st[i].a){
                rem += pqueue.top();
                pqueue.pop();
                cnt++;
            }
            if(rem < st[i].a){
                cout << -1 << endl;
                return 0;
            }
            else{
                pqueue.push(st[i].b);
            }
        }
    }
    cout << cnt << endl;

    return 0;
}


發佈了46 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章