poj 2431 Expedition

本文通过使用贪心算法解决了一个实际问题:如何在有限的油量下,找到最少的加油次数来完成旅程。具体步骤包括创建一个最大堆来存储经过的加油站的油量,并在每个加油站进行最优选择,即尽可能加最多的油。为了简化代码,添加了一个虚拟的起点加油站。通过实例演示和代码实现,详细解释了贪心策略的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

求最少的加油次数,贪心的思想每次加油都尽可能加多的油。所以经过的加油站的油存在一个最大堆里,加油后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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值