Minimum Cost To Make Two Strings Identical in C++


Suppose we have two strings A and B, and another two cost values like CostA, and CostB. We have to find the minimum cost to make A and B identical. We can delete characters from string, the cost for deleting from string A is CostA, and cost for deleting from string B is CostB. Cost of removing all characters from a string is same. Suppose the string A = “wxyz”, B = “wyzx”, CostA is 10 and CostB is 20. So the output will be 30. If we delete x from both the strings, then A and B will be identical. So cost is 10 + 20 = 30.

This is one of the variation of Longest Common Subsequence problem. We have to find the length of LCS from A and B, then subtract LCS length from A and B, thus we can get the number of characters to be removed.

Example

 Live Demo

#include <iostream>
using namespace std;
bool isRepresentedInDDigits(int num, int d, int base) {
   if (d==1 && num < base)
      return true;
   if (d > 1 && num >= base)
      return isRepresentedInDDigits(num/base, --d, base);
      return false;
}
bool checkNumber(int num, int d) {
   // Check for all bases one by one
   for (int base=2; base<=32; base++)
   if (isRepresentedInDDigits(num, d, base))
   return true;
   return false;
}
int main() {
   int num = 8;
   int dig = 2;
   if(checkNumber(num, dig))
      cout << "Can be represented";
   else
      cout << "Can not be represented";
}

Output

Can be represented

Updated on: 21-Oct-2019

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements