Dadas dos strings numéricas, A y B. Una string numérica es una string que contiene solo dígitos [‘0’-‘9’].
La tarea es hacer que ambas strings tengan el mismo costo mínimo. La única operación que puede realizar es eliminar un carácter (es decir, un dígito) de cualquiera de las strings (A o B). El costo de borrar un dígito D es de D unidades.
Ejemplos :
Entrada : A = “7135”, B = “135”
Salida : 7
Para que ambas strings sean idénticas, tenemos que eliminar ‘7’ de la string A.
Entrada : A = “9142”, B = “1429”
Salida : 14
Hay 2 formas de hacer que la string «9142» sea idéntica a «1429», es decir, eliminando ‘9’ de ambas strings o eliminando ‘1’, ‘4’ y ‘2’ de ambas strings. Eliminar 142 de ambas strings costará 2*(1+4+2)=14, lo cual es más óptimo que eliminar ‘9’.
Este problema es una variación de un popular problema de programación dinámica: la subsecuencia común más larga . La idea es encontrar la subsecuencia común de peso máximo que será nuestra string idéntica óptima requerida. Para encontrar el costo de la eliminación, reste la suma de la subsecuencia común de peso máximo de la suma de la string A y B.
Peso mínimo para hacer que la string sea idéntica = costoA + costoB – 2*(costo de LCS)
A continuación se muestra la implementación de la idea anterior:
C++
// CPP program to find minimum cost to make // two numeric strings identical #include <bits/stdc++.h> using namespace std; typedef long long int ll; // Function to find weight of LCS int lcs(int dp[101][101], string a, string b, int m, int n) { for (int i = 0; i < 100; i++) for (int j = 0; j < 100; j++) dp[i][j] = -1; if (m < 0 || n < 0) { return 0; } // if this state is already // calculated then return if (dp[m][n] != -1) return dp[m][n]; int ans = 0; if (a[m] == b[n]) { // adding required weight for // particular match ans = int(a[m] - 48) + lcs(dp, a, b, m - 1, n - 1); } else // recurse for left and right child // and store the max ans = max(lcs(dp, a, b, m - 1, n), lcs(dp, a, b, m, n - 1)); dp[m][n] = ans; return ans; } // Function to calculate cost of string int costOfString(string str) { int cost = 0; for (int i = 0; i < str.length(); i++) cost += int(str[i] - 48); return cost; } // Driver code int main() { string a, b; a = "9142"; b = "1429"; int dp[101][101]; // Minimum cost needed to make two strings identical cout << (costOfString(a) + costOfString(b) - 2 * lcs(dp, a, b, a.length() - 1, b.length() - 1)); return 0; }
Java
// Java program to find minimum cost to make // two numeric strings identical import java.io.*; class GFG { // Function to find weight of LCS static int lcs(int dp[][], String a, String b, int m, int n) { for (int i = 0; i < 100; i++) for (int j = 0; j < 100; j++) dp[i][j] = -1; if (m < 0 || n < 0) { return 0; } // if this state is already // calculated then return if (dp[m][n] != -1) return dp[m][n]; int ans = 0; if (a.charAt(m) == b.charAt(n)) { // adding required weight for // particular match ans = (a.charAt(m) - 48) + lcs(dp, a, b, m - 1, n - 1); } else // recurse for left and right child // and store the max ans = Math.max(lcs(dp, a, b, m - 1, n), lcs(dp, a, b, m, n - 1)); dp[m][n] = ans; return ans; } // Function to calculate cost of string static int costOfString(String str) { int cost = 0; for (int i = 0; i < str.length(); i++) cost += (str.charAt(i) - 48); return cost; } // Driver code public static void main (String[] args) { String a, b; a = "9142"; b = "1429"; int dp[][] = new int[101][101]; // Minimum cost needed to make two strings identical System.out.print( (costOfString(a) + costOfString(b) - 2 * lcs(dp, a, b, a.length() - 1, b.length() - 1))); } } // This code is contributed by anuj_67.
Python 3
# Python 3 program to find minimum cost # to make two numeric strings identical # Function to find weight of LCS def lcs(dp, a, b, m, n): for i in range(100): for j in range(100): dp[i][j] = -1 if (m < 0 or n < 0) : return 0 # if this state is already calculated # then return if (dp[m][n] != -1): return dp[m][n] ans = 0 if (a[m] == b[n]): # adding required weight for # particular match ans = (ord(a[m]) - 48) + lcs(dp, a, b, m - 1, n - 1) else: # recurse for left and right child # and store the max ans = max(lcs(dp, a, b, m - 1, n), lcs(dp, a, b, m, n - 1)) dp[m][n] = ans return ans # Function to calculate cost of string def costOfString(s): cost = 0 for i in range(len(s)): cost += (ord(s[i]) - 48) return cost # Driver code if __name__ == "__main__": a = "9142" b = "1429" dp = [[0 for x in range(101)] for y in range(101)] # Minimum cost needed to make two # strings identical print(costOfString(a) + costOfString(b) - 2 * lcs(dp, a, b, len(a) - 1, len(b) - 1)) # This code is contributed by ita_c
C#
// C# program to find minimum cost to make // two numeric strings identical using System; public class GFG { // Function to find weight of LCS static int lcs(int [,]dp, String a, String b, int m, int n) { for (int i = 0; i < 100; i++) for (int j = 0; j < 100; j++) dp[i,j] = -1; if (m < 0 || n < 0) { return 0; } // if this state is already // calculated then return if (dp[m,n] != -1) return dp[m,n]; int ans = 0; if (a[m] == b[n]) { // adding required weight for // particular match ans = (a[m] - 48) + lcs(dp, a, b, m - 1, n - 1); } else // recurse for left and right child // and store the max ans = Math.Max(lcs(dp, a, b, m - 1, n), lcs(dp, a, b, m, n - 1)); dp[m,n] = ans; return ans; } // Function to calculate cost of string static int costOfString(String str) { int cost = 0; for (int i = 0; i < str.Length; i++) cost += (str[i] - 48); return cost; } // Driver code public static void Main () { String a, b; a = "9142"; b = "1429"; int [,]dp = new int[101,101]; // Minimum cost needed to make two strings identical Console.Write( (costOfString(a) + costOfString(b) - 2 * lcs(dp, a, b, a.Length- 1, b.Length - 1))); } } // This code is contributed by Rajput-Ji
Javascript
<script> // Javascript program to find minimum cost to make // two numeric strings identical // Function to find weight of LCS function lcs(dp,a,b,m,n) { if (m < 0 || n < 0) { return 0; } // if this state is already // calculated then return if (dp[m][n] != -1) return dp[m][n]; let ans = 0; if (a[m] == b[n]) { // adding required weight for // particular match ans = (a[m].charCodeAt(0) - 48) + lcs(dp, a, b, m - 1, n - 1); } else // recurse for left and right child // and store the max ans = Math.max(lcs(dp, a, b, m - 1, n), lcs(dp, a, b, m, n - 1)); dp[m][n] = ans; return ans; } // Function to calculate cost of string function costOfString(str) { let cost = 0; for (let i = 0; i < str.length; i++) cost += (str[i].charCodeAt(0) - 48); return cost; } // Driver code let a = "9142"; let b = "1429"; let dp=new Array(101); for(let i=0;i<dp.length;i++) { dp[i]=new Array(101); for(let j=0;j<101;j++) { dp[i][j]=-1; } } // Minimum cost needed to make two strings identical document.write( (costOfString(a) + costOfString(b) - 2 * lcs(dp, a, b, a.length - 1, b.length - 1))); // This code is contributed by avanitrachhadiya2155 </script>
14
Publicación traducida automáticamente
Artículo escrito por Kushdeep_Mittal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA