C++中使兩個字串相同的最小成本


假設我們有兩個字串A和B,以及另外兩個成本值CostA和CostB。我們必須找到使A和B相同的最小成本。我們可以從字串中刪除字元,從字串A中刪除的成本是CostA,從字串B中刪除的成本是CostB。從字串中刪除所有字元的成本相同。假設字串A = “wxyz”,B = “wyzx”,CostA為10,CostB為20。那麼輸出將為30。如果我們從兩個字串中都刪除x,則A和B將相同。所以成本是10 + 20 = 30。

這是最長公共子序列問題的一個變體。我們必須找到A和B的最長公共子序列的長度,然後從A和B中減去LCS長度,這樣我們就可以得到要刪除的字元數。

示例

 線上演示

#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";
}

輸出

Can be represented

更新於:2019年10月21日

151 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.