题目描述
Do you remember the "Nearest Numbers"? Now here comes its brother:"Nearest Sequence".Given three sequences of char,tell me the length of the longest common subsequence of the three sequences.
输入
There are several test cases.For each test case,the first line gives you the first sequence,the second line gives you the second one and the third line gives you the third one.(the max length of each sequence is 100)
输出
For each test case,print only one integer :the length of the longest common subsequence of the three sequences.
样例输入
abcd
abdc
dbca
abcd
cabd
tsc
样例输出
2
1
提示
思路:简单的动态规划,原始LCS,把以前的二维代码加了一维,AC。
#include <cstring>
#include <cstdlib>
#include <cstdio>
#define Max( a, b ) (a) > (b) ? (a) : (b)
using namespace std;
char s1[105], s2[105],s3[105];
int dp[105][105][105];
int main()
{
int len1, len2 , len3;
while( scanf( "%s %s %s", s1, s2 ,s3 ) != EOF )
{
memset( dp, 0, sizeof(dp) );
len1 = strlen( s1 ), len2 = strlen( s2 );
len3 = strlen( s3 );
for( int i = 1; i <= len1; ++i )
{
for( int j = 1; j <= len2; ++j )
{
for (int k= 1; k <= len3; ++k)
{
if( s1[i-1] == s2[j-1] && s1[i-1] == s3[k-1] )
{
dp[i][j][k] = dp[i-1][j-1][k-1] + 1;
}
else
{
dp[i][j][k] = Max ( dp[i-1][j][k], dp[i][j-1][k] );
dp[i][j][k] =Max (dp[i][j][k],dp[i][j][k-1]);
}
}
}
}
printf( "%d\n", dp[len1][len2][len3] );
}
return 0;
}