📌  相关文章
📜  相邻对的按位与乘积超过 0 的前 N 个自然数的排列

📅  最后修改于: 2021-09-03 03:36:22             🧑  作者: Mango

给定一个正整数N ,任务是找到前N 个自然数的排列,使得相邻元素对的按位 AND( & ) 的乘积大于0 。如果没有找到这样的排列,则打印“不可能”

例子:

朴素方法:解决此问题的最简单方法是生成前 N 个自然数的所有可能排列。对于每个排列,检查其相邻元素的按位与的乘积是否大于0 。如果发现为真,则打印该排列。否则,打印“不可能”

时间复杂度: O(N * N!)
辅助空间: O(1)

有效的方法:可以根据以下观察来解决问题:

请按照以下步骤解决问题:

  • 如果N2的幂,则打印“不可能”
  • 初始化一个数组,比如arr[]来存储满足给定条件的前N 个自然数的排列。
  • 迭代范围[1, N] ,并更新arr[i] = i
  • 更新数组的前三个元素,使其相邻元素的按位与必须大于0 ,即arr[1] = 2arr[2] = 3arr[3] = 1
  • 迭代范围[4, N] 。对于每个i值,检查i是否是2的幂。如果发现为真,则swap(arr[i], arr[i+1])
  • 最后,打印arr[]

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to check if a number
// is a power of 2 or not
bool isPowerOfTwo(int n)
{
    if (n == 0)
        return false;
 
    return (ceil(log2(n))
            == floor(log2(n)));
}
 
// Function to find the permutation of first N
// natural numbers such that the product of
// bitwise AND  of adjacent elements is > 0
void findThePermutation(int N)
{
 
    // Base Case, If N = 1, print 1
    if (N == 1) {
        cout << "1";
        return;
    }
 
    // If N is a power of 2,
    // print "Not Possible"
    if (isPowerOfTwo(N)) {
        cout << "Not Possible";
        return;
    }
 
    // Stores permutation of first N
    // natural numbers that satisfy
    // the condition
    int arr[N + 1];
 
    // Iterate over the range [1, N]
    for (int i = 1; i <= N; i++) {
 
        // Update arr[i]
        arr[i] = i;
    }
 
    // Update arr[1], arr[2] and arr[3]
    arr[1] = 2, arr[2] = 3, arr[3] = 1;
 
    // Iterate over the range [4, N]
    for (int i = 4; i <= N; i++) {
 
        // If i is a power of 2
        if (isPowerOfTwo(i)) {
 
            // Swap adjacent elements
            swap(arr[i], arr[i + 1]);
 
            // Update i
            i++;
        }
    }
 
    // Print the array
    for (int i = 1; i <= N; i++)
        cout << arr[i] << " ";
}
 
// Driver Code
int main()
{
    // Input
    int N = 5;
 
    // Function Call
    findThePermutation(N);
 
    return 0;
}


Java
// Java program to implement the above approach
class GFG
{
 
    // Function to calculate the
    // log base 2 of an integer
    public static int log2(int N)
    {
   
        // calculate log2 N indirectly
        // using log() method
        int result = (int)(Math.log(N) / Math.log(2));  
        return result;
    }
     
    // Function to check if a number
    // is a power of 2 or not
    static boolean isPowerOfTwo(int n)
    {
        if (n == 0)
            return false;   
        return Math.ceil(log2(n)) == Math.floor(log2(n));
    }
     
    // Function to find the permutation of first N
    // natural numbers such that the product of
    // bitwise AND  of adjacent elements is > 0
    static void findThePermutation(int N)
    {
     
        // Base Case, If N = 1, print 1
        if (N == 1)
        {
            System.out.print("1");
            return;
        }
     
        // If N is a power of 2,
        // print "Not Possible"
        if (isPowerOfTwo(N) == false)
        {
            System.out.print("Not Possible");
            return;
        }
     
        // Stores permutation of first N
        // natural numbers that satisfy
        // the condition
        int arr[] = new int[N + 1];
     
        // Iterate over the range [1, N]
        for (int i = 1; i <= N; i++)
        {
     
            // Update arr[i]
            arr[i] = i;
        }
     
        // Update arr[1], arr[2] and arr[3]
        arr[1] = 2; arr[2] = 3; arr[3] = 1;  
        int temp;
         
        // Iterate over the range [4, N]
        for (int i = 4; i <= N; i++)
        {
     
            // If i is a power of 2
            if (isPowerOfTwo(i) == true)
            {
     
                // Swap adjacent elements
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp ;
                 
                // Update i
                i++;
            }
        }
     
        // Print the array
        for (int i = 1; i <= N; i++)
            System.out.print(arr[i] + " ");
    }
     
    // Driver Code
    public static void main(String[] args)
    {
       
        // Input
        int N = 5;
     
        // Function Call
        findThePermutation(N);
    }
}
 
// This code is contributed by AnkThon


Python3
# Python3 program to implement
# the above approach
from math import ceil, floor, log2
 
# Function to check if a number
# is a power of 2 or not
def isPowerOfTwo(n):
     
    if (n == 0):
        return False
         
    return (ceil(log2(n)) == floor(log2(n)))
 
# Function to find the permutation of first N
# natural numbers such that the product of
# bitwise AND of adjacent elements is > 0
def findThePermutation(N):
     
    # Base Case, If N = 1, pr1
    if (N == 1):
        print("1")
        return
 
    # If N is a power of 2,
    # print "Not Possible"
    if (isPowerOfTwo(N)):
        print("Not Possible")
        return
 
    # Stores permutation of first N
    # natural numbers that satisfy
    # the condition
    arr = [i for i in range(N + 1)]
 
    # Iterate over the range [1, N]
    for i in range(1, N + 1):
         
        # Update arr[i]
        arr[i] = i
 
    # Update arr[1], arr[2] and arr[3]
    arr[1], arr[2], arr[3] = 2, 3, 1
     
    # Iterate over the range [4, N]
    for i in range(4, N + 1):
         
        # If i is a power of 2
        if (isPowerOfTwo(i)):
             
            # Swap adjacent elements
            arr[i], arr[i + 1] = arr[i + 1], arr[i]
 
            # Update i
            i += 1
 
    # Print the array
    for i in range(1, N + 1):
        print(arr[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Input
    N = 5
     
    # Function Call
    findThePermutation(N)
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement the above approach
using System;
class GFG
{
 
    // Function to calculate the
    // log base 2 of an integer
    public static int log2(int N)
    {
   
        // calculate log2 N indirectly
        // using log() method
        int result = (int)(Math.Log(N) / Math.Log(2));  
        return result;
    }
     
    // Function to check if a number
    // is a power of 2 or not
    static bool isPowerOfTwo(int n)
    {
        if (n == 0)
            return false;   
        return Math.Ceiling((double)log2(n)) ==
          Math.Floor((double)log2(n));
    }
     
    // Function to find the permutation of first N
    // natural numbers such that the product of
    // bitwise AND  of adjacent elements is > 0
    static void findThePermutation(int N)
    {
     
        // Base Case, If N = 1, print 1
        if (N == 1)
        {
            Console.Write("1");
            return;
        }
     
        // If N is a power of 2,
        // print "Not Possible"
        if (isPowerOfTwo(N) == false)
        {
            Console.Write("Not Possible");
            return;
        }
     
        // Stores permutation of first N
        // natural numbers that satisfy
        // the condition
        int []arr = new int[N + 1];
     
        // Iterate over the range [1, N]
        for (int i = 1; i <= N; i++)
        {
     
            // Update arr[i]
            arr[i] = i;
        }
     
        // Update arr[1], arr[2] and arr[3]
        arr[1] = 2; arr[2] = 3; arr[3] = 1;  
        int temp;
         
        // Iterate over the range [4, N]
        for (int i = 4; i <= N; i++)
        {
     
            // If i is a power of 2
            if (isPowerOfTwo(i) == true)
            {
     
                // Swap adjacent elements
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp ;
                 
                // Update i
                i++;
            }
        }
     
        // Print the array
        for (int i = 1; i <= N; i++)
            Console.Write(arr[i] + " ");
    }
     
    // Driver Code
    public static void Main(String[] args)
    {
       
        // Input
        int N = 5;
     
        // Function Call
        findThePermutation(N);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
2 3 1 5 4

时间复杂度: O(N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live