7-1 尋找大富翁 (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
簡單的排序問題,快排超時了,換了堆排序就過了
AC代碼:
#include <iostream> #include <cstring> #include <algorithm> #include <queue> #include <vector> #include <cstdio> #include <malloc.h> #define INF 0x3f3f3f3f #define FRER() freopen("in.txt", "r", stdin) #define FREW() freopen("out.txt", "w", stdout) using namespace std; const int maxn = 1e6 + 5; int num[maxn]; void adjust(int s, int m) { int temp = num[s]; for(int j = s * 2; j <= m; j *= 2) { if(j < m && num[j] > num[j + 1]) ++j; if(temp <= num[j]) break; num[s] = num[j]; s = j; } num[s] = temp; } void heapSort(int n) { for(int i = n / 2; i > 0; --i) adjust(i, n); for(int i = n; i > 1; --i) { swap(num[1], num[i]); adjust(1, i - 1); } } int main() { int n, m; scanf("%d %d", &n, &m); for(int i = 1; i <= n; ++i) scanf("%d", &num[i]); heapSort(n); for(int i = 1; i <= m && i <= n; ++i) { printf("%d%c", num[i], (i == m || i == n) ? '\n' : ' '); } return 0; }
