天天看點

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
*/      

轉載于:https://www.cnblogs.com/acmjun/archive/2012/07/25/2608325.html