您的位置:首页 > 其它

题目1371:最小的K个数

2015-06-02 23:01 330 查看
时间限制:1 秒内存限制:32 兆题目描述:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。输入:每个测试案例包括2行:第一行为2个整数n,k(1<=n,k<=200000),表示数组的长度。第二行包含n个整数,表示这n个数,数组中的数的范围是[0,1000 000 000]。输出:对应每个测试案例,输出最小的k个数,并按从小到大顺序打印。样例输入:
8 4
4 5 1 6 2 7 3 8
样例输出:
1 2 3 4
#include <iostream>#include <cstdio>#include <algorithm>using namespace std;const int N = 200001;int heaps;void precolateDown(int k){int parent = 1;int val = heaps[1];int child = parent << 1;while (child <= k){if (child + 1 <= k && heaps[child + 1] > heaps[child])++child;if (heaps[child] > val){heaps[parent] = heaps[child];parent = child;child = parent << 1;}elsebreak;}heaps[parent] = val;}bool cmp(int a, int b){return a > b;}int main(void){int n, k;while (scanf("%d", &n) != EOF){scanf("%d", &k);for (int i = 1; i <= n; ++i)scanf("%d", &heaps[i]);sort(heaps + 1, heaps + k + 1, cmp);for (int i = k + 1; i <= n; ++i){if (heaps[i] < heaps[1]){swap(heaps[1], heaps[i]);precolateDown(k);}}sort(heaps + 1, heaps + k + 1);for (int i = 1; i <= k; ++i)i == 1 ? printf("%d", heaps[i]) : printf(" %d", heaps[i]);printf("\n");}return 0;}
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: