33,007
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
#include <stack>
using namespace std;
/*
DP的核心公式:
if xi = yj:
LCS(xi,yj)=LCS(xi-1,yj-1)+1;
else
LCS(xi,yj)=max(LCS(xi-1,yj),LCS(xi,yj-1)).
*/
int LCS_DP( string x, string y )
{
int xlen=x.size();
int ylen=y.size();
//int *lcs = new int[(xlen+1)*(ylen+1)]();
int **lcs = new int*[xlen+1];
int **path = new int*[xlen+1];
for( int i=0; i<=xlen; i++){
lcs[i] = new int[ylen+1]();
path[i] = new int[ylen+1]();
}
for( int k=1; k<=xlen+ylen;k++){
for( int i=1; i<=xlen; i++){
for( int j=1; j<=k-i&&j<=ylen; j++){
if(x[i-1]==y[j-1]){
lcs[i][j] = lcs[i-1][j-1]+1;
path[i][j] = 1; //1表示两个字符相等
}
else{
int a=lcs[i-1][j];
int b=lcs[i][j-1];
lcs[i][j] = a>b?a:b;
path[i][j] = a>b?2:3; //2表示来自y,3表示来自x
}
}
}
}
stack<char> stk;
for( int i=xlen,j=ylen; i>0&&j>0; )
{
if( path[i][j] == 1 ){
stk.push( x[i-1] );
i--;j--;
}
if( path[i][j] == 2 ){
i--;
}
if( path[i][j] == 3 ){
j--;
}
}
cout <<"The Longest Common Sequence Length: " <<lcs[xlen][ylen]<<endl;
cout <<"The Longest Common Sequence is:"<<endl;
while( !stk.empty() ){
cout << stk.top();
stk.pop();
}
return lcs[xlen][ylen];
}
int main()
{
string a,b;
cout << "Input two string: " <<endl;
cin>> a >> b;
LCS_DP( a, b);
return 0;
}