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;
	}

}

猜你喜欢

转载自blog.csdn.net/asbbv/article/details/115191923
今日推荐