在这个问题中,我们有一个整数值N。我们的任务是找到前N个自然数的好排列。
排列是对一组对象的全部或部分进行安排,考虑到排列的顺序。
好排列是一个排列,其中$1leqslant{i}leqslant{N}$并满足以下条件:
$P_{pi}:=:i$
$P_{p!}:=:i$
让我们举一个例子来理解这个问题,
Input : N = 1 Output : -1
A simple solution to the problem is by findingpermutationsp 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 - 1and 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
#includeusing 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中文网其他相关文章!