【思维】G. Special Permutation

Codeforces Round 640 (Div. 4)
G. Special Permutation

题意:输出一个全排列,要求相邻数字之差的绝对值≥2且≤4.

思路:
不难发现n必须≥4,且n=4时排列应为2 4 1 3或者 3 1 4 2,以此为基础,左右两边一偶一奇/一奇一偶逐步扩展即可,如n=6时排列应为 6 2 4 1 3 5
n为奇数的话以 3 1 4 2为基础,n为偶数的话以 2 4 1 3为基础

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--) {
		int n;
		cin >> n;
		if (n < 4) {
			cout << "-1" << endl;
			continue;
		}
		int i = n;
		if (i % 2 == 0) {
			while (i >= 6) {
				cout << i << " ";
				i -= 2;
			}
			cout << "2 4 ";
			for (int j = 1; j <= n - 1; j+=2) cout << j << " ";
		}
		else {
			while (i >= 1) {
				cout << i << " ";
				i -= 2;
			}
			cout << "4 2 ";
			for (int j = 6; j <= n - 1; j+=2) cout << j << " ";
		}
		cout << endl;
	}
	return 0;
}
原文地址:https://www.cnblogs.com/streamazure/p/12866537.html