Minimum Cost to make two Numeric Strings Identical in C++

C++Server Side ProgrammingProgramming

Suppose we have two numeric strings A and B. We have to find the minimum cost to make A and B identical. We can perform only one operation, that is we can delete digits from string, the cost for deleting a digit from number is same as the digit value. Suppose the string A = “6789”, B = “7859”, Then we have to delete 6 from A, and delete 5 from B, so the cost will be 5 + 6 = 11.

This is one of the variation of Longest Common Subsequence problem. We have to find the length of LCS from A and B, by using this formula, we can get the minimum cost.

MinimumCost=CostA+CostB−2∗lcscost

Example

 Live Demo

#include <iostream>
using namespace std;
int longest_common_subsequence(int dp[101][101], string a, string b, int a_len,
int b_len) {
   for (int i = 0; i < 100; i++)
   for (int j = 0; j < 100; j++)
   dp[i][j] = -1;
   if (a_len < 0 || b_len < 0) {
      return 0;
   }
   if (dp[a_len][b_len] != -1)
   return dp[a_len][b_len];
   int res = 0;
   if (a[a_len] == b[b_len]) {
      res = int(a[a_len] - 48) + longest_common_subsequence(dp, a, b, a_len - 1, b_len - 1);
   } else
      res = max(longest_common_subsequence(dp, a, b, a_len - 1, b_len),
      longest_common_subsequence(dp, a, b, a_len, b_len - 1));
      dp[a_len][b_len] = res;
      return res;
}
int minCost(string str) {
   int cost = 0;
   for (int i = 0; i < str.length(); i++)
   cost += int(str[i] - 48);
   return cost;
}
int main() {
   string a, b;
   a = "6789";
   b = "7859";
   int dp[101][101];
   cout << "Minimum Cost to make these two numbers identical: " << (minCost(a) + minCost(b) - 2 * longest_common_subsequence(dp, a, b, a.length() - 1, b.length() - 1));
   return 0;
}

Output

Minimum Cost to make these two numbers identical: 11
raja
Published on 21-Oct-2019 13:22:13
Advertisements