区间dp - 编辑距离问题

 

 1 #include <iostream>
 2 #include <string>
 3 #define Maxsize 5000+1
 4 #define MIN(a,b) (a<b?a:b)
 5 #define MINN(a,b,c) (MIN(a,b)<MIN(a,c)?MIN(a,b):MIN(a,c))
 6 using namespace std;
 7 int dp[Maxsize][Maxsize];
 8 // 计算串1的前i个字符,到达串2的前j个字符的编辑距离d;即 dp[i][j] = edit((0~i),(0~j));
 9 int main(){
10     string src,dest;
11     cin >> src >> dest;
12     int len1 = (int)src.size();
13     int len2 = (int)dest.size();
14     for (int i = 1; i <= len1; i++) {
15         dp[i][0] = i;
16     }
17     for (int j = 1; j <= len2; j++) {
18         dp[0][j] = j;
19     }
20     
21     for (int i = 1; i <= len1; i++) {
22         for (int j = 1; j <= len2; j++) {
23             if (src[i-1] != dest[j-1]) {
24                 dp[i][j] = MINN(dp[i][j-1],dp[i-1][j],dp[i-1][j-1]) + 1;
25             }else{
26                 dp[i][j] = dp[i-1][j-1];
27             }
28         }
29     }
30     cout << dp[len1][len2];
31     return 0;
32 }
33  

 

posted @ 2020-03-14 10:48  popozyl  阅读(159)  评论(0编辑  收藏  举报