標籤:實驗 can scanf 堆排序 use std 複雜度 更新 head
資料結構實驗之排序四:尋找大富翁Time Limit: 200 ms Memory Limit: 512 KiBProblem Description
2015胡潤全球財富榜調查顯示,個人資產在1000萬以上的高淨值人群達到200萬人,假設給出N個人的個人資產值,請你快速找出排前M位的大富翁。
Input
首先輸入兩個正整數N( N ≤ 10^6)和M(M ≤ 10),其中N為總人數,M為需要找出的大富翁數目,接下來給出N個人的個人資產,以萬元為單位,個人資產數字為正整數,數字間以空格分隔。
Output
一行資料,按降序輸出資產排前M位的大富翁的個人資產值,數字間以空格分隔,行末不得有多餘空格。
Sample Input
6 312 6 56 23 188 60
Sample Output
188 60 56
提示:本題要求用堆排來解決,堆排需要建大堆和小堆。堆排的時間複雜度是O(nlogn)
代碼實現如下(gcc):
#include <stdio.h>int a[20];int m;void Swap(int x,int y)//交換順序{ int t; t=a[x]; a[x]=a[y]; a[y]=t;}void Siftdown(int i)//向下找{ int t,flag=0;//t用來記錄較小結點,flag來判斷能否向下調整 while(i*2<=m&&flag==0) { if(a[i]>a[i*2]) t=i*2; else t=i; if(i*2+1<=m) { if(a[t]>a[i*2+1]) t=i*2+1; } if(t!=i) { Swap(t,i);//交換 i=t;//向下更新 } else flag=1;//否則不能調整了 }}void heapsort()//堆排序{ while(m>1) { Swap(m,1); m--; Siftdown(m); }}int main(){ int num,n,i,j; scanf("%d %d",&num,&m); for(i=1;i<=m;i++) { scanf("%d",&a[i]); } n=m; for(i=m/2;i>=1;i--) { Siftdown(i); } for(i=m+1;i<=num;i++) { int x; scanf("%d",&x); if(x>a[1]) { a[1]=x; for(j=m/2;j>=1;j--) { Siftdown(j); } } } heapsort(); for(i=1;i<=n;i++) { i<n? printf("%d ",a[i]):printf("%d\n",a[i]); } return 0;}/***************************************************Result: AcceptedTake time: 196msTake Memory: 156KB****************************************************/
SDUT 3401 資料結構實驗之排序四:尋找大富翁