优先队列

C++中有优先队列的模版。

于是用了一下,对a排了个序,Ac了。

代码如下:

 

#include <stdio.h>
#include <queue>
#include <stdlib.h>
#include <algorithm>
using namespace std;

struct s
{
    int a;
    int b;
}pr[100005];

int cmp1(struct s a,struct s b)
{
    return a.a < b.a;
}

int main()
{
    int n,m,i,j,k,p;
    while(scanf("%d%d%d",&n,&m,&p) != EOF)
    {
        for(i = 0;i < n;i++)
            scanf("%d%d",&pr[i].a,&pr[i].b);
        sort(pr,pr+n,cmp1);
        priority_queue <int> q;
        q.push(0);
        i = 0;
        while(m--)
        {
            for(;i < n;i++)
                if(pr[i].a <= p)
                    q.push(pr[i].b);
                else
                    break;
            if(q.empty()) break;
            p += q.top();
            q.pop();
        }
        while(!q.empty()) q.pop();
        printf("%d/n",p);
    }
    return 0;
}

 

 

最后判断队列为空的那一句非常重要。如果没写的话会超内存。

 

系统默认是最大堆,如果要实现最小堆,应该如下写:

 

struct cmp1{
       bool operator ()(const int &i,const int &j){
            return j>i;     //最小堆只要把i>j;
         }
};

priority_queue < int, vector < int >, cmp1 > q;

 

post by: Kiswell

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值