排列前N个自然数,以使所有相邻元素之间的绝对差> 1?
我们有前N个自然数。我们的任务是获取它们的一个排列,其中每两个连续元素之间的绝对差>1。如果不存在这样的排列,则返回-1。
该方法很简单。我们将使用贪婪的方法。我们将按升序或降序排列所有奇数,然后按降序或升序排列所有偶数
算法
安排N(n)
Begin if N is 1, then return 1 if N is 2 or 3, then return -1 as no such permutation is not present even_max and odd_max is set as max even and odd number less or equal to n arrange all odd numbers in descending order arrange all even numbers in descending order End
示例
#include <iostream> using namespace std; void arrangeN(int N) { if (N == 1) { //if N is 1, only that will be placed cout << "1"; return; } if (N == 2 || N == 3) { //for N = 2 and 3, no such permutation is available cout << "-1"; return; } int even_max = -1, odd_max = -1; //查找小于或等于N的最大偶数和奇数 if (N % 2 == 0) { even_max = N; odd_max = N - 1; } else { odd_max = N; even_max = N - 1; } while (odd_max >= 1) { //print all odd numbers in decreasing order cout << odd_max << " "; odd_max -= 2; } while (even_max >= 2) { //print all even numbers in decreasing order cout << even_max << " "; even_max -= 2; } } int main() { int N = 8; arrangeN(N); }
输出结果
7 5 3 1 8 6 4 2