📌  相关文章
📜  通过仅交换 GCD 为 1 的对来对给定数组进行排序

📅  最后修改于: 2022-05-13 01:56:05.585000             🧑  作者: Mango

通过仅交换 GCD 为 1 的对来对给定数组进行排序

给定一个数组arr[] ,任务是检查是否可以使用任意数量的操作对给定数组进行排序,其中在每个操作中,如果arr[的 GCD 可以交换两个元素arr[i]arr[j] i]arr[j]1

例子:

方法:给定的问题可以在递归和回溯的帮助下解决。创建一个递归函数来迭代给定数组的所有反转,如果它们的GCD为 1 ,则一次交换一个反转元素,并递归调用剩余的数组。在任何时候,如果可以使用 is_sorted()函数检查的数组已排序,则返回true ,否则返回false

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Recursive function to check if it is
// possible to sort the given array by
// swapping elements with their GCD = 1
bool isPossible(vector arr)
{
    // If the given array is sorted
    if (is_sorted(arr.begin(), arr.end())) {
        return true;
    }
 
    // Stores if it is possible to sort
    // the given array
    bool res = false;
 
    // Iterate for all possible pairs of
    // Inversions
    for (int i = 0; i < arr.size(); i++) {
        for (int j = i + 1; j < arr.size(); j++) {
 
            // If for current inversion,
            // GCD of both elements is 1,
            // GCD of both the indices
            if (arr[i] > arr[j]
                && __gcd(arr[i], arr[j]) == 1) {
                swap(arr[i], arr[j]);
 
                // Recursive Call for the
                // remaining array
                res = (res | isPossible(arr));
 
                // Backtrack
                swap(arr[i], arr[j]);
            }
        }
    }
 
    // Return Answer
    return res;
}
 
// Driver Code
int main()
{
    vector arr = { 1, 9, 3, 7, 2, 4 };
 
    if (isPossible(arr))
        cout << "Possible";
    else
        cout << "Not Possible";
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Recursive function to check if it is
// possible to sort the given array by
// swapping elements with their GCD = 1
static boolean isPossible(int[] arr)
{
   
    // If the given array is sorted
    if (is_sorted(arr)) {
        return true;
    }
 
    // Stores if it is possible to sort
    // the given array
    boolean res = false;
 
    // Iterate for all possible pairs of
    // Inversions
    for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
 
            // If for current inversion,
            // GCD of both elements is 1,
            // GCD of both the indices
            if (arr[i] > arr[j]
                && __gcd(arr[i], arr[j]) == 1) {
                arr = swap(arr,i,j);
 
                // Recursive Call for the
                // remaining array
                res = (res | isPossible(arr));
 
                // Backtrack
                arr = swap(arr,i,j);
            }
        }
    }
 
    // Return Answer
    return res;
}
static int __gcd(int a, int b) 
{ 
    return b == 0? a:__gcd(b, a % b);    
}
static int[] swap(int []arr, int i, int j){
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    return arr;
}
private static boolean is_sorted(int[] a) {
    int i;
    for(i = 0; i < a.length - 1 && a[i] < a[i+1]; i++){}
    return (i == a.length - 1);
}
 
public static void main(String[] args)
{
    int[] arr = { 1, 9, 3, 7, 2, 4 };
 
    if (isPossible(arr))
        System.out.print("Possible");
    else
        System.out.print("Not Possible");
 
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python code for the above approach
 
# Recursive function to return gcd of a and b
def __gcd(a, b):
 
    # Everything divides 0
    if (a == 0):
        return b
    if (b == 0):
        return a
 
    # base case
    if (a == b):
        return a
 
    # a is greater
    if (a > b):
        return __gcd(a - b, b)
    return __gcd(a, b - a)
 
# Recursive function to check if it is
# possible to sort the given array by
# swapping elements with their GCD = 1
def isPossible(arr):
 
    # If the given array is sorted
    brr = sorted(arr)
    if (arr == brr):
        return True
 
    # Stores if it is possible to sort
    # the given array
    res = False
 
    # Iterate for all possible pairs of
    # Inversions
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
 
            # If for current inversion,
            # GCD of both elements is 1,
            # GCD of both the indices
            if (arr[i] > arr[j] and __gcd(arr[i], arr[j]) == 1):
                temp = arr[i]
                arr[i] = arr[j]
                arr[j] = temp
 
                # Recursive Call for the
                # remaining array
                res = (res | isPossible(arr))
 
                # Backtrack
                temp = arr[i]
                arr[i] = arr[j]
                arr[j] = temp
 
    # Return Answer
    return res
 
# Driver Code
arr = [1, 9, 3, 7, 2, 4]
if (isPossible(arr)):
    print("Possible")
else:
    print("Not Possible")
 
# This code is contributed by Saurabh Jaiswal


C#
// C# program for the above approach
using System;
 
public class GFG{
 
// Recursive function to check if it is
// possible to sort the given array by
// swapping elements with their GCD = 1
static bool isPossible(int[] arr)
{
   
    // If the given array is sorted
    if (is_sorted(arr)) {
        return true;
    }
 
    // Stores if it is possible to sort
    // the given array
    bool res = false;
 
    // Iterate for all possible pairs of
    // Inversions
    for (int i = 0; i < arr.Length; i++) {
        for (int j = i + 1; j < arr.Length; j++) {
 
            // If for current inversion,
            // GCD of both elements is 1,
            // GCD of both the indices
            if (arr[i] > arr[j]
                && __gcd(arr[i], arr[j]) == 1) {
                arr = swap(arr,i,j);
 
                // Recursive Call for the
                // remaining array
                res = (res | isPossible(arr));
 
                // Backtrack
                arr = swap(arr,i,j);
            }
        }
    }
 
    // Return Answer
    return res;
}
static int __gcd(int a, int b) 
{ 
    return b == 0? a:__gcd(b, a % b);    
}
static int[] swap(int []arr, int i, int j){
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    return arr;
}
private static bool is_sorted(int[] a) {
    int i;
    for(i = 0; i < a.Length - 1 && a[i] < a[i+1]; i++){}
    return (i == a.Length - 1);
}
 
public static void Main(String[] args)
{
    int[] arr = { 1, 9, 3, 7, 2, 4 };
 
    if (isPossible(arr))
        Console.Write("Possible");
    else
        Console.Write("Not Possible");
 
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出
Possible

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