「暑期训练」「Brute Force」 Optimal Point on a Line (Educational Codeforces Round 16, B)

时间:2024-01-21 17:15:57

题意

You are given n points on a line with their coordinates $x_i$. Find the point x so the sum of distances to the given points is minimal.

分析

答案是直觉上显然的:输出数组的中位数即可(对于偶数个数的,则是中间靠左)。
这样的结果正确的原因也很显然。首先,答案肯定在$[x_{min},x_{max}]$中,那么点无论在哪里,对于$x_i,x_{n-i}$这一对点而言,答案是保持不变的。于是需要考虑中间点。当点为奇数个,放在中间是最优的。点为偶数个,放在中间两个点的闭区间内都可以。

代码

#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define fi first
#define se second
#define ZERO(x) memset((x), 0, sizeof(x))
#define ALL(x) (x).begin(),(x).end()
#define rep(i, a, b) for (int i = (a); i <= (b); ++i)
#define per(i, a, b) for (int i = (a); i >= (b); --i)
#define QUICKIO \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0);
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pi = pair<int, int>;
using pii = pair<int, pi>; template<typename T>
T read()
{
T tmp; cin>>tmp;
return tmp;
} int main()
{
QUICKIO
int n; cin>>n;
vector<int> vec;
rep(i,1,n)
vec.PB(read<int>());
sort(ALL(vec));
cout<<vec[n%2?n/2:n/2-1];
return 0;
}