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

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

WBOY
Release: 2023-08-25 19:09:13
forward
946 people have browsed it

找到前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
Copy after login

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;
}
Copy after login

Output

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template