codevs 3110 二叉堆练习3

3110 二叉堆练习3

题目描述 Description

给定N(N≤500,000)和N个整数(较有序),将其排序后输出。

输入描述 Input Description

N和N个整数

输出描述 Output Description

N个整数(升序)

样例输入 Sample Input

5

12 11 10 8 9

样例输出 Sample Output

8 9 10 11 12

数据范围及提示 Data Size & Hint

对于33%的数据 N≤10000

对于另外33%的数据 N≤100,000  0≤每个数≤1000

对于100%的数据 N≤500,000  0≤每个数≤2*10^9

详细讲解见随笔:讲解——堆 http://www.cnblogs.com/TheRoadToTheGold/p/6238795.html

此篇随笔只提供代码

#include<algorithm>
#include<iostream>
#include<cstdio>
using namespace std;
int n,a[500001];
int init()
{
    int x=0;char c=getchar();
    while(c<'0'||c>'9') c=getchar();
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x;
}
void heapify(int t)
{
    int left=t*2,right=t*2+1;
    int minn=t;//
    if(left<=n) {minn=a[minn]<a[left] ? minn:left;}
    if(right<=n){minn=a[minn]<a[right] ? minn:right;}
    if(minn!=t)
    {
        swap(a[minn],a[t]);
        heapify(minn);
    }
}
void build()
{
    for(int i=n/2;i;i--)
    heapify(i);
}
int get()
{
    int top=a[1];
    a[1]=a[n];
    n--;
    heapify(1);
    return top;
}
int main()
{
    n=init();
    for(int i=1;i<=n;i++) a[i]=init();
    build();
    while(n)  printf("%d ",get());
}
原文地址:https://www.cnblogs.com/TheRoadToTheGold/p/6238806.html