Common Subsequence
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 61444 | Accepted: 25704 |
Description
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, ..., xm > another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, ..., ik > of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.
Input
The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
Output
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.
Sample Input
abcfbc abfcab programming contest abcd mnp
Sample Output
4 2 0
Source
1.用递归写超时:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int maxc[502][502];
char a[502];
char b[502];
int judge(int lena,int lenb)
{
if(lena==0||lenb==0) return 0;
if(a[lena-1]==b[lenb-1])
{
return judge(lena-1,lenb-1)+1;
}
else
{
return max(judge(lena-1,lenb),judge(lena,lenb-1));
}
}
int main()
{
while(cin>>a>>b)
{
int lena=strlen(a);
int lenb=strlen(b);
memset(maxc,0,sizeof(int));
int num=judge(lena,lenb);
cout<<num<<endl;
}
return 0;
}
2.递推:
2.1递推公式:
if(a[i-1]==b[j-1])
{
maxc[i][j]=maxc[i-1][j-1]+1;
}
else
{
maxc[i][j]=max(maxc[i-1][j],maxc[i][j-1]);
}
2.2找到递推公式后,代码如下:
2.2.1首先,在理解maxc[][],数组含义以及对数组进行初始化的时候出现了理解的偏差。
2.2.2maxc[][]的含义是:a[]数组第i个元素 b[]数组的第j个元素的最长公共子序列的长度。
2.2.3maxc[][]初始化解释:
以:
a[3]={a,b,c}
b[4]={d,a,b,c}为例。
maxc[1][1]=max(maxc[1][0],maxc[0][1]); //因为a[0]!=b[0]
而maxc[1][0]和maxc[0][1]都为0 //初始化得到的
初始化的时候,并不是if(lena==0||lenb==0)的时候,对maxc[i][j]进行的初始化,一定要明白它的意义。0并不是表示字符 串的长速度为零,而是a[0]前面的那一个不存在的字符。
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int maxc[502][502];
int main()
{
char a[502];
char b[502];
while(cin>>a>>b)
{
int lena=strlen(a);
int lenb=strlen(b);
memset(maxc,0,sizeof(int));
//if(lena==0)一定要注意它的含义 ,此处错误
//{
for(int i=0;i<lenb;i++)
maxc[0][i]=0;
//}
//if(lenb==0)一定要注意它的含义 ,此处错误
//{
for(int i=0;i<lena;i++)
{
maxc[i][0]=0;
}
//}
for(int i=1;i<=lena;i++)
{
for(int j=1;j<=lenb;j++)
{
if(a[i-1]==b[j-1])
{
maxc[i][j]=maxc[i-1][j-1]+1;
}
else
{
maxc[i][j]=max(maxc[i-1][j],maxc[i][j-1]);
}
}
}
cout<<maxc[lena][lenb]<<endl;
}
return 0;
}