URAL1306--Sequence Median(优先队列)

 Sequence Median

Time limit: 1.0 second
Memory limit: 1 MB
Language limit: C, C++, Pascal
Given a sequence of  N nonnegative integers. Let's define the median of such sequence. If  N is odd the median is the element with stands in the middle of the sequence after it is sorted. One may notice that in this case the median has position ( N+1)/2 in sorted sequence if sequence elements are numbered starting with 1. If  N is even then the median is the semi-sum of the two "middle" elements of sorted sequence. I.e. semi-sum of the elements in positions  N/2 and ( N/2)+1 of sorted sequence. But original sequence might be unsorted.
Your task is to write program to find the median of given sequence.

Input

The first line of input contains the only integer number  N — the length of the sequence. Sequence itself follows in subsequent lines, one number in a line. The length of the sequence lies in the range from 1 to 250000. Each element of the sequence is a positive integer not greater than 2 31−1 inclusive.

Output

You should print the value of the median with exactly one digit after decimal point.

Sample

input output
4
3
6
4
5
4.5


题意:求中位数,如果n为偶数,则输出( 默认sort后):N/2+(N/2)+1/2 ;

            如果n为奇数,则输出N/2即可。

初一看,这道题貌似很水的样子,我直接sort了一下,超内存了,然后看了一下给的内存,才1M惊恐。 光开数组就差不多了1000+kB, 然后想用unsigned int 还是超内存了,不过现在已经到了1036KB了,已经没办法优化了,然后就放弃开这么大的数组了。

听到RE说了一下优先队列,还是没想到怎么写,,,今天看了一下别人的解题报告,才发现先存一半+1个数就行了,然后输入一个数,就和q.top(),比较。判断是否进队列。


代码如下:


#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
#include<algorithm>
#include<map>
#include<list>
#include<cmath>
#define LL long long;
using namespace std;

priority_queue <int , vector<int>,  greater<int> > q;

int main()
{
    int n, cnt, t, i;
    double mid;
    while(~scanf("%d", &n))
	{
		mid = 0;
		while(!q.empty()) q.pop(); //清空队列

		cnt = n/2+1;

		for(i=0; i<n; i++)
		{
			scanf("%d", &t);
			if(q.size() < cnt)
				q.push(t);
			 
			else if(q.top() < t)
		    {
				q.pop();
				q.push(t);
			}
		}
		if(n%2) mid = q.top();
		else
		{
            mid+= q.top();
            q.pop();
            mid += q.top();
            mid /=2.0;
		}
		printf("%.1lf\n", mid);
	}
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值