Problem Description
2015胡润全球财富榜调查显示,个人资产在1000万以上的高净值人群达到200万人,假设给出N个人的个人资产值,请你快速找出排前M位的大富翁。
Input
首先输入两个正整数N( N ≤ 10^6)和M(M ≤ 10),其中N为总人数,M为需要找出的大富翁数目,接下来给出N个人的个人资产,以万元为单位,个人资产数字为正整数,数字间以空格分隔。
Output
一行数据,按降序输出资产排前M位的大富翁的个人资产值,数字间以空格分隔,行末不得有多余空格。
Example Input
6 3
12 6 56 23 188 60
Example Output
188 60 56
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int N = 12;
int heap[N];
void adjust(int i, int m){ //调整为最小堆
int l = 2 * i;
int r = l + 1;
int res = i;
if(l <= m && heap[l] < heap[res])
res = l;
if(r <= m && heap[r] < heap[res])
res = r;
if(res != i)
{
swap(heap[res], heap[i]);
adjust(res, m);
}
}
int main(){
int n, m, x;
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i++) //建立含有m个元素的堆
scanf("%d", &heap[i]);
for(int i = m / 2; i >= 1; i--)
adjust(i, m);
for(int i = m + 1; i <= n; i++) //比较元素,调整堆
{
scanf("%d", &x);
if(x > heap[1])
{
heap[1] = x;
adjust(1, m);
}
}
for(int i = m; i >= 2; i--) //堆排序
{
swap(heap[1], heap[i]);
adjust(1, i - 1);
}
for(int i = 1; i <= m; i++)
{
printf("%d", heap[i]);
if(i < m)
printf(" ");
}
return 0;
}