单纯LCS
#include <bits/stdc++.h>
using namespace std;
string s1,s2;
int f[1010][1010],len1,len2,ans;
int main(){
cin>>s1>>s2;
len1=s1.size();
len2=s2.size();
for(int i=1;i<=len1;i++)
for(int j=1;j<=len2;j++)
{
if(s1[i-1]!=s2[j-1])f[i][j]=max(f[i-1][j],f[i][j-1]);
else{
f[i][j]=f[i-1][j-1]+1;
}
}
cout<<f[len1][len2];
return 0;
}
LCS 及路径输出
#include <bits/stdc++.h>
using namespace std;
const int N=1010;
string s1,s2;
int n,f[N][N],b[N][N],len1,len2;
void lcs(){
for(int i=1;i<=len1;i++)
for(int j=1;j<=len2;j++){
if(s1[i-1]==s2[j-1]){
f[i][j]=f[i-1][j-1]+1;
b[i][j]=1;//b数组记录路径
}
else {
if(f[i][j-1]>=f[i-1][j]){
f[i][j]=f[i][j-1];
b[i][j]=2;
}
else {
f[i][j]=f[i-1][j];
b[i][j]=3;
}
}
}
}
//递归输出正序路径
void print(int i,int j){
if(i==0||j==0)return;
if(b[i][j]==1){
print(i-1,j-1);
cout<<s1[i-1];
}
else if(b[i][j]==2){
print(i,j-1);
}
else
print(i-1,j);
}
int main(){
cin>>s1>>s2;
len1=s1.size();
len2=s2.size();
lcs();
cout<<f[len1][len2];
print(len1,len2);
// cout<<endl;
// for(int i=0;i<=len1;i++){
// for(int j=0;j<=len2;j++)
// cout<<f[i][j]<<" ";
// cout<<endl;
// }
// cout<<endl;
// for(int i=0;i<=len1;i++){
// for(int j=0;j<=len2;j++)
// cout<<b[i][j]<<" ";
// cout<<endl;
// }
return 0;
}
参考:
LCS参考博文https://blog.csdn.net/hrn1216/article/details/51534607
路径输出参考《趣学算法》