码迷,mamicode.com
首页 > 其他好文 > 详细

URAL 1306 Sequence Median(优先队列)

时间:2014-08-04 13:29:27      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   for   art   

题意:求一串数字里的中位数。内存为1M。每个数范围是0到2的31次方-1。

思路:很容易想到把数字全部读入,然后排序,但是会超内存。用计数排序但是数又太大。由于我们只需要第n/2、n/2+1大(n为偶数)或第(n+1)/2大(n为奇数)。所以可以用优先队列来维护最值,这样只需要存一半元素(n/2+1个元素)就可以了。

bubuko.com,布布扣
#include<cstdio>
#include<algorithm>
#include<queue>
#define UL unsigned int
using namespace std;
priority_queue<UL> que;
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        while(!que.empty()) que.pop();
        {
            UL a;
            for(int i=0; i<=n/2; ++i)
            {

                scanf("%u",&a);
                que.push(a);
            }
            for(int i=n/2+1; i<n; ++i)
            {
                scanf("%u",&a);
                if(!que.empty()&&a<=que.top())
                {
                    que.pop();
                    que.push(a);
                }
            }
            if(n&1)
                printf("%u",que.top());
            else
            {
                UL a=que.top();
                que.pop();
                UL b=que.top();
                printf("%.1f\n",(a+b)/2.0);
            }
        }
    }
    return 0;
}
View Code

 

URAL 1306 Sequence Median(优先队列),布布扣,bubuko.com

URAL 1306 Sequence Median(优先队列)

标签:style   blog   http   color   os   io   for   art   

原文地址:http://www.cnblogs.com/kkkwjx/p/3889644.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!