【题解】C. Electrification⭐⭐⭐ 【思维】

C. Electrification

At first, there was a legend related to the name of the problem, but now it’s just a formal statement.

You are given n points a1,a2,…,an on the OX axis. Now you are asked to find such an integer point x on OX axis that fk(x) is minimal possible.

The function fk(x) can be described in the following way:

form a list of distances d1,d2,…,dn where di=|ai−x| (distance between ai and x);
sort list d in non-descending order;
take dk+1 as a result.
If there are multiple optimal answers you can print any of them.

Input

The first line contains single integer T (1≤T≤2⋅105) — number of queries. Next 2⋅T lines contain descriptions of queries. All queries are independent.

The first line of each query contains two integers n, k (1≤n≤2⋅105, 0≤k

The second line contains n integers a1,a2,…,an (1≤a1

It’s guaranteed that ∑n doesn’t exceed 2⋅105.

Output

Print T integers — corresponding points x which have minimal possible value of fk(x). If there are multiple answers you can print any of them.

Examples

inputCopy
3
3 2
1 2 5
2 1
1 1000000000
1 0
4
outputCopy
3
500000000
4

Hint




题意:

给出n个数a[i], 定义如下函数f(x): 将a数组转换成d数组, d[i] = abs(a[i]-x), d[k+1]为函数的值
求最小的函数值

题解:

可以想到, 若想使得d[k+1]的值最小, x一定是取在中位数
同时d[k+1] = a[k+i]-a[i]
这样的话我们枚举一遍k即可

经验小结:


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const int inf = 1<<30;
const LL maxn = 1e5*2+10;

int n, k, a[maxn];
int main()
{
    int T;
    cin >> T;
    while(T--){
        cin >> n >> k;
        for(int i = 1; i <= n; ++i)
            cin >> a[i];
        int mind = inf, x;
        for(int i = 1; i+k <= n; ++i){
            if(a[i+k]-a[i] < mind){
                mind = a[i+k]-a[i];
                x = (a[i+k]+a[i])/2;
            }
        }
        cout << x << endl;
    }

	return 0;
}

你可能感兴趣的:(思维)