题目1371:最小的K个数

时间限制: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[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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值