找到前N个自然数的好排列 C++

WBOY
WBOY 转载
2023-08-25 19:09:13 476浏览

找到前N个自然数的好排列 C++

在这个问题中,我们有一个整数值N。我们的任务是找到前N个自然数的好排列

排列是对一组对象的全部或部分进行安排,考虑到排列的顺序。

好排列是一个排列,其中$1\leqslant{i}\leqslant{N}$并满足以下条件:

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

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

让我们举一个例子来理解这个问题,

Input : N = 1
Output : -1

Solution Approach

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.

Example

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中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除