數據結構實驗之排序四:尋找大富翁
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
請用堆排序完成。
/*-------------------------
Name:數據結構實驗之排序四:尋找大富翁(堆排序)
Author:Mr.z
Time:2016-12-10
---------------------------*/
#include <stdio.h>
void swap(int arr[],int i,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
void HeapAdjust(int arr[],int s,int n){
int temp=arr[s],i,j;
for(i=s*2;i<=n;i*=2){
if(i<n && arr[i]>arr[i+1])
i++;
if(temp<=arr[i])
break;
arr[s]=arr[i];
s=i;
}
arr[s]=temp;
}
void HeapSort(int arr[],int n){
for(int i=n/2;i>0;i--)
HeapAdjust(arr,i,n);
for(int i=n;i>1;i--){
swap(arr,1,i);
HeapAdjust(arr,1,i-1);
}
}
int main(){
int arr[12],i,n,m,temp,k;
k=1;
scanf("%d %d",&n,&m);
for(i=1;i<=n;i++){
scanf("%d",&temp);
if(k<=m) arr[k++]=temp;
else {
int l=1;
for(int j=2;j<=m;j++)
if(arr[l]>arr[j])
l=j;
if(arr[l]<temp)
arr[l]=temp;
}
}
HeapSort(arr,m);
for(i=1;i<=m;i++)
if(i==m) printf("%d\n",arr[i]);
else printf("%d ",arr[i]);
return 0;
}
/***************************************************
User name: zhxw150244李政
Result: Accepted
Take time: 156ms
Take Memory: 104KB
Submit time: 2016-12-10 21:42:40
****************************************************/