Bogosort

题目连接: 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;
}

END

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逍遥Fau

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值