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

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

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

请用堆排序完成。

代码如下: 

堆排序做法:

#include<bits/stdc++.h>

using namespace std;

void Swap(int st[],int i,int j)
{
    int temp=st[i];
    st[i]=st[j];
    st[j]=temp;
}

void HeapAdjust(int st[],int s,int m)
{
    int temp=st[s];
    for(int i=2*s; i<=m; i*=2)
    {
        if(i<m&&st[i]>st[i+1])
            ++i;
        if(temp<=st[i])
            break;
        st[s]=st[i];
        s=i;
    }
    st[s]=temp;
}

void HeapSort(int st[],int n)
{
    for(int i=n/2; i>0; --i)
        HeapAdjust(st,i,n);
    for(int i=n; i>1; --i)
    {
        Swap(st,1,i);
        HeapAdjust(st,1,i-1);
    }
}

int main()
{
    int n,m;
    int st[1001];
    int k=1;
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++)
    {
        int temp;
        scanf("%d",&temp);
        if(k<=m)
            st[k++]=temp;
        else
        {
            int p=1;
            for(int j=2; j<=m; j++)
                if(st[p]>st[j])
                    p=j;
            if(st[p]<temp)
                st[p]=temp;
        }
    }
    HeapSort(st,m);
    for(int i=1; i<=m; i++)
    {
        if(i==m)
            cout<<st[i]<<endl;
        else
            cout<<st[i]<<" ";
    }
    return 0;
}

快速排序做法:

#include<bits/stdc++.h>

using namespace std;

int cmp(const void *a,const void *b)
{
    return *(int *)b-*(int *)a;
}

int main()
{
    int n,m;
    int a[1001];
    int k=0;
    scanf("%d%d",&n,&m);
    for(int i=0; i<n; i++)
    {
        int temp;
        scanf("%d",&temp);
        if(k<m)
            a[k++]=temp;
        else
        {
            int p=0;
            for(int j=1; j<m; j++)
            {
                if(a[p]>a[j])
                    p=j;
            }
            if(a[p]<temp)
                a[p]=temp;
        }
    }
    qsort(a,m,sizeof(a[0]),cmp);
    for(int i=0; i<m; i++)
    {
        if(i==m-1)
            cout<<a[i]<<endl;
        else
            cout<<a[i]<<" ";
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值