Dada una array de strings y una array de enteros donde el i -ésimo entero de la array corresponde al valor de la i -ésima string presente en la array de strings. Ahora elija dos strings que tengan los valores más pequeños en la array de enteros y sume ambos enteros y concatene las strings y agregue tanto el entero resumido a la array de enteros como la string concatenada a la array de strings, y siga repitiendo todo el proceso hasta que solo queda un elemento en ambas arrays. Además, tenga en cuenta que una vez que se seleccionan dos strings y números enteros, se eliminan de la array y se agregan nuevas strings y números enteros a las arrays respectivas.
La tarea es imprimir la string final obtenida.
Ejemplos:
Entrada: str = {“Geeks”, “For”, “Geeks”}, num = {2, 3, 7}
Salida: GeeksForGeeks
Elija 2 y 3, agréguelos y forme “GeeksFor” y 5
Vuelva a agregarlos a las arrays , str = {“GeeksFor”, “Geeks”}, num = {5, 7}
Ahora elija 7 y 5 agréguelos para formar “GeeksForGeeks”, que es la string final.Entrada: str = {“abc”, “def”, “ghi”, “jkl”}, num = {1, 4, 2, 6}
Salida: jklabcghidef
Enfoque: La idea es usar una cola de prioridad , y hacer un par de strings y sus valores correspondientes y almacenarlos en la cola de prioridad y seguir eliminando dos pares de la cola de prioridad, agregando los números enteros y concatenando las strings, y volviéndolos a poner en cola. en la cola de prioridad, hasta que el tamaño de la cola se reduzca a uno, y luego imprima la única string restante en la cola.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Class that represents a pair struct Priority { string s; int count; }; struct Compare { int operator()(Priority a, Priority b) { if (a.count > b.count) return 1; else if (a.count < b.count) return -1; return 0; } }; // Function that prints the final string static void FindString(string str[], int num[], int n) { priority_queue<int, vector<Priority>, Compare> p; // Add all the strings and their corresponding // values to the priority queue for(int i = 0; i < n; i++) { Priority x; x.s = str[i]; x.count = num[i]; p.push(x); } // Take those two strings from the priority // queue whose corresponding integer values // are smaller and add them up as well as // their values and add them back to the // priority queue while there are more // than a single element in the queue while (p.size() > 1) { // Get the minimum valued string Priority x = p.top(); p.pop(); // p.remove(x); // Get the second minimum valued string Priority y = p.top(); p.pop(); // Updated integer value int temp = x.count + y.count; string sb = x.s + y.s; // Create new entry for the queue Priority z; z.count = temp; z.s = sb; // Add to the queue p.push(z); } // Print the only remaining string Priority z = p.top(); p.pop(); cout << z.s << endl; } // Driver code int main() { string str[] = { "Geeks", "For", "Geeks" }; int num[] = { 2, 3, 7 }; int n = sizeof(num) / sizeof(int); FindString(str, num, n); } // This code is contributed by sanjeev2552
Java
// Java implementation of the approach import java.util.*; import java.lang.*; // Class that represents a pair class Priority { String s; int count; } class PQ implements Comparator<Priority> { public int compare(Priority a, Priority b) { if (a.count > b.count) return 1; else if (a.count < b.count) return -1; return 0; } } class GFG { // Function that prints the final string static void FindString(String str[], int num[], int n) { Comparator<Priority> comparator = new PQ(); PriorityQueue<Priority> p = new PriorityQueue<Priority>(comparator); // Add all the strings and their corresponding // values to the priority queue for (int i = 0; i < n; i++) { Priority x = new Priority(); x.s = str[i]; x.count = num[i]; p.add(x); } // Take those two strings from the priority // queue whose corresponding integer values are smaller // and add them up as well as their values and // add them back to the priority queue // while there are more than a single element in the queue while (p.size() > 1) { // Get the minimum valued string Priority x = p.poll(); p.remove(x); // Get the second minimum valued string Priority y = p.poll(); p.remove(y); // Updated integer value int temp = x.count + y.count; String sb = x.s + y.s; // Create new entry for the queue Priority z = new Priority(); z.count = temp; z.s = sb; // Add to the queue p.add(z); } // Print the only remaining string Priority z = p.poll(); System.out.println(z.s); } // Driver code public static void main(String[] args) { String str[] = { "Geeks", "For", "Geeks" }; int num[] = { 2, 3, 7 }; int n = num.length; FindString(str, num, n); } }
Python3
# Python program for the above approach # Function that prints the final string def FindString(str, num, n): p = [] # Add all the strings and their corresponding # values to the priority queue for i in range(n): x = [0,0] x[0] = str[i] x[1] = num[i] p.append(x) # Take those two strings from the priority # queue whose corresponding integer values # are smaller and add them up as well as # their values and add them back to the # priority queue while there are more # than a single element in the queue while (len(p) > 1): # Get the minimum valued string x = p[-1] p.pop() # p.remove(x); # Get the second minimum valued string y = p[-1] p.pop() # Updated integer value temp = x[1] + y[1] sb = x[0] + y[0] # Create new entry for the queue z = [0,0] z[1] = temp z[0] = sb # Add to the queue p.append(z) # Print the only remaining string z = p[-1] p.pop() print(z[0]) # Driver code str = ["Geeks", "For", "Geeks"] num = [2, 3, 7] n = len(num) FindString(str, num, n); # This code is contributed by shinjanpatra
Javascript
<script> // Javascript implementation of the approach // Function that prints the final string function FindString(str, num, n) { var p = []; // Add all the strings and their corresponding // values to the priority queue for(var i = 0; i < n; i++) { var x = [0,0]; x[0] = str[i]; x[1] = num[i]; p.push(x); } // Take those two strings from the priority // queue whose corresponding integer values // are smaller and add them up as well as // their values and add them back to the // priority queue while there are more // than a single element in the queue while (p.length > 1) { // Get the minimum valued string var x = p[p.length-1]; p.pop(); // p.remove(x); // Get the second minimum valued string var y = p[p.length-1]; p.pop(); // Updated integer value var temp = x[1] + y[1]; var sb = x[0] + y[0]; // Create new entry for the queue var z = [0,0]; z[1] = temp; z[0] = sb; // Add to the queue p.push(z); } // Print the only remaining string var z = p[p.length-1]; p.pop(); document.write(z[0] + "<br>"); } // Driver code var str = ["Geeks", "For", "Geeks"]; var num = [2, 3, 7]; var n = num.length; FindString(str, num, n); // This code is contributed by rutvik_56. </script>
GeeksForGeeks
Complejidad de tiempo: O(N * log(N))
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por Sakshi_Srivastava y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA