-
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
时间限制:1 秒
内存限制:32 兆
题目描述:
-
输入:
-
每个测试案例包括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[N]; 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; } else break; } 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; }