胡润研究院的调查显示,截至2017年底,中国个人资产超过1亿元的高净值人群达15万人。假设给出N个人的个人资产值,请快速找出资产排前M位的大富翁。
输入格式:
输入首先给出两个正整数N(≤106)和M(≤10),其中N为总人数,M为需要找出的大富翁数;接下来一行给出N个人的个人资产值,以百万元为单位,为不超过长整型范围的整数。数字间以空格分隔。
输出格式:
在一行内按非递增顺序输出资产排前M位的大富翁的个人资产值。数字间以空格分隔,但结尾不得有多余空格。
输入样例:
8 3
8 12 7 3 20 9 5 18
输出样例:
20 18 12
此题没有重复元素,但是有m>n的情形。
1.快速排序
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=1e6+5;
long long int a[maxn];
int n,m;
int main()
{
scanf("%d%d",&n,&m);
for (int i=0;i<n;i++)
scanf("%lld",&a[i]);
sort(a,a+n);
m>n? m=n:m=m;
for (int i=n-1;i>=n-m;i--)
{
printf("%lld%c",a[i],i==n-m? '\n':' ');
}
return 0;
}
2堆排序:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=2e6+5;
int n,m;
int a[maxn];
void Heap (int x)
{
int left=x<<1,right=x<<1|1;
int large=x;
if(left<=n&&a[left]>a[large])
large=left;
if(right<=n&&a[right]>a[large])
large=right;
if(large!=x)
{
swap(a[x],a[large]);
Heap(large);
}
}
void Create ()
{
for (int i=n>>1;i>=1;i--)
Heap(i);
}
bool IsEmpty()
{
return n==0? true:false;
}
int Delete ()
{
if(IsEmpty())
return -1;
int temp=a[1];
int ttemp=a[n--];
int child,parent;
for (parent=1;parent<=n;parent=child)
{
child=parent<<1;
if(child<n&a[child]<a[child+1])
child++;
if(a[child]>ttemp)
a[parent]=a[child];
else
break;
}
a[parent]=ttemp;
return temp;
}
int main()
{
scanf("%d%d",&n,&m);
m>n? m=n:m=m;
for (int i=1;i<=n;i++)
scanf("%d",&a[i]);
Create ();
for (int i=1;i<=m;i++)
printf("%d%c",Delete(),i==m? '\n':' ');
return 0;
}