SDUT 3401 資料結構實驗之排序四:尋找大富翁

來源:互聯網
上載者:User

標籤:實驗   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 資料結構實驗之排序四:尋找大富翁

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.