Ordene una array dada intercambiando solo pares con GCD como 1

Dada una array arr[] , la tarea es verificar si es posible ordenar la array dada usando cualquier cantidad de operaciones donde en cada operación, dos elementos arr[i] y arr[j] pueden intercambiarse si GCD de arr[ i] y arr[j] es 1 .

Ejemplo:

Entrada: a = {3, 2, 1}
Salida: Posible
explicación: La array dada se puede ordenar intercambiando arr[0] y arr[2], es decir, 3 y 1 como mcd(3, 1) = 1. 

Entrada: arr[] = {10, 15, 6, 2, 9}
Salida: No es posible
Explicación: No es posible ordenar la array dada usando ninguna secuencia de operaciones válidas.

Entrada: arr[] = {1, 9, 3, 7, 2, 4}
Salida: Posible

Enfoque: el problema dado se puede resolver con la ayuda de la recursividad y el retroceso . Cree una función recursiva para iterar sobre todas las inversiones de la array dada , intercambie los elementos invertidos uno a la vez si su GCD es 1 y llame recursivamente a la array restante. En cualquier momento, si la array está ordenada, lo que se puede verificar con la función is_sorted() , devuelve verdadero ; de lo contrario, devuelve falso .

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
#include <bits/stdc++.h>
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<int> 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<int> 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

  <script>
        // JavaScript code for the above approach
 
        // Recursive function to return gcd of a and b
        function __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
        function isPossible(arr)
        {
         
            // If the given array is sorted
            brr = arr.sort(function (a, b) { return a - b })
            if (arr == brr) {
                return true;
            }
             
            // Stores if it is possible to sort
            // the given array
            let res = false;
             
            // Iterate for all possible pairs of
            // Inversions
            for (let i = 0; i < arr.length; i++)
            {
                for (let 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) {
                        let 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
        let arr = [1, 9, 3, 7, 2, 4];
        if (isPossible(arr))
            document.write("Possible")
        else
            document.write("Not Possible");
             
// This code is contributed by Potta Lokesh
 
    </script>
Producción

Possible

Complejidad temporal:  O(N 2 N!)
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por sridiv6 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *