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

題意

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

分析

答案是直覺上顯然的:輸出數組的中位數即可(對於偶數個數的,則是中間靠左)。
這樣的結果正確的原因也很顯然。首先,答案肯定在[xmin,xmax] 中,那麼點無論在哪裏,對於(xi,xni) 這一對點而言,答案是保持不變的。於是需要考慮中間點。當點爲奇數個,放在中間是最優的。點爲偶數個,放在中間兩個點的閉區間內都可以。

代碼

#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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章