題目大意:給你連個字符串A 和 B , 讓你求A 和 B 的最長公共子序列。
解題思路:此題屬簡單的DP 問題, 具體講解推薦以下博客:
http://blog.csdn.net/yysdsyl/article/details/4226630
我的代碼如下:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std ;
const int MAXN = 1e4 + 5 ;
char x[MAXN] ;
char y[MAXN] ;
int L[MAXN][MAXN] ;
void solve()
{
int lenx = strlen(x) ;
int leny = strlen(y) ;
int i , j ;
for(i = 0 ; i <= lenx ; i ++)
L[i][0] = 0 ;
for(j = 0 ; j <= leny ; j ++)
L[0][j] = 0 ;
for(i = 1 ; i <= lenx ; i ++)
{
for(j = 1 ; j <= leny ; j ++)
{
if(x[i - 1] == y[j - 1])
{
L[i][j] = L[i - 1][j - 1] + 1 ;
}
else
{
L[i][j] = max(L[i - 1][j] , L[i][j - 1]) ;
}
}
}
printf("%d\n" , L[lenx][leny]) ;
}
int main()
{
while (scanf("%s" , x) != EOF)
{
scanf("%s" , y) ;
solve() ;
}
return 0 ;
}