EOJ 1855 【贪心】 【优先队列】

本文探讨了一辆卡车在前往指定距离城镇的过程中,如何通过最少的加油站加油次数来达到目的地的问题。通过贪心算法策略,即在用光油之后选择沿途油量最大的加油站进行补给,最终实现了在给定条件下的最优解。代码实现展示了如何使用优先队列来高效地管理和调度加油站补给过程。

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

/*题目链接*/

题意:一辆卡车要去距离L的城镇,初始油量为P,途中有N个加油站,告诉你每个加油站距城镇的 距离a 和 该加油站的 油量库存b,问你开到城镇的途中最少去几个加油站加油,如果不能到达输出-1。

题目分析: 

既然要加油次数最少,所以在加油站加油一定全部加完。
贪心步骤:1、把油全部用光。
  2、选择路过的加油站中库存最大的加完。
  3、重复1,2直到到达城镇或者无油可加。
实现:用优先队列维护加油站,队列中元素按照油量从大到小排序,行驶过程中将路过的加油站入队,没油后取队首元素加油,队首元素出队,计数器+1。

AC码:

#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <climits>
#include <cassert>
#include <complex>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>


using namespace std;
struct ST
{
    int v;
    int w;
    bool operator < (const ST &a) const
    {
        return a.w>w;
    }
};
bool cmp(const ST a, const ST b)
{
    return a.v>b.v;
}



int main()
{
    int n,L,P,j=0,ans=0;
    ST a[10010];
    priority_queue<ST> q;
    cin >> n;
    for (int i=0; i!=n; ++i)
        scanf("%d%d",&a[i].v,&a[i].w);
    sort(a,a+n,cmp);
    cin >> L >> P;
    while (L>0)
    {
        L -= P;
        P = 0;
        if (L<=0)
            break;
        while (j!=n && a[j].v>=L)
        {
            q.push(a[j]);
            ++j;
        }
        if (!q.empty())
        {
            P += q.top().w;
            q.pop();
            ans++;
        }
        if (P==0 && L>0)
            break;

    }
    if (L<=0)
        cout << ans << endl;
    else
        cout << "-1\n";
    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值