查詢前 N 個自然數的良好排列 C++


在這個問題中,我們有一個整數 N。我們的任務是查詢前 N 個自然數的良好排列

排列是指對集合中的所有或部分物件進行排列,並考慮排列的順序。

良好排列是一種排列,其中$1\leqslant{i}\leqslant{N}$,並且遵循:

$P_{pi}\:=\:i$

$P_{p!}\:=\:i$

讓我們來看一個例子來理解這個問題:

Input : N = 1
Output : -1

解決方案方法

解決這個問題的一個簡單方法是找到滿足 pi = i 的排列 p。

然後我們將重新考慮方程以滿足 pi != i。因此,對於滿足$2x \leqslant x$的值 x,我們有 p2x - 1 和 p2k。現在,我們有一個滿足 n 的排列方程的方程。這裡的方程解是……


示例

程式說明了我們解決方案的工作原理

#include <iostream>
using namespace std;
void printGoodPermutation(int n) {
   if (n % 2 != 0)
      cout<<-1;
   else
      for (int i = 1; i <= n / 2; i++)
         cout<<(2*i)<<"\t"<<((2*i) - 1)<<"\t";
}
int main() {
   int n = 4;
   cout<<"Good Permutation of first N natural Numbers : \n"; printGoodPermutation(n);
   return 0;
}

輸出

Good Permutation of first N natural Numbers :
2 1 4 3

更新於:2022年1月27日

204 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告