案例7-1.3 寻找大富翁 (25 分) 胡润研究院的调查显示,截至2017年底,中国个人资产超过1亿元的高净值人群达15万人。假设给出N个人的个人资产值,请快速找出资产排前M位的大富翁。
输入格式: 输入首先给出两个正整数N(≤10 6
)和M(≤10),其中N为总人数,M为需要找出的大富翁数;接下来一行给出N个人的个人资产值,以百万元为单位,为不超过长整型范围的整数。数字间以空格分隔。输出格式: 在一行内按非递增顺序输出资产排前M位的大富翁的个人资产值。数字间以空格分隔,但结尾不得有多余空格。
输入样例: 8 3 8 12 7 3 20 9 5 18 输出样例: 20 18 12
书上提到了三种实现,我就全部写一遍,反正闲着也是闲着(
第一种:
数据全部存在数组中,快排实现,时间复杂度NlogN+
注意N<M的情况
#include<iostream>
#include<queue>
#include<cstdlib>
#include<cstdio>
#include<cstring>
using namespace std;
int compare(const void* a, const void* b) {
return (*(int*)b - *(int*)a);//(int*) is used to type convert,and another * is used to stare at the data
}
int main() {
int N, M;
cin >> N >> M;
int* a = (int*)malloc(sizeof(int) * N);
for (int i = 0; i < N; i++)
scanf_s("%d", &a[i]);
qsort(a, N, sizeof(int), compare);
cout << a[0];
if (N < M) {
for (int i = 1; i < N; i++)
cout << " " << a[i];
}
else
for (int i = 1; i < M; i++)
cout <<" "<< a[i];
}
结果:
测试点 提示 结果 耗时 内存
0 sample 答案正确 4 ms 356 KB
1 有相等数字 答案正确 4 ms 384 KB
2 N小于M 答案正确 3 ms 384 KB
3 最大规模数据,逆序输入 答案正确 277 ms 8236 KB
第二种:
最大堆
#include<iostream>
#include<queue>
#include<cstdlib>
#include<cstdio>
#include<cstring>
using namespace std;
void adjustHeap(int* a,int i,int size) {
int left, right, max,tmp;
left = 2 * i;
right = left + 1;
max = i;
if (left <= size && a[left] > a[max])
max = left;
if(right<=size&& a[right] > a[max])
max = right;
if (max != i) {//need to check the son tree and swap son node with father node
tmp = a[i];
a[i] = a[max];
a[max] = tmp;
adjustHeap(a, max, size);
}
}
void MAXHEAP(int* a, int N,int M) {
int tmp;
for (int i = N / 2; i >= 1; i--)
adjustHeap(a, i,N);
if (N < M) {
for (int i = 1; i <= N; i++) {
if (i == 1)
cout << a[1];
else cout << " " << a[1];
tmp = a[1];
a[1] = a[N - i + 1];
a[N - i + 1] = tmp;
adjustHeap(a, 1, N - i);
}
}
else for (int i = 1; i <= M; i++) {
if (i == 1)
cout << a[1];
else cout << " " << a[1];
tmp = a[1];
a[1] = a[N-i+1];
a[N - i + 1] = tmp;
adjustHeap(a, 1, N - i);
}
}
int main() {
int N, M;
cin >> N >> M;
int* a = (int*)malloc(sizeof(int) * N);
for (int i = 1; i <= N; i++)
scanf_s("%d", &a[i]);
MAXHEAP(a, N, M);
return 0;
}
测试点 提示 结果 耗时 内存
0 sample 答案正确 4 ms 400 KB
1 有相等数字 答案正确 3 ms 368 KB
2 N小于M 答案正确 4 ms 384 KB
3 最大规模数据,逆序输入 答案正确 142 ms 4224 KB
可以看出在大规模数据确实有更好的表现但是消耗空间相当大
第三种:
最小堆
读入M个数据建立一个为M大小的最小堆,然后依次读入剩下数据,和顶点数据比较,每读入一个数据,调整一次堆
然后堆排序输出