Recursive method of the longest common subsequence LCS

Source: Internet
Author: User

#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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.