C. Electrification (贪心、思维、尺取)

题目

思路:对于每个有k+1个元素的区间必然会存在一个x使得第k+1个元素-x为第k+1个最大,我们要想让这个结果最小则取(lst[i]+lst[i+k]+1)/2为x。即使这样求得的x可能不会使最近的x个元素刚好为此区间的,但这个x求得的最小值在之后的区间也会被另外的最小值给替换掉(具体原因可以模拟一下在该区间求得的x值有其它更近的元素情况),所以尺取遍历一遍即可。

#include<iostream>
#include<string>
#include<stdio.h>
#include<map>
#include<memory.h>
#include<vector>
#include<algorithm>
#define FAST ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
typedef long long ll;
using namespace std;
const int Max = 1e6 + 5;
int lst[Max], ls[Max];
int n;

int main()
{
	int t;cin >> t;
	while (t--)
	{
		int n, k;cin >> n >> k;
		for (int i = 1;i <= n;i++)cin >> lst[i];
		sort(lst + 1, lst + 1 + n);
		int x=0, mi = 1e9;
		for (int i = 1;i + k <= n;i++)
		{
			if ((lst[i + k] - lst[i]+1)/2 < mi)
			{
				x = (lst[i + k] + lst[i]) / 2, mi = (lst[i + k] - lst[i] + 1) / 2;
			}
		}
		if (k == 0)cout << lst[1] << endl;
		else cout << x << endl;
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Rikka_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值