📜  找出前N个自然数的良好排列

📅  最后修改于: 2021-06-25 19:49:28             🧑  作者: Mango

给定整数N ,任务是打印前N个自然数的良好排列。让我们将置换的i元素表示为p i
好的排列是这样的排列:对于所有1≤i≤N ,以下等式成立,

  • p pi =我
  • !=我

基本上,以上表达式表示没有值等于其位置。
如果不存在这样好的排列,则打印-1
例子:

方法:考虑置换p ,使p i = i 。实际上, p是一个从1N的数字序列,并且p pi = i
现在唯一的技巧是改变排列以满足第二个等式,即p i != i 。让我们交换每两个连续的元素。更正式地讲,对于每个k2k≤n,让我们交换p 2k – 1p 2k 。很容易看出,获得的置换满足每个n的两个方程,唯一的例外是:当n为奇数时,没有答案,我们应该打印-1
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to print the good permutation
// of first N natural numbers
int printPermutation(int n)
{
    // If n is odd
    if (n % 2 != 0)
        cout << -1;
 
    // Otherwise
    else
        for (int i = 1; i <= n / 2; i++)
            cout << 2 * i << " " << 2 * i - 1 << " ";
}
 
// Driver code
int main()
{
    int n = 4;
    printPermutation(n);
 
    return 0;
}


Java
// Java implementation of the approach
 
class GFG
{
 
// Function to print the good permutation
// of first N natural numbers
static int printPermutation(int n)
{
    // If n is odd
    if (n % 2 != 0)
    {
        System.out.println("-1");
    }
 
    // Otherwise
    else
        for (int i = 1; i <= n / 2; i++)
        {
            System.out.print(2 * i + " " + ((2 * i) - 1) + " ");
        }
         
    return n;
     
}
 
// Driver code
public static void main(String []args)
{
    int n = 4;
    printPermutation(n);
}
}
 
// This code contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
 
# Function to print the good permutation
# of first N natural numbers
def printPermutation(n):
     
    # If n is odd
    if (n % 2 != 0):
        print(-1);
 
    # Otherwise
    else:
        for i in range(1, (n // 2) + 1):
            print((2 * i), (2 * i - 1), end = " ");
 
# Driver code
n = 4;
printPermutation(n);
 
# This code is contributed by mits


C#
// C# implementation of the approach
using System;
 
class GFG {
 
// Function to print the good permutation
// of first N natural numbers
static int printPermutation(int n)
{
    // If n is odd
    if (n % 2 != 0)
    {
        Console.WriteLine("-1");
    }
 
    // Otherwise
    else
        for (int i = 1; i <= n / 2; i++)
        {
            Console.WriteLine(2 * i + " " + ((2 * i) - 1) + " ");
        }
         
    return n;
     
}
 
// Driver code
public static void Main(String []args)
{
    int n = 4;
    printPermutation(n);
}
}
 
// This code is contributed by Kirti_Mangal


PHP


Javascript


输出:
2 1 4 3

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。