数据结构实验之排序四:寻找大富翁

来源:互联网 发布:pca算法人脸识别 编辑:程序博客网 时间:2024/05/16 23:59

Problem Description

2015胡润全球财富榜调查显示,个人资产在1000万以上的高净值人群达到200万人,假设给出N个人的个人资产值,请你快速找出排前M位的大富翁。

Input

首先输入两个正整数N( N ≤ 10^6)和M(M ≤ 10),其中N为总人数,M为需要找出的大富翁数目,接下来给出N个人的个人资产,以万元为单位,个人资产数字为正整数,数字间以空格分隔。

Output

一行数据,按降序输出资产排前M位的大富翁的个人资产值,数字间以空格分隔,行末不得有多余空格。

 

Example Input

6 312 6 56 23 188 60

Example Output

188 60 56


code:

#include <bits/stdc++.h>using namespace std;int a[15], n, i, j, m, k, t;void heapadjust(int a[], int i, int size){    int l = i*2;    int r = i*2+1;    int max = i;    if(i <= size/2)    {        if(l <= size && a[l] > a[max])            max = l;        if(r <= size && a[r] > a[max])            max = r;        if(max != i)        {            swap(a[i], a[max]);            heapadjust(a, max, size);        }    }}void heapbuild(int a[], int size){    for(i = size/2; i>=1; i--)    {        heapadjust(a, i, size);    }}void heapsort(int a[], int size){    heapbuild(a, size);    for(i = size; i >= 1; i--)    {        swap(a[i], a[1]);        heapadjust(a, 1, i-1);    }}int main(){    while(~scanf("%d %d", &n, &m))    {        int k = 1;        for(i = 1; i <= n; i++)        {            cin >> t;            if(k <= m)                a[k++] = t;            else            {                int l = 1;                for(j = 2; j <= m; j++)                {                    if(a[j] < a[l])                        l = j;                }                if(a[l] < t)                    a[l] = t;            }        }        heapsort(a, m);        for(i = m; i >= 1; i--)            printf("%d%c", a[i], i==1?'\n':' ');    }    return 0;}

原创粉丝点击