poj 2051 priority_queue应用

题意:每一行输入一个编号,再给定它每一次出现的间隔时间,最后以“#”结束。之后是m次查询,根据他们出现的时间从早到晚把前m个编号打印出来,若在同一时间有多个编号,那么先输出小的编号。

思路:用优先队列维护时间点,每次堆中最小的输出,然后加上间隔再push进去即可。小于号重载的写法总是记不住,希望这次能够记住。两种写法:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <cstdlib>
using namespace std;
#define clc(s,t) memset(s,t,sizeof(s))
#define INF 0x3fffffff
#define N 1005
struct node{
    int id,t,num;
    bool operator<(const node &b) const {
        if(t == b.t)
            return id>b.id;
        return t>b.t;
    }
}p[N];
priority_queue<struct node> h;
int n,m;
int main(){
    int i = 0;
    char s[15];
    while(scanf("%s",s) && strcmp(s,"#")){
        scanf("%d %d\n",&p[i].id,&p[i].t);
        p[i].num = i;
        h.push(p[i++]);
    }
    scanf("%d",&m);
    while(m--){
        struct node tmp = h.top();
        printf("%d\n",tmp.id);
        h.pop();
        tmp.t += p[tmp.num].t;
        h.push(tmp);
    }
}

这样写也可以:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <cstdlib>
using namespace std;
#define clc(s,t) memset(s,t,sizeof(s))
#define INF 0x3fffffff
#define N 1005
struct node{
    int id,t,num;
    
}p[N];
bool operator<(node a,node b){
    if(a.t == b.t)
        return a.id>b.id;
    return a.t>b.t;
}
priority_queue<struct node> h;
int n,m;
int main(){
    int i = 0;
    char s[15];
    while(scanf("%s",s) && strcmp(s,"#")){
        scanf("%d %d\n",&p[i].id,&p[i].t);
        p[i].num = i;
        h.push(p[i++]);
    }
    scanf("%d",&m);
    while(m--){
        struct node tmp = h.top();
        printf("%d\n",tmp.id);
        h.pop();
        tmp.t += p[tmp.num].t;
        h.push(tmp);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值