题目连接: Bogosort
题目:
You are given an array a1,a2,…,an. Array is good if for each pair of indexes i<j the condition j−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).
For example, if a=[1,1,3,5], then shuffled arrays [1,3,5,1], [3,5,1,1] and [5,3,1,1] are good, but shuffled arrays [3,1,5,1], [1,1,3,5] and [1,1,5,3] aren’t.
It’s guaranteed that it’s always possible to shuffle an array to meet this condition.
Input
The first line contains one integer t (1≤t≤100) — the number of test cases.
The first line of each test case contains one integer n (1≤n≤100) — the length of array a.
The second line of each test case contains n integers a1,a2,…,an (1≤ai≤100).
Output
For each test case print the shuffled version of the array a which is good.
Example
Input
3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
Output
7
1 5 1 3
2 4 6 1 3 5
大致题意:
给你一个数组, 需要让你对数组重新排序, 要求如下: 如果对于数组下标i与j(i < j), 需要满足 j−aj≠i−ai .
解题思路:
这个题的做法可以很暴力, 三层循环跑也能跑出来, 但是也有一种十分巧妙的方法, 就是将数组从大到小排序.
那么, 为什么可以从大到小排序后直接输出呢?
如果我们进行了排序, 那么我们可以知道 a[j] <= a[i] 是成立的.
而因为有 j > i 所以对于 j−a[j] 和 i−a[i] 的关系而言, 可以看做 大减小 与 小减大的关系, 所以有 j-a[j] > i-a[i].
特别说明: 虽然a[j]与a[i]的关系不是严格的大小关系, 但是当a[i] = a[j]时, 我们也有 大减同 > 小减同 关系成立.
AC代码:
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int a[105]; int n;
bool cmp(int a, int b) { return a > b; }
void init() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
}
sort(a + 1, a + 1 + n, cmp);
}
int main(void)
{
int t; cin >> t;
while (t--) {
init();
for (int i = 1; i <= n; ++i) {
printf("%d", a[i]);
i == n ? printf("\n") : printf(" ");
}
}
return 0;
}