题解:P17033 [NWERC 2020] 温泉 / Hot Springs

· · 题解

P17033 [NWERC 2020] 温泉 / Hot Springs 题解

思路

先把所有数从小到大排序。

然后从中间往两边取数,左边取一个右边取一个,交替放到答案里。这样排出来的序列,前面的数比较接近,差值小;后面的数越来越远,差值大,正好满足要求。

如果是奇数个,就从正中间开始取;如果是偶数个,就从中间两个开始取。 ::::success[code]

#include <bits/stdc++.h>
using namespace std;

#define int long long
#define endl '\n'

int n;
vector<int> ans;

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n;
    vector<int> a(n);
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }

    sort(a.begin(), a.end());

    int l = n / 2, r = n / 2 + 1;
    if(n % 2 == 0){
        l = n / 2 - 1;
        r = n / 2;
    }

    while(l >= 0 || r < n){
        if(l >= 0) ans.push_back(a[l--]);
        if(r < n) ans.push_back(a[r++]);
    }

    for(int i = 0; i < ans.size(); i ++){
        cout << ans[i] << " ";
    }

    return 0;
}

::::