作者:Blackage | 来源:互联网 | 2023-10-11 12:38
最长公共子序列不需要字符连续出现和字串不同LCS求最长公共子串模板题CommonSubsequence描述Asubsequenceofagivensequenceisthegive
最长公共子序列不需要字符连续出现和字串不同
//LCS 求最长公共子串模板题
Common Subsequence
描述
输入
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
输出
For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
样例输入
abcfbc abfcab
programming contest
abcd mnp
样例输出
4
2
0
#include
using namespace std;
string a,b;
int dp[1001][1001], len1, len2;
void lcs(int i,int j)
{
for(i=1; i<=len1; i++)
{
for(j=1; j<=len2; j++)
{
if(a[i-1] == b[j-1])
dp[i][j] = dp[i-1][j-1] + 1;
else
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
}
int main()
{
while(cin>>a)
{
cin>>b;
memset(dp, 0, sizeof(dp));
len1 = a.length();
len2 = b.length();
lcs(len1, len2);
cout<endl;
}
}
//有可能遇到爆内存的情况,在只求长度的情况下可以把dp数组改为只有两个状态;
void lcs(int i,int j)
{
for(i=1; i<=len1; i++)
{
e^=1; //切换e为1 和 0;
for(j=1; j<=len2; j++)
{
if(a[i-1] == b[j-1])
dp[e][j] = dp[e^1][j-1] + val[a[i-1]];
else
dp[e][j] = max(dp[e^1][j],dp[e][j-1]);
}
}
}
//输出最长公共子串上面的代码不变,根据dp数组状态来决定取哪几个元素
#include
using namespace std;
string a,b;
int dp[1001][1001], len1, len2;
void lcs(int i,int j)
{
for(i=1; i<=len1; i++)
{
for(j=1; j<=len2; j++)
{
if(a[i-1] == b[j-1])
dp[i][j] = dp[i-1][j-1] + 1;
else
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
}
void printflcs()
{
char c[1001];
memset(c, 0, sizeof(c));
int i = len1;int j = len2;int d=0;
while(i!=0 && j!=0)
{
if(a[i-1] == b[j-1])
{
c[d++] = a[--i];
j--;
}
else if(dp[i-1][j] 1])
j--;
else if(dp[i][j-1] <= dp[i-1][j])
i--;
}
for(i=d-1; i>=0; i--)
cout<<c[i];
cout<<endl;
}
int main()
{
while(cin>>a)
{
cin>>b;
memset(dp, 0, sizeof(dp));
len1 = a.length();
len2 = b.length();
lcs(len1, len2);
printflcs();
cout<endl;
}
}
LCS 求最长公共子序列