Cプログラミング
 Computer >> コンピューター >  >> プログラミング >> Cプログラミング

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


最初のN個の自然数があります。私たちのタスクは、2つの連続する要素ごとの絶対差が> 1である、それらの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

#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

  1. C最初のn個の自然数の立方和のプログラム?

    この問題では、最初のn個の自然数の立方体の合計を取得する方法を確認します。ここでは、1からnまで実行されるforループを使用しています。各ステップで、項の3乗を計算し、それを合計に追加します。このプログラムは、完了するまでにO(n)時間かかります。しかし、これをO(1)または一定時間で解きたい場合は、この級数式-を使用できます。 アルゴリズム cubeNNatural(n) begin    sum := 0    for i in range 1 to n, do       sum := sum + i^3 &n

  2. Pythonを使用して、指定されたリスト内の隣接する要素間の差を計算します

    この記事では、リストの隣接する要素の値を差し引くことにより、特定のリストから新しいリストを作成する方法を説明します。そのためのさまざまなアプローチがあります。 追加と範囲あり このアプローチでは、インデックス位置を使用して値を減算し、各減算の結果を新しいリストに追加することにより、リスト要素を反復処理します。 rangeおよびlen関数を使用して、実行する反復回数を追跡します。 例 listA= [25, 97, 13, 62, 14, 102] print("Given list:\n",listA) list_with_diff = [] for n in rang