最长公共子序列LCS Posted on 2018-12-02 | In c++ | 二维数组c[][]记录最长公共子序列的长度,b[][]记录最长子序列的来源c[][]右下角的值即为最长子序列的长度 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061#include<iostream>#define MAX 100using namespace std;int c[MAX][MAX];int b[MAX][MAX];void lcs(string s1,string s2){ int m=s1.length(); int n=s2.length(); for(int i=0;i<=m;i++) { c[i][0]=b[i][0]=0; c[0][i]=b[0][i]=0; } for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ if(s1[i-1]==s2[j-1]){ c[i][j]=c[i-1][j-1]+1; b[i][j]=1; } else{ if(c[i-1][j]>c[i][j-1]){ c[i][j]=c[i-1][j]; b[i][j]=3; } else{ c[i][j]=c[i][j-1]; b[i][j]=2; } } } }}void findPath(int x,int y,string s1){ if(x==0||y==0) return ; if(b[x][y]==1){ findPath(x-1,y-1,s1); cout<<s1[x-1]<<" "; } else if(b[x][y]==2){ findPath(x,y-1,s1); } else{ findPath(x-1,y,s1); } }int main(){ string s1,s2; freopen("12-2.txt","r",stdin); cin>>s1>>s2; lcs(s1,s2); int m=s1.length(); int n=s2.length(); cout<<"最长公共子序列的长度:"<<c[m][n]<<endl; cout<<"最长公共子序列是:"<<endl; findPath(m,n,s1); return 0; }