POJ 2431 Expedition 贪心 + 优先队列

12 篇文章 0 订阅
11 篇文章 0 订阅

POJ 2431 Expedition 贪心 + 优先队列

题意:有一辆车,油箱容量无限,要出发去一个城镇,途中有n个加油站,汽车每行驶一单位距离消耗一单位汽油,每个加油站都有一个最大加油量的限制,你可以选择在任何一个你经过的加油站加油,问在保证能到达城镇的前提下,最少加几次油,当不能到达城镇输出-1;

输入:第一行一个数字 n,表示一个加油站, 第2 到 n+1 行 每行 2 个数字,表示加油站距离城镇的距离 和 加油限度。最后一行 起始汽车距离城镇的距离 和 油量。输入不保证 距离的单调性。

考虑到距离最大才 1000000(100w) 开个数组足够, 于是我用空间复杂度换取时间复杂度。直接桶排加油站,这样在某个距离 有加油站时,那么 d[这个距离] 就不为 0;以此来 确定路过的加油站。把路过的加油站推入优先队列中,如果没油了,就从优先队列中取出最大的油量的加油站加上 ,这样的效果等同于 在路过那个加油站的时候 加上了油。

代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;

const int MAXN = 1000000 + 10;
int dis[MAXN];

priority_queue <int> q;

int main()
{
    int n;
    scanf("%d",&n);
    for(int i = 1; i <= n; i ++)
    {
        int a, b;
        scanf("%d%d",&a,&b);
        dis[a] = b;
    }
    int L, P, ans = 0;
    scanf("%d%d",&L, &P);
    while(L > 0)
    {
        if(dis[L])
            q.push(dis[L]);
        if(!P)
        {
            if(!q.empty())
            {
                P += q.top();
                q.pop();
                ans ++;
            }
            else{
                puts("-1");
                return 0;
            }
        }
        P --;
        L --;
    }
    printf("%d\n",ans);
    return 0;
}

还有一种解法就是 用数组记录 加油站,然后排序。
评测结果的话这个比较优。

代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;

const int MAXN = 10000 + 10;
struct Gas_Station{
    int l, p;
}gas[MAXN];

priority_queue <int> q;

bool cmp(Gas_Station a, Gas_Station b)
{
    return a.l > b.l;
}

int main()
{
    int n;
    scanf("%d",&n);
    for(int i = 1; i <= n; i ++)
        scanf("%d%d", &gas[i].l, &gas[i].p);
    sort(gas+1, gas+n+1, cmp);
    int L, P, ans = 0, cnt = 1;
    scanf("%d%d",&L, &P);
    while(L > 0)
    {
        if(L == gas[cnt].l)
        {
            q.push(gas[cnt].p);
            cnt ++;
        }
        if(!P)
        {
            if(!q.empty())
            {
                P += q.top();
                q.pop();
                ans ++;
            }
            else{
                puts("-1");
                return 0;
            }
        }
        P --;
        L --;
    }
    printf("%d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值