数据结构实验之排序四:寻找大富翁
Time Limit: 200MS
Memory Limit: 512KB
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
Hint
请用堆排序完成。
Author
xam
代码一 堆排序
#include<stdio.h>
#include <iostream>
#include<algorithm>
using namespace std;
void HeapAdjust(int *a,int i,int size)
{
int lchild=2*i;
int rchild=2*i+1;
int max=i;
if(i<=size/2)
{
if(lchild<=size&&a[lchild]>a[max])
{
max=lchild;
}
if(rchild<=size&&a[rchild]>a[max])
{
max=rchild;
}
if(max!=i)
{
swap(a[i],a[max]);
HeapAdjust(a,max,size);
}
}
}
void BuildHeap(int *a,int size)
{
int i;
for(i=size/2; i>=1; i--)
{
HeapAdjust(a,i,size);
}
}
void HeapSort(int *a,int size)
{
int i;
BuildHeap(a,size);
for(i=size; i>=1; i--)
{
swap(a[1],a[i]);
HeapAdjust(a,1,i-1);
}
}
int main()
{
int i,j,n,m,k,t,l;
while(scanf("%d %d",&n,&m)!=EOF)
{
int a[12];
k=1;
for(i=0; i<n; i++)
{
scanf("%d",&t);
if(k<m+1)
a[k++]=t;
else
{
l=1;
for(j=2; j<k; j++)
{
if(a[l]>a[j])
l=j;
}
if(a[l]<t)
a[l]=t;
}
}
HeapSort(a,m);
for(i=m; i>=1; i--)
if(i==m)
printf("%d",a[i]);
else
printf(" %d",a[i]);
printf("\n");
}
}
代码二 不用堆排序
#include <bits/stdc++.h>
using namespace std;
int a[15], n, m;
int cmp(const void *a, const void *b)
{
return *(int *)b-*(int *)a;
}
int main()
{
int k=0;
scanf("%d %d", &n, &m);
for(int i=0;i<n;i++)
{
int t;
scanf("%d", &t);
if(k<m) a[k++]=t;
else
{
int min=a[0], f=0;
for(int j=1;j<m;j++)
if(a[j]<min) {min=a[j];f=j;}
if(min<t) a[f]=t;
}
}
qsort(a,m,sizeof(a[0]),cmp);
for(int i=0;i<m-1;i++)
printf("%d ", a[i]);
printf("%d\n", a[m-1]);
return 0;
}