Permutación lexicográficamente más grande de la array tal que a[i] = a[i-1] + mcd(a[i-1], a[i-2])

Dada una array arr[] de tamaño N ( N > 2 ). La tarea es encontrar la permutación lexicográficamente más grande de la array tal que arr[i] = arr[i – 1] + mcd(arr[i – 1], arr[i – 2]) . Si no es posible encontrar dicho arreglo, imprima -1 .
Ejemplos: 
 

Entrada: arr[] = {4, 6, 2, 5, 3} 
Salida: 2 3 4 5 6 
4 = 3 + mcd(2, 3) 
5 = 4 + mcd(3, 4) 
6 = 5 + mcd( 4, 5)
Entrada: arr[] = {1, 6, 8} 
Salida: -1 
 

Enfoque: si está pensando en una solución que implique ordenar la array y luego verificar si se cumple la condición gcd. Tienes razón en parte, los números deben estar en secuencia creciente, pero excepto en un caso en el que podría haber un número que podría aparecer al comienzo de la permutación. Por ejemplo, arr[] = {2, 4, 6, 8, 8} en este caso, 8 se puede colocar al comienzo de la array para obtener la permutación {8, 2, 4, 6, 8}. 
Casos de esquina: 
 

  • No podías tener más de dos elementos cuya frecuencia fuera mayor a 1.
  • Si tuviera dos ceros en la array, la única permutación posible sería todos los ceros.

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

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find elements of vector
void Print(vector<int>& ans)
{
    for (auto i : ans)
        cout << i << " ";
}
 
// Function to find the lexicographically largest
// permutation that satisfies the given condition
void Permutation(int a[], int n)
{
    int flag = 0, pos;
 
    // To store the required ans
    vector<int> ans;
 
    // Sort the array
    sort(a, a + n);
 
    for (int i = 2; i < n; i++) {
 
        // If need to make arrangement
        if (a[i] != a[i - 1] + __gcd(a[i - 1], a[i - 2])) {
            flag = 1;
            pos = i;
            break;
        }
    }
 
    // If possible then check for lexicographically
    // larger permutation (if any possible)
    if (flag == 0) {
 
        // If larger arrangement is possible
        if (a[1] == a[0] + __gcd(a[0], a[n - 1])) {
            ans.push_back(a[n - 1]);
            for (int i = 0; i < n - 1; i++)
                ans.push_back(a[i]);
 
            Print(ans);
            return;
        }
 
        // If no other arrangement is possible
        else {
            for (int i = 0; i < n; i++)
                ans.push_back(a[i]);
 
            Print(ans);
            return;
        }
    }
 
    // Need to re-arrange the array
    else {
 
        // If possible, place at first position
        if (a[1] == a[0] + __gcd(a[pos], a[0])) {
            flag = 0;
            for (int i = n - 1; i > pos + 2; i--) {
 
                // If even after one arrangement its impossible
                // to get the required array
                if (a[i] != a[i - 1] + __gcd(a[i - 1], a[i - 2])) {
                    flag = 1;
                    break;
                }
            }
 
            if (flag == 0 and pos < n - 1) {
 
                // If it is not possible to get
                // the required array
                if (a[pos + 1]
                    != a[pos - 1] + __gcd(a[pos - 1], a[pos - 2]))
                    flag = 1;
            }
 
            if (flag == 0 and pos < n - 2) {
 
                // If it is not possible to get
                // the required array
                if (a[pos + 2]
                    != a[pos + 1] + __gcd(a[pos - 1], a[pos + 1]))
                    flag = 1;
            }
 
            // If it is possible to get the answer
            if (flag == 0) {
                ans.push_back(a[pos]);
                for (int i = 0; i < n; i++)
                    if (i != pos)
                        ans.push_back(a[i]);
 
                Print(ans);
                return;
            }
        }
    }
 
    ans.push_back(-1);
    Print(ans);
}
 
// Driver code
int main()
{
    int a[] = { 4, 6, 2, 8, 8 };
    int n = sizeof(a) / sizeof(a[0]);
 
    Permutation(a, n);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to find elements of vector
static void Print(Vector<Integer> ans)
{
    for (Integer i : ans)
        System.out.print(i + " ");
}
 
// Function to find the lexicographically largest
// permutation that satisfies the given condition
static void Permutation(int a[], int n)
{
    int flag = 0, pos = 0;
 
    // To store the required ans
    Vector<Integer> ans = new Vector<Integer>();
 
    // Sort the array
    Arrays.sort(a);
 
    for (int i = 2; i < n; i++)
    {
 
        // If need to make arrangement
        if (a[i] != a[i - 1] + __gcd(a[i - 1],
                                     a[i - 2]))
        {
            flag = 1;
            pos = i;
            break;
        }
    }
 
    // If possible then check for lexicographically
    // larger permutation (if any possible)
    if (flag == 0)
    {
 
        // If larger arrangement is possible
        if (a[1] == a[0] + __gcd(a[0],
                                 a[n - 1]))
        {
            ans.add(a[n - 1]);
            for (int i = 0; i < n - 1; i++)
                ans.add(a[i]);
 
            Print(ans);
            return;
        }
 
        // If no other arrangement is possible
        else
        {
            for (int i = 0; i < n; i++)
                ans.add(a[i]);
 
            Print(ans);
            return;
        }
    }
 
    // Need to re-arrange the array
    else
    {
 
        // If possible, place at first position
        if (a[1] == a[0] + __gcd(a[pos], a[0]))
        {
            flag = 0;
            for (int i = n - 1; i > pos + 2; i--)
            {
 
                // If even after one arrangement
                // its impossible to get
                // the required array
                if (a[i] != a[i - 1] + __gcd(a[i - 1],
                                             a[i - 2]))
                {
                    flag = 1;
                    break;
                }
            }
 
            if (flag == 0 & pos < n - 1)
            {
 
                // If it is not possible to get
                // the required array
                if (a[pos + 1]
                    != a[pos - 1] + __gcd(a[pos - 1],
                                          a[pos - 2]))
                    flag = 1;
            }
 
            if (flag == 0 & pos < n - 2)
            {
 
                // If it is not possible to get
                // the required array
                if (a[pos + 2]
                    != a[pos + 1] + __gcd(a[pos - 1],
                                          a[pos + 1]))
                    flag = 1;
            }
 
            // If it is possible to get the answer
            if (flag == 0)
            {
                ans.add(a[pos]);
                for (int i = 0; i < n; i++)
                    if (i != pos)
                        ans.add(a[i]);
 
                Print(ans);
                return;
            }
        }
    }
 
    ans.add(-1);
    Print(ans);
}
 
static int __gcd(int a, int b)
{
    if (b == 0)
        return a;
    return __gcd(b, a % b);    
}
 
// Driver code
public static void main(String[] args)
{
    int a[] = { 4, 6, 2, 8, 8 };
    int n = a.length;
 
    Permutation(a, n);
    }
}
 
// This code is contributed
// by PrinciRaj1992

Python3

# Python 3 implementation of the approach
from math import gcd
 
# Function to find elements of vector
def Print(ans):
    for i in range(len(ans)):
        print(ans[i], end = " ")
 
# Function to find the lexicographically
# largest permutation that satisfies
# the given condition
def Permutation(a, n):
    flag = 0
 
    # To store the required ans
    ans = []
 
    # Sort the array
    a.sort(reverse = False)
 
    for i in range(2, n, 1):
         
        # If need to make arrangement
        if (a[i] != a[i - 1] +
        gcd(a[i - 1], a[i - 2])):
            flag = 1
            pos = i
            break
 
    # If possible then check for
    # lexicographically larger
    # permutation (if any possible)
    if (flag == 0):
         
        # If larger arrangement is possible
        if (a[1] == a[0] +
        gcd(a[0], a[n - 1])):
            ans.append(a[n - 1])
            for i in range(n - 1):
                ans.append(a[i])
 
            Print(ans)
            return
 
        # If no other arrangement is possible
        else:
            for i in range(n):
                ans.append(a[i])
 
            Print(ans)
            return
 
    # Need to re-arrange the array
    else:
         
        # If possible, place at first position
        if (a[1] == a[0] +
        gcd(a[pos], a[0])):
            flag = 0
            i = n - 1
            while(i > pos + 2):
                 
                # If even after one arrangement its
                # impossible to get the required array
                if (a[i] != a[i - 1] +
                gcd(a[i - 1], a[i - 2])):
                    flag = 1
                    break
 
                i -= 1
             
            if (flag == 0 and pos < n - 1):
                 
                # If it is not possible to get
                # the required array
                if (a[pos + 1] != a[pos - 1] +
                gcd(a[pos - 1], a[pos - 2])):
                    flag = 1
 
            if (flag == 0 and pos < n - 2):
                 
                # If it is not possible to get
                # the required array
                if (a[pos + 2] != a[pos + 1] +
                gcd(a[pos - 1], a[pos + 1])):
                    flag = 1
 
            # If it is possible to get the answer
            if (flag == 0):
                ans.append(a[pos])
                for i in range(n):
                    if (i != pos):
                        ans.append(a[i])
 
                Print(ans)
                return
 
    ans.append(-1)
    Print(ans)
 
# Driver code
if __name__ == '__main__':
    a = [4, 6, 2, 8, 8]
    n = len(a)
 
    Permutation(a, n)
     
# This code is contributed by
# Surendra_Gangwar

C#

// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to find elements of vector
static void Print(List<int> ans)
{
    foreach (int i in ans)
        Console.Write(i + " ");
}
 
// Function to find the lexicographically largest
// permutation that satisfies the given condition
static void Permutation(int []a, int n)
{
    int flag = 0, pos = 0;
 
    // To store the required ans
    List<int> ans = new List<int>();
 
    // Sort the array
    Array.Sort(a);
 
    for (int i = 2; i < n; i++)
    {
 
        // If need to make arrangement
        if (a[i] != a[i - 1] + __gcd(a[i - 1],
                                     a[i - 2]))
        {
            flag = 1;
            pos = i;
            break;
        }
    }
 
    // If possible then check for lexicographically
    // larger permutation (if any possible)
    if (flag == 0)
    {
 
        // If larger arrangement is possible
        if (a[1] == a[0] + __gcd(a[0],
                                 a[n - 1]))
        {
            ans.Add(a[n - 1]);
            for (int i = 0; i < n - 1; i++)
                ans.Add(a[i]);
 
            Print(ans);
            return;
        }
 
        // If no other arrangement is possible
        else
        {
            for (int i = 0; i < n; i++)
                ans.Add(a[i]);
 
            Print(ans);
            return;
        }
    }
 
    // Need to re-arrange the array
    else
    {
 
        // If possible, place at first position
        if (a[1] == a[0] + __gcd(a[pos], a[0]))
        {
            flag = 0;
            for (int i = n - 1; i > pos + 2; i--)
            {
 
                // If even after one arrangement
                // its impossible to get
                // the required array
                if (a[i] != a[i - 1] + __gcd(a[i - 1],
                                             a[i - 2]))
                {
                    flag = 1;
                    break;
                }
            }
 
            if (flag == 0 & pos < n - 1)
            {
 
                // If it is not possible to get
                // the required array
                if (a[pos + 1]
                    != a[pos - 1] + __gcd(a[pos - 1],
                                          a[pos - 2]))
                    flag = 1;
            }
 
            if (flag == 0 & pos < n - 2)
            {
 
                // If it is not possible to get
                // the required array
                if (a[pos + 2]
                    != a[pos + 1] + __gcd(a[pos - 1],
                                          a[pos + 1]))
                    flag = 1;
            }
 
            // If it is possible to get the answer
            if (flag == 0)
            {
                ans.Add(a[pos]);
                for (int i = 0; i < n; i++)
                    if (i != pos)
                        ans.Add(a[i]);
 
                Print(ans);
                return;
            }
        }
    }
 
    ans.Add(-1);
    Print(ans);
}
 
static int __gcd(int a, int b)
{
    if (b == 0)
        return a;
    return __gcd(b, a % b);    
}
 
// Driver code
public static void Main(String[] args)
{
    int []a = { 4, 6, 2, 8, 8 };
    int n = a.Length;
 
    Permutation(a, n);
    }
}
 
// This code is contributed by Rajput-Ji

Javascript

<script>
 
// JavaScript implementation of the approach
 
 
// Function to find elements of vector
function Print(ans) {
    for (let i of ans)
        document.write(i + " ");
}
 
// Function to find the lexicographically largest
// permutation that satisfies the given condition
function Permutation(a, n) {
    let flag = 0, pos = 0;
 
    // To store the required ans
    let ans = new Array();
 
    // Sort the array
    a.sort((a, b) => a - b);
 
    for (let i = 2; i < n; i++) {
 
        // If need to make arrangement
        if (a[i] != a[i - 1] + __gcd(a[i - 1],
            a[i - 2])) {
            flag = 1;
            pos = i;
            break;
        }
    }
 
    // If possible then check for lexicographically
    // larger permutation (if any possible)
    if (flag == 0) {
 
        // If larger arrangement is possible
        if (a[1] == a[0] + __gcd(a[0],
            a[n - 1])) {
            ans.push(a[n - 1]);
            for (let i = 0; i < n - 1; i++)
                ans.push(a[i]);
 
            Print(ans);
            return;
        }
 
        // If no other arrangement is possible
        else {
            for (let i = 0; i < n; i++)
                ans.push(a[i]);
 
            Print(ans);
            return;
        }
    }
 
    // Need to re-arrange the array
    else {
 
        // If possible, place at first position
        if (a[1] == a[0] + __gcd(a[pos], a[0])) {
            flag = 0;
            for (let i = n - 1; i > pos + 2; i--) {
 
                // If even after one arrangement
                // its impossible to get
                // the required array
                if (a[i] != a[i - 1] + __gcd(a[i - 1],
                    a[i - 2])) {
                    flag = 1;
                    break;
                }
            }
 
            if (flag == 0 & pos < n - 1) {
 
                // If it is not possible to get
                // the required array
                if (a[pos + 1]
                    != a[pos - 1] + __gcd(a[pos - 1],
                        a[pos - 2]))
                    flag = 1;
            }
 
            if (flag == 0 & pos < n - 2) {
 
                // If it is not possible to get
                // the required array
                if (a[pos + 2]
                    != a[pos + 1] + __gcd(a[pos - 1],
                        a[pos + 1]))
                    flag = 1;
            }
 
            // If it is possible to get the answer
            if (flag == 0) {
                ans.push(a[pos]);
                for (let i = 0; i < n; i++)
                    if (i != pos)
                        ans.push(a[i]);
 
                Print(ans);
                return;
            }
        }
    }
 
    ans.push(-1);
    Print(ans);
}
 
function __gcd(a, b) {
    if (b == 0)
        return a;
    return __gcd(b, a % b);
}
 
// Driver code
 
let a = [4, 6, 2, 8, 8];
let n = a.length;
 
Permutation(a, n);
 
// This code is contributed by _saurabh_jaiswal
 
</script>
Producción: 

8 2 4 6 8

 

Complejidad del tiempo: O(NlogN)
 

Publicación traducida automáticamente

Artículo escrito por pawan_asipu 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 *