Question: edit the distance. Here are two strings to convert known strings into target strings. You can add, delete, and change letters to the minimum number of operations.
Analysis: DP, editing distance. Same as the largest public subsequence. Note that the operation location changes in real time. (The previous steps have been completed)
F [I] [J] = f [I-1] [J] Then delete str1 [I], position J + 1;
F [I] [J] = f [I] [J-1] adding str2 [J], position J;
F [I] [J] = f [I-1] [J-1] + K if str1 [I] = str2 [J] Then the same K = 0, otherwise k = 1, location J.
Note: note that str1 is changed to str2; the changed position is the location where this step is located (the previous steps have been processed ).
# Include <iostream> # include <cstdlib> # include <cstring> # include <cstdio> char str1 [24], str2 [24]; int DP [24] [24], OP [24] [24]; void output (int I, Int J) {If (! I &&! J) return; If (OP [I] [J] = 1) {output (I-1, J); printf ("d % C % 02d", str1 [I-1], J + 1);} else if (OP [I] [J] = 2) {output (I, J-1); printf ("I % C % 02d ", str2 [J-1], J);} else if (OP [I] [J] = 3) {output (I-1, J-1 ); printf ("C % 02d", str2 [J-1], J);} else output (I-1, J-1);} int main () {While (scanf ("% s", str1) & str1 [0]! = '#') {Scanf ("% s", str2); int L1 = strlen (str1); int L2 = strlen (str2); For (INT I = 0; I <= L1; ++ I) for (Int J = 0; j <= L2; ++ J) {DP [I] [J] = 400; OP [I] [J] = 0 ;}// initialize for (INT I = 0; I <= L1; ++ I) {op [I] [0] = 1; DP [I] [0] = I ;}for (INT I = 0; I <= L2; ++ I) {op [0] [I] = 2; DP [0] [I] = I ;}for (INT I = 1; I <= L1; ++ I) for (Int J = 1; j <= L2; ++ J) {If (str1 [I-1]! = Str2 [J-1]) {op [I] [J] = 3; DP [I] [J] = DP [I-1] [J-1] + 1 ;} else DP [I] [J] = DP [I-1] [J-1]; If (DP [I-1] [J] + 1 <DP [I] [J]) {op [I] [J] = 1; DP [I] [J] = DP [I-1] [J] + 1 ;} if (DP [I] [J-1] + 1 <DP [I] [J]) {op [I] [J] = 2; DP [I] [J] = DP [I] [J-1] + 1 ;}} output (L1, L2); printf ("e \ n ");} return 0 ;}