题目描述:
给定两个字符串str1和str2,再给定三个整数ic,dc,rc,分别代表插入、删除、替换一个字符的代价,返回将str1编辑成str2的最小代价。
举例:
str1="abc" str2="adc" ic=5 dc=3 rc=2,从"abc"编辑到"adc"把b替换成d代价最小,为2;
str1="abc" str2="adc" ic=5 dc=3 rc=10,从"abc"编辑到"adc",先删除b再插入d代价最小,为8;
分成四种情况依次处理 1 #include<iostream> 2 #include<algorithm> 3 #include<string> 4 using namespace std; 5 int dp[100][100] = { 0 }; 6 int main(void) 7 { 8 int ic = 5, dc = 3, rc = 2; 9 string s1; 10 string s2; 11 while(cin >> s1 >> s2) 12 { 13 int length1 = s1.length(); 14 int length2 = s2.length(); 15 int i, j; 16 for (j = 0; j <= length2; ++j) 17 { 18 dp[0][j] = j * ic; 19 } 20 for (i = 0; i <= length1; ++i) 21 { 22 dp[i][0] = i * dc; 23 } 24 for (i = 1; i <= length1; ++i) 25 { 26 for (j = 1; j <= length2; ++j) 27 { 28 if (s1[i - 1] == s2[j - 1]) 29 { 30 dp[i][j] = dp[i - 1][j - 1]; 31 } 32 else 33 { 34 dp[i][j] = dp[i - 1][j - 1] + rc; 35 } 36 dp[i][j] = min(dp[i][j], dp[i - 1][j] + dc); 37 dp[i][j] = min(dp[i][j], dp[i][j - 1] + ic); 38 39 } 40 } 41 cout << "最小代价是:" << dp[length1][length2] << endl; 42 } 43 return 0; 44 }
原文地址:https://www.cnblogs.com/zouma/p/10768139.html
时间: 2024-10-10 05:22:12