Edit Distance
Time limit:5000ms Memory limit:65536kb
Total submit:314 accepted:128
Description
There are two strings (consisting only of English lowercase letters), A, B. We can change A to B by some actions. There are three types of operations: 1 To modify a letter, 2 to delete a letter, and 3 to insert a letter. The editing distance is now defined as the minimum number of times to modify a to B by the above operation.
Input
The first line has a positive integer n, which indicates how many sets of test data
Next there are 2*n lines, each of which represents a set of data. The first row of each set of data is a starting string A, and the second line is the destination string B.
Output
For each set of data, output a value that changes the edit distance of a to B, one row for each group of data, and no extra spaces.
N<=100, A, b string length not exceeding 500
Sample Input
2
Hello
Hi
Apple
Google
Sample Output
4
4
Source
Problem solving: Dynamic programming, DP[I][J] represents the minimum editing distance required for the first character of the source string s to be converted to the front J character of the target string T.
Then we have if s[i] = = T[j] Then direct DP[I][J] is equal to dp[i-1][j-1], because this is equal, do not need to operate the number of
If s[i]! = T[j] Then we have three options, add, delete and modify, we first consider the changes, if the s[i] modified to t[j], then dp[i][j] = dp[i-1][j-1]+1
If we want to remove s[i], then dp[i][j] = Dp[i-1][j] + 1 that is to say the s[i-1 in front] can become t[j]
If we choose to add so dp[i][j] = Dp[i][j-1] + 1 That is, we can already change s front I through the shortest editing distance to t[j-1] now to become t[j], we can choose to add s[i] after t[j], so
S[i] can go through the shortest editing distance into t[j]. Remember to take the minimum.
1#include <bits/stdc++.h>2 using namespacestd;3 Const intMAXN =510;4 CharSA[MAXN],SB[MAXN];5 intDP[MAXN][MAXN];6 intMain () {7 intKase;8scanf"%d",&Kase);9 while(kase--) {Tenscanf"%s%s", SA,SB); One intn =strlen (SA); A intm =strlen (SB); -Memset (DP,0x3f,sizeofDP); - for(inti =0; I <= N; ++i) dp[i][0] =i; the for(inti =0; I <= m; ++i) dp[0][i] =i; - for(inti =1; I <= N; ++i) - for(intj =1; J <= M; ++j) { -Dp[i][j] = min (dp[i-1][j]+1, dp[i][j-1]+1); +Dp[i][j] = min (dp[i][j],dp[i-1][j-1] + (sa[i-1]! = sb[j-1])); - } +printf"%d\n", Dp[n][m]); A } at return 0; -}
View Code
Ecnuoj 2857 Editing distance