두 개의 숫자 문자열 A와 B가 있다고 가정합니다. A와 B를 동일하게 만드는 최소 비용을 찾아야 합니다. 우리는 단 하나의 작업만 수행할 수 있습니다. 즉, 문자열에서 숫자를 삭제할 수 있습니다. 숫자에서 숫자를 삭제하는 비용은 숫자 값과 동일합니다. 문자열 A ="6789", B ="7859"라고 가정하면 A에서 6을 삭제하고 B에서 5를 삭제해야 하므로 비용은 5 + 6 =11이 됩니다.
이것은 Longest Common Subsequence 문제의 변형 중 하나입니다. A와 B에서 LCS의 길이를 구해야 하며, 이 공식을 사용하여 최소 비용을 얻을 수 있습니다.
MinimumCost=CostA+CostB−2*lcs비용
예시
#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;
} 출력
Minimum Cost to make these two numbers identical: 11