STL之heap堆的应用

heap堆

STL中的堆默认是最大堆,想用最小堆的话,必须在push_heap, pop_heap,make_heap等每一个函数后面加第三个参数greater<int>(),括号不能省略。


heap堆的方法

  1. make_heap(_First, _Last):使序列变成堆。默认是建立最大堆的。
  2. push_heap(_First, _Last):新添加一个元素在末尾,然后重新调整堆序。该算法必须是在一个已经满足堆序的条件下,添加元素。
  3. pop_heap(_First, _Last):与push_heap类似,参数一样。把堆顶元素取出来,重新调整堆序。
  4. sort_heap(_First, _Last):每次pop_heap可以获得堆中最大的元素,那么我们持续对整个heap做pop_heap操作,每次将操作的范围向前缩减一个元素。当整个程序执行完毕后,我们得到一个非降的序列。


heap堆的应用

Sequence Median

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.
Example

input
4
3
6
4
5
output
4.5


解题思路:

题意为求某序列的中位数,所以只需要记录前N+1位数字并对其排序即可。该题可通过运用最大堆进行求解。


AC代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<cstring>
#include<queue>
#include<stack>
#include<vector>

using namespace std;

unsigned int a[125005];

int main() {

    unsigned int n, i, x, s1, s2;
    scanf("%d", &n);

    for(i = 0; i < n/2 + 1; i++) {
        scanf("%d", &a[i]);
    }
    make_heap(a, a+n/2+1);
    for(i = n/2 + 1; i < n; i++) {
        scanf("%d", &x);
        a[n/2 + 1] = x;
        push_heap(a, a+n/2 + 2);
        pop_heap(a, a+n/2 + 2);
    }

    if(n % 2) {
        printf("%.1lf\n", (double)a[0]);
    }else {
        s1 = a[0];
        pop_heap(a, a+n/2 + 1);
        s2 = a[0];
        double sum = s1 + s2;
        printf("%.1lf\n", sum / 2);
    }


}

参考链接:http://www.cnblogs.com/peccavi/p/4997266.html
                 http://blog.csdn.net/longhopefor/article/details/38303545

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值