题目详见洛谷
解析
设dp[i][j]表示 a[i] b[j] 的最长子序列长度,那么有三种情况:
一,a[i]不在子序列中,此时dp[i][j] = dp[i - 1][j];
二,b[i]不在子序列中,此时dp[i][j] = dp[i][j - 1];
三,都在,此时dp[i][j] = dp[i][j] = dp[i - 1][j - 1] + 1;
综上状态转移方程:
dp[i][j] = max(dp[i - 1][j],dp[i][j - 1]);
if(a[i] == b[j]){
dp[i][j] = max(dp[i][j],dp[i - 1][j - 1] + 1);
}
完整代码:
#include<bits/stdc++.h>
using namespace std;
int n,m;
char a[100001],b[100001];
int dp[10001][10001];
int main()
{
gets(a + 1);
gets(b + 1);
n = strlen(a + 1);
m = strlen(b + 1);
for(int i = 1;i <= n; i++){
for(int j = 1;j <= m; j++){
dp[i][j] = max(dp[i - 1][j],dp[i][j - 1]);
if(a[i] == b[j]){
dp[i][j] = max(dp[i][j],dp[i - 1][j - 1] + 1);
}
}
}
printf("%d" ,dp[n][m]);
return 0;
}