We recommend that you first look at the preface: http://www.cnblogs.com/tanky_woo/archive/2011/04/09/2010263.html
This case is also relatively simple. The longest common subsequence (LCS) has a lot of online analysis, which is awesome!
Find the state transition equation as summarized in the previous article:
Therefore, according to the given equation, writeCodeThe work is very simple and easy:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
/* Author: tanky wooblog: www. wutianqi. comabout :《AlgorithmIntroduction 15.4 longest public sequence (LCS )*/ # Include <iostream> Using Namespace STD ; Char B [ 20 ] [ 20 ] ; Int C [ 20 ] [ 20 ] ; Char X [ 20 ] , Y [ 20 ] ; Void LCS ( ) { Int M = Strlen ( X + 1 ) ; Int N = Strlen ( Y + 1 ) ; For ( Int I = 1 ; I <= M ; ++ I ) C [ I ] [ 0 ] = 0 ; For ( Int J = 1 ; J <= N ; ++ J ) C [ 0 ] [ J ] = 0 ; For ( Int I = 1 ; I <= M ; ++ I ) For ( Int J = 1 ; J <= N ; ++ J ) { If ( X [ I] = Y [ J ] ) { C [ I ] [ J ] = C [ I - 1 ] [ J - 1 ] + 1 ; B [ I ] [ J ] = '\\'; // Note that the first \ here is a transfer character, representing\} Else if (C [I-1] [J]> = C [I] [J-1]) {C [I] [J] = C [I-1] [J]; B [I] [J] =' | ';} Else {C [I] [J] = C [I] [J-1]; B [I] [J] =' - ';}} Void printlcs (int I, Int J) {if (I = 0 | j = 0) return; if (B [I] [J] =' \\ ') {Printlcs (I-1, J-1); cout <X [I] <";} else if (B [I] [J] =' | ') Printlcs (I-1, J); elseprintlcs (I, J-1);} int main () {cout <"input the array:\ N"; CIN> x + 1; cout <" input the array B:\ N"; CIN> Y + 1; LCS (); printlcs (strlen (x + 1), strlen (Y + 1 ));} |
Result graph of reading 15-6:
It is also a powerful graph. We recommend that you followProgramDraw this picture.
Speaking of LCS, what I have to say is Lis (the longest ascending subsequence), which is also a DP. I have summarized the following:
Http://www.wutianqi.com /? P = 1850
Tanky Woo Tag: DP, dynamic planning, LCs
In my independent blog: http://www.wutianqi.com /? P = 2505
You are welcome to learn from each other and make progress!