HDU 4006 The kth great number (优先队列)

题目链接

题意:n次操作,每次可以用 I 表示写入一个数,或者用 Q 表示询问第k大的数是多少。

题解:优先队列,只保留前k大的数。

#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
typedef long long ll;
int main()
{
    ll n,k,num;
    char s[15];
    while(scanf("%lld%lld",&n,&k)!=EOF)
    {
        priority_queue<ll,vector<ll>,greater<ll> >q;
        while(n--)
        {
            scanf("%s",s);
            if(s[0]=='I')
            {
                scanf("%lld",&num);
                q.push(num);
                if(q.size()>k) q.pop();
            }
            else printf("%lld
",q.top());
        }
    }
    return 0;
}

优先队列底层是堆来实现的,map、set底层是红黑树。 

注意优先队列默认是大的先出 就是 1 2 3 4 5 6 这样 ,然后 6 是队头,1是队尾。

和数组正好是反过来的,可以说是大于号小于号反过来了,更好的方法就说是队头和队尾反过来了,因为数组一般认为0是开头嘛。

另外注意优先队列队头我们称之为优先级最高的元素叫top,附上一个队列和优先队列的链接:传送门

#include <bits/stdc++.h>
using namespace std;
struct node
{
    int x;
    friend bool operator < (node a,node b)
    {
        return a.x<b.x;
        //小于就是默认的 1 2 3 4 5 6 然后6先出去 小于号是大根堆
        //大于就是6 4 5 3 2 1 然后1先出去 大于号是小根堆
    }
};
int main()
{
    priority_queue<node> q;
    node a[5];
    a[1].x=1;a[2].x=2;a[3].x=3;
    a[4].x=4;
    q.push(a[4]);
    q.push(a[1]);
    q.push(a[2]);
    q.push(a[3]);
    q.pop();
    for(int i=0;i<3;i++){
        printf("%d
",q.top());
        q.pop();
    }
    return 0;
}

个人感觉这个和结构体sort cmp 这种比的话优点就是动态插入删除都是logn,而sortcmp是nlogn。

原文地址:https://www.cnblogs.com/Ritchie/p/5765655.html