Portal: A pass evaluation 1276"Title description"
Set A and B are two strings. We want to convert string A to string B with the fewest number of character operations. There are three types of characters spoken here:
1, delete a character;
2, insert a character;
3. Change one character to another character.
For any of the two strings A and B, the minimum number of character operations used to transform string A into string B is computed.
"Input"
The first behavior string A; second behavior string B; string A and B are both less than 2000 in length.
"Output"
There is only one positive integer, which is the minimum number of character operations.
"Input Sample"
Sfdqxbwgfdgw
"output Example"4"Ideas"
Dynamic Programming idea, the topic asks is the editing distance from string A to string B. Dynamic programming has the structure of optimal sub-problem, the form of sub-problem is similar to the original problem, and the scale decreases. So when you think about it, take a step forward:
• If the first alen-1 character of string A is the same as B, the current edit distance from A to B is 1 (delete the last one)
• If the first blen-1 characters of the string A and B are the same, the current distance from A to B is also 1 (add one)
• If the first alen-1 character of A and the blen-1 character of B are already the same, if the last character of A is the same as the last character of B, then the edit distance of a to B is 0, otherwise 1 (change once)
Set state to Dp[i][j], representing the first I character of string A to the editing distance of the first J character of String B, from the above analysis, you can write the DP state transition equation:
dp[i][j]=min (dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]) (The first and second characters of A are the same as the first J characters of B)
dp[i][j]=min (dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+1) (The first and second characters of a are different from the first J characters of B)
The detailed code is as follows:
1#include <bits/stdc++.h>2 using namespacestd;3 #defineMAXN 2000+54 intD[MAXN][MAXN];5 intMinintAintBintc)6 {7 if(a>b) Swap ( A, a);8 if(a>c) Swap (A,C);9 returnA;Ten } One intMain () A { - CharA[MAXN],B[MAXN]; -Cin>>A; theCin>>b; -memset (D,0,sizeof(d)); - intlen1=strlen (a); - for(intI=1; i<=len1;i++) + { -d[i][0]=i; + } A intLen2=strlen (b); at for(intI=1; i<=len2;i++) - { -d[0][i]=i; - } - for(intI=1; i<=len1;i++) - { in for(intj=1; j<=len2;j++) - { toD[i][j]=min (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+ (a[i-1]==b[j-1]?0:1)); + } - } thecout<<d[len1][len2]<<Endl; * return 0; $}
"DP" Edit distance