现在的位置: 首页 > 综合 > 正文

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

2013年09月03日 ⁄ 综合 ⁄ 共 779字 ⁄ 字号 评论关闭

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4006

这个题目其实比较简单,如果能想到优先队列一下子就搞定了,如果想不到,可能有点麻烦

这个题目这样做,首先开始查询的时候一定有K个元素,始终维护第K大元素ans,如果当前

要插入的一个值比ans小,那么不用插入,肯定不会成为第K大,如果比ans大,那么弹出队

顶元素,插入这个元素,更新ans为队顶元素

注意:每次使用完优先队列之后记得清空

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <queue>
using namespace std;
struct myComp
{
bool operator()(const int &a,const int &b)
{
//由小到大排列采用“>”号;如果要由大到小排列,则采用“<”号
return a>b;
}
};

priority_queue<int,vector<int>,myComp> q;
int main()
{
    int n,k,i,a,ans=-1;
    char ch;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        ans=-1;
        for(i=0;i<k;i++)
        {
            getchar();
            scanf("%c%d",&ch,&a);
            q.push(a);
        }
        ans=q.top();
        //printf("K:%d\n",ans);
        for(i;i<n;i++)
        {
            getchar();
            scanf("%c",&ch);
            if(ch=='Q')
            {
                printf("%d\n",ans);
                continue;
            }
            scanf("%d",&a);
            if(a>ans)
            {
                q.pop();
                q.push(a);
                ans=q.top();
            }
        }
        while(!q.empty())
        q.pop();
    }
    return 0;
}

抱歉!评论已关闭.