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
最近在学习邓俊辉老师的《数据结构》,该题先用递归方法做了一遍,肯定是TLE的,因为时间复杂度是O(2^n),属于难解,因为该算法有大量的重复递归实例,增加了复杂度,解决方法是用动态规划自下而上设计算法。
TLE版本:
#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
char word1[1005];
char word2[1005];
int cnt=0;
int lcs(char* word1,char* word2)
{
char temp1[1005];
char temp2[1005];
memset(temp1,0,sizeof(temp1));
memset(temp2,0,sizeof(temp2));
for(int i=0; i<strlen(word1); i++)
{
temp1[i]=word1[i];
}
for(int i=0; i<strlen(word2); i++)
{
temp2[i]=word2[i];
}
if(strlen(temp1)==0||strlen(temp2)==0)
{
return 0;
}
if(temp1[0]==temp2[0])
{
for(int i=0; i<strlen(temp1); i++)
{
temp1[i]=temp1[i+1];
}
for(int i=0; i<strlen(temp2); i++)
{
temp2[i]=temp2[i+1];
}
return lcs(temp1,temp2)+1;
}
else
{
char temp[1005];
memset(temp,0,sizeof(temp));
int a,b;
for(int i=0; i<strlen(temp1); i++)
{
temp[i]=temp1[i+1];
}
a=lcs(temp,temp2);
memset(temp,0,sizeof(temp));
for(int i=0; i<strlen(temp2); i++)
{
temp[i]=temp2[i+1];
}
b=lcs(temp1,temp);
return (a>b)?a:b;
}
}
int main()
{
memset(word1,0,sizeof(word1));
memset(word2,0,sizeof(word2));
while (scanf("%s%s",word1,word2)!=EOF)
{
cnt=lcs(word1,word2);
printf("%d\n",cnt);
memset(word1,0,sizeof(word1));
memset(word2,0,sizeof(word2));
}
return 0;
}