hdu1159: Common Subsequence

hdu1159: http://acm.hdu.edu.cn/showproblem.php?pid=1159
题意:求最长共同子序列(可不连续)的长度
解法:dp:dp[i][j]表示第一个字符串的前i个字符与第二个字符串的前j个字符的最长共同子序列,则有两种情况,一种是a[i]==b[j],此时dp[i][j]=dp[i-1][j-1]+1;另一种是不等,则dp[i][j]=max(dp[i-1][j],dp[i][j-1]).
code:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
int max(int a,int b)
{
    if(a>b)
        return a;
    else
        return b;
}
char a[1050], b[1050];
int dp[1050][1050];
int main()
{
    while(scanf("%s%s",a+1,b+1)!=EOF)
    {
        int alen = strlen(a+1);      //这里有个小技巧,把字符串往后移一位,以免出现i-1为负的情况
        int blen = strlen(b+1);
        memset(dp, 0, sizeof(dp));
        for(int i = 1; i <= alen; i++)
            for(int j = 1; j <= blen; j++)
            {
                if(a[i] == b[j])
                    dp[i][j] = dp[i-1][j-1] + 1;
                else
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
            }
        printf("%d\n", dp[alen][blen]);
    }
    return 0;
}
/*
input:
abcfbc abfcab
programming contest
abcd mnp
output:
4
2
0
*/

posted on 2012-07-25 15:05  acmer-jun  阅读(136)  评论(0)    收藏  举报

导航