原题链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1159
题目大意:给两个字符串,求最大上升公共子序列长度。(不要求连续)
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
设dp[i+1][j+1]表示截止a[i], b[j]为止的最大长度,
若a[i] == b[j],有
dp[i+1][j+1] = dp[i][j] + 1
否则,有
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1000;
int dp[maxn][maxn];
char a[maxn], b[maxn];
int main(){
while(scanf("%s%s", a, b) != EOF){
int len1 = strlen(a);
int len2 = strlen(b);
for(int i = 0; i < len1; i++){
for(int j = 0; j < len2; j++){
if(a[i] == b[j])
dp[i+1][j+1] = dp[i][j] + 1;
else
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
}
}
printf("%d\n", dp[len1][len2]);
}
return 0;
}