Description
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.
Input
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)
Output
For each test case,print only one integer :the length of the longest common subsequence of the three sequences.
Sample Input
abcd
abdc
dbca
abcd
cabd
tsc
Sample Output
2
1
HINT
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
int dp[101][101][101]; /* 存储LCS长度, 下标i,j表示序列X,Y长度 */
char X[101];
char Y[101];
char z[101];
int i,j,k;
main()
{
// freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
// cin.getline(X,100);
// cin.getline(Y,100);
// cin.getline(z,100);
while(cin>>X>>Y>>z){
int xlen = strlen(X);
int ylen = strlen(Y);
int zlen = strlen(z);
for(i = 1; i <= xlen; ++i)
{
for(j = 1; j <= ylen; ++j)
for( k = 1; k <=zlen ; ++k)
{
if(X[i-1] == Y[j-1]&&Y[j-1]==z[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],max(dp[i][j-1][k],dp[i][j][k-1]));
}
}
printf("%d\n", dp[xlen-1][ylen-1][zlen-1]+1);
}
}
啊啊啊 终于可以自己摸索着做出dp的题,虽然是在别人求两个序列lcs的代码上修改才成功的, 不过对最后的输出数组还是有点不太清楚,待究。。。