CodeForces-652B题解

题目链接:http://codeforces.com/problemset/problem/652/B

B. z-sort
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:

  1. ai ≥ ai - 1 for all even i,
  2. ai ≤ ai - 1 for all odd i > 1.

For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.

Can you make the array z-sorted?

Input

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array a.

The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

Output

If it's possible to make the array a z-sorted print n space separated integers ai — the elements after z-sort. Otherwise print the only word "Impossible".

Examples
input
Copy
4
1 2 2 1
output
Copy
1 2 1 2
input
Copy
5
1 3 2 2 5
output
Copy
1 5 2 3 2

题目意思:首先一个n(1<=n<=1000))表示一个整数数组a的元素个数(1<=a[i]<=1e9),现在要求我们把这个数组“Z”排序,“Z”排序规则如下:
1.任意的偶数项总是大于等于前一项;
2.任意的奇数项总是小于等于前一项(第一项除外)。
如果这样的“Z”排序存在,则输出这个排序后的数组,每个元素之前空格。
否则,输出“Impossible”。
题目思路:这个题目挖了一个小坑:就是这样的Z排序是一定存在的。我们只要先把数组按照从小到大排序然后依次插入数组中奇数下标的位置,插完奇数位插偶数位,就符合题意了。
至于为什么可以这么做,可以先把原数组元素按照大小分成两半:大的那一半所有元素比小的那一半所有元素都大,然后模拟此插入过程,我们总会发现这样是满足要求的。
#include<stdio.h>
#include<algorithm> 
using namespace std;
const int maxn=1000+10;
int main()
{
    int n,a[maxn],ans[maxn],j=1;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    sort(a+1,a+n+1);
    for(int i=1;i<=n;i+=2,j++)ans[i]=a[j];
    for(int i=2;i<=n;i+=2,j++)ans[i]=a[j];
    printf("%d",ans[1]);
    for(int i=2;i<=n;i++)printf(" %d",ans[i]);
    printf("
");
    return 0;
}
原文地址:https://www.cnblogs.com/Mingusu/p/11845759.html