Codefoeces 1339B Sorted Adjacent Differences

题意:给定一个长度为n的数组,需要重新调整元素的位置使得|ai-ai+1|<=|ai+1-ai+2|。

思路:构造即可,将数组排序以后,把最大的元素放最后面,最小的元素放在倒数第二个位置,第二大的元素放在倒数第三个位置,第二小的放在倒数第四个位置......

code:

#include<bits/stdc++.h>

using namespace std;
const int maxn = 3e5 + 10;
int a[maxn], b[maxn];

int main(){
    int T;
    cin>>T;
    while(T--){
        int n;
        cin>>n;
        for(int i = 1 ; i <= n; i++) cin>>a[i];
        sort(a + 1, a + 1 + n);
        int l = 1, r = n, pos = n, f = 0;
        while(pos){
            if(!f) b[pos] = a[r], r--, f = 1;
            else b[pos] = a[l], l++, f = 0;
            pos--;
        }
        for(int i = 1;  i <= n; i++) cout<<b[i]<<" ";cout<<endl;
    }
}

 

posted @ 2020-04-13 10:29  魏紫桃黄  阅读(150)  评论(0)    收藏  举报