7-2 尋找大富翁 (25 分)
胡潤研究院的調查顯示,截至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
堆排序
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <map>
#include <stack>
#include <set>
#include <vector>
#include <cstring>
#include <queue>
#include <cmath>
#define FRER() freopen("in.txt","r",stdin);
#define FREW() freopen("out.txt","w",stdout);
#define mem(a,b) memset(a,b,sizeof(a));
#define go int T;scanf("%d",&T);for(int cas=1;cas<=T;cas++)
#define mod 1000000007
using namespace std;
typedef pair<int,int> pii;
typedef long long ll;
const int maxn = 1000000 + 7;
int a[maxn];
void heapAdjust(int i,int n){
int tmp = a[i];
for(int j=i<<1;j<=n;j<<=1){
if(j<n&&a[j]<a[j+1]) j++;
if(a[j]<a[i]) break;
swap(a[i],a[j]);
i=j;
}
}
void heapSort(int n,int k){
for(int i=n/2;i>=1;i--) heapAdjust(i, n);
for(int i=n;i>=1&&k--;i--){
if(i!=n) cout<<" ";
cout<<a[1];
swap(a[1], a[i]);
heapAdjust(1, i-1);
}
cout<<endl;
}
int main() {
//FRER();
int n,k;
cin>>n>>k;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
heapSort(n,k);
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。