Codeforces 1175C Electrification
题目传送门
C. Electrification
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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<n) — the number of points and constant k.
The second line contains n integers a1,a2,…,an (1≤a1<a2<⋯<an≤109) — points in ascending order.
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.
Example
inputCopy
3
3 2
1 2 5
2 1
1 1000000000
1 0
4
outputCopy
3
500000000
4
题意:给定一个序列ai,求找出一个x使得di=|ai-x|,然后对得到的新序列排序,将d(k+1)作为结果,要求结果最小。
这题真的挺考智商的,我当时想了半天没想出来,想出来后就会觉得其实不难,其实代码很简单,这题因为是要d(k+1)作为结果,首先对ai进行排序,然后遍历每一个数时,结果只可能在往后的长度为k+1的区间中,对于每一个长度为k+1的区间,可以想象的出,该区间的最大值可能会成为整个di序列的结果,而要使得每个区间的最大值最小,则x必为(a[i]+a[i+k])/2,可以仔细思考下,这样代码就很简单了
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
void solve() {
int n, k;
cin >> n >> k;
vector<ll> points(n);
for (int i = 0; i < n; ++i) cin >> points[i];
sort(points.begin(), points.end());
ll res = INF;
ll x = -1;
for (int i = 0; i+k < n; ++i) {
//在i到i+k这个区间里面,dk+1最小值为第i+k个点-第i个点再除以2,此时x为(points[i+k]+points[i])/2
ll dk = (points[i+k] - points[i] + 1) / 2;
if (dk < res) {
res = dk;
x = (points[i+k] + points[i]) / 2;
}
}
cout << x << '\n';
}
int main() {
int t;
cin >> t;
while(t--) {
solve();
}
return 0;
}