运行效果:

Nearth==>动态规划算法003/最长公共子序列算法_子序列

代码学习:

#include<iostream>
using namespace std;
#define MAX 1000//输入字符串的最大长度
char a[MAX]={0};//输入的字符串1
char b[MAX]={0};//输入的字符串2
int flag[MAX][MAX];//为了输出字符串1,2的共同字符所设下的标志
int count[MAX][MAX]={0};//字符串1,2的最长公共子长度
void print(int i,int j){//根据标志控制输出公共字符的函数
if(i==0||j==0){
return ;
}
if(flag[i][j]==1){
print(i-1,j-1);
cout<<a[i-1];
}
else if(flag[i][j]==2){
print(i-1,j);
}
else if(flag[i][j]==3){
print(i,j-1);
}
}
void LCSLength(){
cout<<"请输入子序列1(长度不能超过1000):";
cin>>a;
cout<<"请输入子序列2(长度不能超过1000):";
cin>>b;
int lengthA=strlen(a);
int lengthB=strlen(b);
for(int i=1;i<=lengthA;i++){
for(int j=1;j<=lengthB;j++){
if(a[i]==b[j]){//如果最后字符串1,2的最后一个字符相同,则这两个字符串的最大公共字符串长度为->
count[i][j]=count[i-1][j-1]+1;//->count[i-1][j-1]+1
flag[i][j]=1;
}
else{
if(count[i-1][j]>count[i][j-1]){
count[i][j]=count[i-1][j];
flag[i][j]=2;
}
else{
count[i][j]=count[i][j-1];
flag[i][j]=3;
}
}
}
}
cout<<"*******************************************************"<<endl;
cout<<"******************测试结果如下*************************"<<endl;
cout<<"两个子序列的最长公共子序列长度为:"<<count[lengthA][lengthB]<<endl;
cout<<"最长公共子序列为:";
print(lengthA,lengthB);
cout<<endl;
}
int main(){
int i=1;
cout<<"*******************************************************"<<endl;
cout<<"*****************最长公共子序列算法********************"<<endl;
cout<<"*******************************************************"<<endl;
while(i<20){
cout<<"--------------第"<<i++<<"次操作"<<"-----------------------"<<endl;
cout<<"******************测试指示如下*************************"<<endl;
LCSLength();
}
return 0;
}