URAL 1306-Sequence Median(堆)

Posted ljbguanli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了URAL 1306-Sequence Median(堆)相关的知识,希望对你有一定的参考价值。

1306. 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 231?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

题目非常easy。就是求一个序列的中位数,假设这个序列的长度为偶数。输出中间的两个的平均数。但内存卡的非常紧,所以不能排序暴力。能够建一个最大堆维护序列前n/2+1个元素,这样内存最多用n/2+1。优先队列900多k。换成数组堆后600k+。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int maxn=250000;
int a[maxn/2+10];
int main()
{
    int n;double ans;
    while(scanf("%d",&n)!=EOF)
    {
       int num=0,x;
       for(int i=0;i<n/2+1;i++)
       scanf("%d",&a[i]);
       make_heap(a,a+n/2+1);
       for(int i=n/2+1;i<n;i++)
       {
           scanf("%d",&x);
           if(x<a[0])
           {
               pop_heap(a,a+n/2+1);
               a[n/2]=x;
               push_heap(a,a+n/2+1);
           }
       }
       if(n%2)
       {
		   ans=(double)a[0];
		   printf("%.1lf\n",ans);
       }
       else
       {
           ans=(double)a[0];
           pop_heap(a,a+n/2+1);
           ans+=(double)a[0];
		   printf("%.1lf\n",ans/2.0);
       }

    }
    return 0;
}



以上是关于URAL 1306-Sequence Median(堆)的主要内容,如果未能解决你的问题,请参考以下文章

[URAL1519]Formula 1

Ural 1146 Maximum Sum(DP)

URAL 1427 SMS

URAL - 1627:Join (生成树计数)

URAL比赛记录

Ural 1382 2SAT