在这个问题中,我们有一个整数值N。我们的任务是找到前N个自然数的好排列。
排列是对一组对象的全部或部分进行安排,考虑到排列的顺序。
好排列是一个排列,其中$1\leqslant{i}\leqslant{N}$并满足以下条件:
$P_{pi}\:=\:i$
立即学习“C++免费学习笔记(深入)”;
$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中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号