在這個問題中,我們有一個整數值N。我們的任務是找到前N個自然數的好排列。
排列是對一組物件的全部或部分進行安排,考慮到排列的順序。
好排列是一個排列,其中$1\leqslant{i}\leqslant{N}$並滿足以下條件:
$P_{pi}\:= \:i$
$P_{p!}\:=\:i$
#讓我們舉出一個例子來理解這個問題,
Input : N = 1 Output : -1
A simple solution to the problem is by finding permutations p such that pi = i.
Then we will reconsider the equation to satisfy pi != i. So, for a value x such that $2x \leqslant x$, we have p2x - 1 and p2k. Now, we have an equation that satisfies the permutation equation for n. Here, the solution for the equation.
Program to illustrate the working of our solution
#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
以上是求前N個自然數的好排列 C++的詳細內容。更多資訊請關注PHP中文網其他相關文章!