ホームページ  >  記事  >  バックエンド開発  >  最初の N 個の自然数を、隣接する要素間の絶対差が 1 より大きくなるように配置します。

最初の N 個の自然数を、隣接する要素間の絶対差が 1 より大きくなるように配置します。

PHPz
PHPz転載
2023-09-07 22:01:021046ブラウズ

最初の N 個の自然数を、隣接する要素間の絶対差が 1 より大きくなるように配置します。

最初の N 個の自然数があります。私たちのタスクは、すべての連続する 2 つの要素間の絶対差が 1 より大きい、それらの順列を取得することです。そのような取り決めが存在しない場合は、-1 が返されます。

方法は非常に簡単です。貪欲な方法を使用します。すべての奇数を昇順または降順で並べ替えてから、すべての偶数を降順または昇順で並べ替えます。

アルゴリズム

arrangeN(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

Example

中国語の翻訳:

Example

#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;
   //find max even and odd which are less than or equal to 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

以上が最初の N 個の自然数を、隣接する要素間の絶対差が 1 より大きくなるように配置します。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。