Dada una array arr[] de tamaño N , la tarea es encontrar el número mínimo de operaciones para convertir la array en una permutación de [1, n] , en cada operación, un elemento a[i] puede ser reemplazado por a[ i] % d donde d puede ser diferente en cada operación realizada. Si no es posible, imprima -1 .
Ejemplos:
Entrada: arr[] = {5, 4, 10, 8, 1}
Salida: 2
Explicación: En la primera operación eligiendo d = 7, 10 puede ser reemplazado por 10 % 7,
En la segunda operación d = 6, 8 puede ser reemplazado por 8 %6 así que dos operaciones.Entrada: arr[] = {1, 2, 3, 7}
Salida: -1
Enfoque: la tarea se puede resolver utilizando el enfoque codicioso . Este enfoque se basa en el hecho de que cuando se va a obtener el resto r, entonces a[i] > 2*r ie r se encuentra entre el rango [0, a[i]-1/2]
Tomemos un ejemplo: 8 para diferentes d
Tomando, 8 % 7= 1
8%6 = 2
8%5 = 3
8%4 = 0
8%3 = 2
8%2 = 0
8%1=0
Entonces, el número máximo que se puede obtener es 3 usando la operación mod, por lo que cuando queremos obtener un número i en una permutación, el número debe a[i] > 2* i+1
Siga estos pasos para resolver este problema:
- Inicializar un conjunto s
- Recorra la array arr[] e inserte todos los elementos de arr[] en el conjunto.
- Inicializar una variable ops = 0
- Ahora iterar de n a 1
- Compruebe si ya lo ha hecho si lo ha eliminado del conjunto.
- De lo contrario, incremente las operaciones y verifique si el elemento más grande del conjunto < 2* i +1
- Si el mayor del conjunto es < 2* i +1 , establezca ops = -1 y salga del ciclo.
- De lo contrario, bórrelo del conjunto porque podemos hacerlo usando la operación mod.
- Imprime las operaciones
`A continuación se muestra la implementación del enfoque anterior:
C++
// C++ code for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the minimum operations // to convert the array into a permutation of [1, n] void minimum_operations(int arr[], int n) { // Initialize the set set<int> s; // Insert all the elements into the set for (int i = 0; i < n; i++) { s.insert(arr[i]); } // Initialize ops to count the operations int ops = 0; // Traverse from [n to 1] for (int i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.find(i) != s.end()) { s.erase(s.find(i)); } // count the ops because there is no element else { ops++; // Check the largest element of the set auto it = s.end(); it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (*it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.erase(it); } } // Print the result cout << ops << endl; } // Driver Code int main() { // Initialize the value n int arr[] = { 5, 4, 10, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); minimum_operations(arr, n); return 0; }
Java
// Java code for the above approach import java.util.*; class GFG{ // Function to find the minimum operations // to convert the array into a permutation of [1, n] static void minimum_operations(int arr[], int n) { // Initialize the set SortedSet<Integer> s = new TreeSet<Integer>(); // Insert all the elements into the set for (int i = 0; i < n; i++) { s.add(arr[i]); } // Initialize ops to count the operations int ops = 0; // Traverse from [n to 1] for (int i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.contains(i)) { s.remove(i); } // count the ops because there is no element else { ops++; // Check the largest element of the set Integer it = s.last(); it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.remove(it); } } // Print the result System.out.print(ops +"\n"); } // Driver Code public static void main(String[] args) { // Initialize the value n int arr[] = { 5, 4, 10, 8, 1 }; int n = arr.length; minimum_operations(arr, n); } } // This code is contributed by 29AjayKumar
Python3
# Python 3 code for the above approach # Function to find the minimum operations # to convert the array into a permutation of [1, n] def minimum_operations(arr, n): # Initialize the set s = set([]) # Insert all the elements into the set for i in range(n): s.add(arr[i]) # Initialize ops to count the operations ops = 0 # Traverse from [n to 1] for i in range(n, 0, -1): # If we already have i in our # array erase it from the set if (i in s): list(s).remove(i) # count the ops because there is no element else: ops += 1 # Check the largest element of the set it = len(s) it -= 1 # If it is < 2*i +1 we cant get that i # using % operation so there is no way to # create a permutation if (list(s)[it] < 2 * i + 1): ops = -1 break # Erase it if we have processed # it to i by % operation list(s).pop(it) # Print the result print(ops) # Driver Code if __name__ == "__main__": # Initialize the value n arr = [5, 4, 10, 8, 1] n = len(arr) minimum_operations(arr, n) # This code is contributed by ukasp.
C#
// C# code for the above approach using System; using System.Collections.Generic; public class GFG { // Function to find the minimum operations // to convert the array into a permutation of [1, n] static void minimum_operations(int []arr, int n) { // Initialize the set SortedSet<int> s = new SortedSet<int>(); // Insert all the elements into the set for (int i = 0; i < n; i++) { s.Add(arr[i]); } // Initialize ops to count the operations int ops = 0; // Traverse from [n to 1] for (int i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.Contains(i)) { s.Remove(i); } // count the ops because there is no element else { ops++; // Check the largest element of the set int it = s.Max; it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.Remove(it); } } // Print the result Console.Write(ops +"\n"); } // Driver Code public static void Main(String[] args) { // Initialize the value n int []arr = { 5, 4, 10, 8, 1 }; int n = arr.Length; minimum_operations(arr, n); } } // This code is contributed by 29AjayKumar
Javascript
<script> // Javascript code for the above approach // Function to find the minimum operations // to convert the array into a permutation of [1, n] function minimum_operations(arr, n) { // Initialize the set var s = new Set(); // Insert all the elements into the set for (var i = 0; i < n; i++) { s.add(arr[i]); } // Initialize ops to count the operations var ops = 0; // Traverse from [n to 1] for (var i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.has(i)) { s.delete(i); } // count the ops because there is no element else { ops++; // Check the largest element of the set var it = Math.max(...Array.from(s.values())); it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.delete(it); } } // Print the result document.write(ops +"<br>"); } // Driver Code // Initialize the value n var arr = [ 5, 4, 10, 8, 1 ]; var n = arr.length; minimum_operations(arr, n); // This code is contributed by Shubham Singh </script>
2
Complejidad temporal: O(nlogn)
Espacio auxiliar: O(n)
Publicación traducida automáticamente
Artículo escrito por lokeshpotta20 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA