Problem Description
2015胡润全球财富榜调查显示,个人资产在1000万以上的高净值人群达到200万人,假设给出N个人的个人资产值,请你快速找出排前M位的大富翁。
Input
首先输入两个正整数N( N ≤ 10^6)和M(M ≤ 10),其中N为总人数,M为需要找出的大富翁数目,接下来给出N个人的个人资产,以万元为单位,个人资产数字为正整数,数字间以空格分隔。
Output
一行数据,按降序输出资产排前M位的大富翁的个人资产值,数字间以空格分隔,行末不得有多余空格。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int a[1000020];
void HeapAdjust(int s, int len)
{
int x = a[s], j;
for(j = 2 * s; j <= len; j *= 2)
{
if(j < len && a[j] > a[j + 1])
j++;
if(x < a[j])
break;
a[s] = a[j];
s = j;
}
a[s] = x;
}
void HeapSort(int len)
{
int i, t;
for(i = len; i > 1; i--)
{
t = a[1];
a[1] = a[i];
a[i] = t;
HeapAdjust(1, i - 1);
}
}
int main()
{
int n, m, i, j, x;
scanf("%d %d", &n, &m);
for(i = 1; i <= m; i++)
scanf("%d", &a[i]);
for(i = m / 2; i > 0; i--)
HeapAdjust(i, m);
for(i = m + 1; i <= n; i++)
{
scanf("%d", &x);
if(x > a[1])
{
a[1] = x;
for(j = m / 2; j > 0; j--)
HeapAdjust(j, m);
}
}
HeapSort(m);
for(i = 1; i < m; i++)
printf("%d ", a[i]);
printf("%d\n", a[i]);
return 0;
}
Example Input
6 3 12 6 56 23 188 60
Example Output
188 60 56
Hint
请用堆排序完成。