假设我们有两个字符串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中找到LCS的长度,然后从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) {
//一一检查所有基地
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 << "可以表示";
else
cout << "无法代表";
}输出结果
可以表示