Codeforces div2 Sorted Adjacent Differences 题解

You have array of n numbers 1,2,…,a1​,a2​,…,an​.

Rearrange these numbers to satisfy ∣a1​−a2​∣≤∣a2​−a3​∣≤…≤∣an−1​−an​∣, where∣x∣ denotes absolute value of x. It's always possible to find such rearrangement.

Note that all numbers in a are not necessarily different. In other words, some numbers of a may be same.

You have to answer independent t test cases.

Input

The first line contains a single integer (1≤t≤104) — the number of test cases.

The first line of each test case contains single integer (3≤n≤10^5) — the length of array a. It is guaranteed that the sum of values of n over all test cases in the input does not exceed 105105.

The second line of each test case contains n integers a1​,a2​,…,an​ (−10^9≤ai​≤10^9).

Output

For each test case, print the rearranged version of array a which satisfies given condition. If there are multiple valid rearrangements, print any of them.

Sample 1

Input Output
2
6
5 -2 4 8 6 5
4
8 1 4 2
5 5 4 6 8 -2
1 2 4 8

Note

In the first test case, after given rearrangement, ∣a1​−a2​∣=0≤∣a2​−a3​∣=1≤∣a3​−a4​∣=2≤∣a4​−a5​∣=2≤∣a5​−a6​∣=10. There are other possible answers like "5 4 5 6 -2 8".

In the second test case, after given rearrangement, ∣a1​−a2​∣=1≤∣a2​−a3​∣=2≤∣a3​−a4​∣=4. There are other possible answers like "2 4 8 1".

题目分析:

 给一个数列,让你变换成相邻两个数之差不呈现递减的数列;

我们首先要做的就是排序,这样对于一个数列来说,左边的数就小于等于右边的数

我们举个例子:

1 2 3 4 5

我们发现第一个数字和最后一个数字之差最大,第二个和倒数第二个第二大,而最中间的我们先不看它

最终我们拿出来这么一组数 {1,5}、{2,4}、{3} ;

那么我们如何排列呢?

最好是按照小的数字在后面排列:3 4 2 5 1,也就是将中位数前面的数依次插入后面;

当然,这是奇数的情况,那偶数呢?

其实也是大同小异,主要的一点区别就是,偶数没有中间那个孤立的数,所以直接插入就可以了;

AC代码:

#include
#include
using namespace std;
const int N = 1e5 + 5;
int a[N];
int ans[N];
int main()
{
	int _;
	cin >> _;
	while (_--)
	{
		int n;
		cin >> n;
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		sort(a + 1, a + n + 1);
		if (n % 2 == 0)
		{
			ans[2] = a[n / 2];
			ans[1] = a[n / 2 + 1];
			for (int i = 3; i <= n; i++)
			{
				if (i % 2 == 0)
					ans[i] = a[n / 2 - (i - 2) / 2];
				else
					ans[i] = a[n / 2 + (i - 1) / 2 + 1];
			}
		}
		else
		{
			ans[1] = a[(n + 1) / 2];
			for (int i = 2; i <= n; i++)
			{
				if (i % 2 == 0)
					ans[i] = a[(n + 1) / 2 + i / 2];
				else
					ans[i] = a[(n - i + 2) / 2];
			}
		}
		for (int i = 1; i < n; i++)
			cout << ans[i] << " ";
		cout << ans[n];
		cout << endl;
	}
	return 0;
}

你可能感兴趣的:(c++,算法)