首頁> 後端開發> C++> 主體

求前N個自然數的好排列 C++

WBOY
發布: 2023-08-25 19:09:13
轉載
829 人瀏覽過

找到前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 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.

Example

Program to illustrate the working of our solution

#include  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.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!