hdu4006 The kth great number(优先队列)

本文分享了一次使用优先队列解决编程问题的经历,详细记录从最初思路到最终实现的过程,包括如何避免超时错误及代码优化技巧。

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

可喜可贺!终于按照自己的想法A了第一道优先队列题,虽然WA了4次,但还是很开心吐舌头

刚开始想输出第三大数,那每次输出的时候都把第k个以前的都存起来出队列,输出第k个后再入队列回去,后来果断超时(噗)。

然后就想干脆只弄k个有效值,队列满了k个就和队首判断然后输出,中间还有几次失误,不过还好A了~

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

const int N = 5000;
const int INF = 1000000;

struct node
{
    int w;
    friend bool operator < (const node &a, const node &b)
    {
        return a.w > b.w;
    }
};

int main()
{
  //  freopen("in.txt", "r", stdin);
    char a[3];
    int n, k, num;
    while(~scanf("%d%d", &n, &k))
    {
        priority_queue <node> q;
        while(n --)
        {
            cin >> a;
            if(a[0] == 'I')
            {
                if(q.size() >= k)//等于不可去掉
                {
                    node jud = q.top();
                    scanf("%d", &num);
                    node tmp;
                    tmp.w = num;
                    if(tmp.w > jud.w)
                    {
                        q.push(tmp);
                        q.pop();
                    }
                }
                else
                {
                    node tmp;
                    scanf("%d", &num);
                    tmp.w = num;
                    q.push(tmp);
                }
            }
            else if(a[0] == 'Q')
            {
                node tmp1 = q.top();
                printf("%d\n", tmp1.w);
            }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值