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
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP