Home  >  Article  >  Backend Development  >  Find a good permutation of the first N natural numbers C++

Find a good permutation of the first N natural numbers C++

WBOY
WBOYforward
2023-08-25 19:09:13912browse

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

In this problem, we have an integer value N. Our task is to find a good permutation of the first N natural numbers.

Arrangement is the arrangement of all or part of a set of objects, taking into account the order of arrangement.

Good permutation is a permutation where $1\leqslant{i}\leqslant{N}$ satisfies the following conditions:

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

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

Let us give an example to understand this problem,

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;
}

Output

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

The above is the detailed content of Find a good permutation of the first N natural numbers C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete