Edit distance Time Limit: 1000 ms memory limit: 65536 k any questions? Click Here ^_^ The description assumes that the basic operations of a string are only: delete one character, insert one character, and modify one character to another.
We call any of the above three operations a step-by-step basic operation.
Next we define the editing distance between two strings: For two strings a and B, through the above basic operations, we can convert A to B or B to, the minimum number of operation steps required for converting string a to string B is the distance between string a and string B.
For example, if a = "ABC", B = "cbcd", the distance between A and B is 2.
Your task is to compile a quick program to calculate the editing distance between any two strings. The input contains multiple groups of test data. One row of test data in each group, which is string a and string B.
The length of a string is not greater than 1024 characters, and all characters are letters. Output editing distance. Sample Input
ABC CBCD
Sample output
2
In the first place, I wanted to search. I thought the scope was silly... String Model DP.
Set DP [I] [J] to represent the shortest editing distance between the original string and the target string from 1 to J,
DP [I] [J] = min (DP [I] [J-1] + 1 (delete a [I]), DP [I-1] [J] + 1 (add B [J]), a [I] = B [J]? DP [I-1] [J-1]: DP [I-1] [J-1] + 1 );
#include <cstdio>#include <iostream>#include <algorithm>#include <cstring>#include <cctype>#include <cmath>#include <cstdlib>#include <vector>#include <queue>#include <set>#include <map>#include <list>#define ll long longusing namespace std;const int INF = 0x3f3f3f3f;int dp[1025][1025];char a[1025],b[1025];int My_min(int x,int y,int z){return min(min(x,y),z);}int main(){while(~scanf("%s%s",a,b)){int lena=strlen(a),lenb=strlen(b);for(int i=0;i<=lenb;i++)dp[0][i]=i;for(int i=0;i<=lena;i++)dp[i][0]=i;for(int i=1;i<=lena;i++)for(int j=1;j<=lenb;j++)dp[i][j]=My_min(dp[i-1][j]+1,dp[i][j-1]+1,a[i-1]==b[j-1]?dp[i-1][j-1]:dp[i-1][j-1]+1);printf("%d\n",dp[lena][lenb]);}return 0;}
Sdut 1225-editing distance (string DP)