PTA 資料結構與演算法題目集(中文)7-38 尋找大富翁(25 分)快排或堆排序
阿新 • • 發佈:2018-12-24
胡潤研究院的調查顯示,截至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; }