#include <iostream> #include <string.h>using namespace Std;int Row,col,**map,index,maxlen;char *record,* Lcs;bool flag=true;string str1,str2;/*eg:str1= "ABCB", str2= "ACB" a B C b a 1 0 0 0c 0 0 1 0b 0 1 0 1 Map: As above, with str1 length of row,str2 length as Col, when Str1[i]==str2[j],map[i][j]=1;index: represents the number of elements at a time in the record maxlen: during DFS storage, Temporary eldest-child sequence length appearing record: Storing the CSLCS in the DFS process: storing the final lcsflag: Controlling the result, when the STR1==STR2 direct output, no more than the DFS idea: first get the map array, then from top left to bottom right start DFS, each encounter a 1, Jumps to the next column of a row, returns to the boundary and determines whether the resulting CS is longer than the original CS. (temporarily made out, no optimization algorithm, feeling inefficient, first use ...) */void DFS (int r,int c)//r represents a temporary row, C stands for a temporary column {for (int i=r;i<row;i++) for (int j=c;j<col;j++) if (map[i][j]==1) {record[ index]=str1[i];index++;d FS (i+1,j+1); index--;record[index]=0;} if (maxlen<index) {maxlen=index;strcpy (Lcs,record);}} void init () {int i,j;cin>>str1>>str2;if (STR1==STR2) {Cout<<str1<<endl;flag=false;return;} Row=str1.length (); Col=str2.length (); record=new Char[row>col?row:col] (); Lcs=new Char[row>col?row:col] (); map =new Int*[row];index=maxlen=0;for (i=0;i<row;i++) map[i]=new Int[col] (); for (i=0;i<row;i++) for (j=0;j<col;j++) if (str1[i ]==STR2[J]) map[i][j]=1;} void Delmem () {for (int i=0;i<row;i++) delete[] map[i];d elete[] map;} int main () {init (); if (flag) {DFS (0,0);cout<<lcs<<endl;cout<<maxlen<<endl;cout<< Strlen (LCS) <<endl;delmem ();} return 0;}
Recursive method of the longest common subsequence LCS