Thanks Prof. Abhiram Ranade for he vedio on longest Common subsequence ' s back track search view in lecture, nice EXPL Anation indeed.
Back track, recursive, 390 MS, O (m*n) memory
#include <cstdio>#include <vector>#include <string>#include <iostream>#include <algorithm>#define MAXSIZE 1001using STD::string;Char*P1, *P2;intM, N;intTable[maxsize][maxsize];intSolvelcslength (intIintj) {if(table[i][j]>=0)returnTABLE[I][J];intK for(K=j;k<n && p2[k]!=p1[i];++k) {}if(k!=n) table[i][j]=STD:: Max (Solvelcslength (i+1, j),1+solvelcslength (i+1, K +1));ElseTable[i][j]=solvelcslength (i+1, j);returnTABLE[I][J];}intLcslength (string&S1,string&S2) {p1=&s1[0], p2=&s2[0], M=s1.size (), n=s2.size (); for(intI=0; i<m;++i) { for(intj=0; j<n;++j) {table[i][j]=-1; } table[i][n]=0; } for(intj=0; j<=n;++j) {table[m][j]=0; }returnSolvelcslength (0,0);}intMain () {stringS1, S2; while(STD::Cin>> S1 >> S2) {printf("%d\n", Lcslength (S1,S2)); }return 0;}
Incremental, 31ms, O (m+n) memory
#include <cstdio>#include <algorithm>#define MAXSIZE 1001intMain () {CharS1[maxsize], s2[maxsize];inttable[maxsize<<1], *prev, *curr;intLen1,len2, I,j; while(scanf("%s%s", s1,s2) = =2) {len1=strlen(S1), len2=strlen(S2); Prev=table, curr=&table[len2+1]; for(i=0; i<=len2+1; ++i) prev[i]=0; for(i=1; i<=len1;++i) { for(j=1; j<=len2;++j) {if(s1[i-1]==s2[j-1]) curr[j]=1+prev[j-1];Elsecurr[j]=prev[j]>curr[j-1]?prev[j]:curr[j-1]; }STD:: Swap (Curr,prev); }printf("%d\n", Prev[len2]); }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hdu 1159, LCS, dynamic programming, recursive backtrack vs incremental, C + +