POJ 1458 && HDU 1159 Common Subsequence(LCS)

Description
现在给出两个序列X和Y,你的任务是找到X和Y的最大公共子序列,也就是说要找到一个最长的序列Z,使得Z既是X的子序列也是Y的子序列
Input
输入包括多组测试数据。每组数据包括一行,给出两个长度不超过200 的字符串,表示两个序列。两个字符串之间由若干个空格隔开。
Output
对每组输入数据,输出一行,给出两个序列的最大公共子序列的长度
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
Solution
LCS
Code

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define maxn 201
char s1[maxn],s2[maxn];
short int dp[2][maxn];
int main()
{
    while(scanf("%s%s",s1,s2)==2)
    {
        int m=strlen(s1);
        int n=strlen(s2);
        memset(dp,0,sizeof(dp));
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
                if(s1[i]==s2[j])
                    dp[(i+1)&1][j+1]=dp[i&1][j]+1;
                else
                    dp[(i+1)&1][j+1]=max(dp[(i+1)&1][j],dp[i&1][j+1]);
        cout<<dp[m&1][n]<<endl;
    }
    return 0;
}

你可能感兴趣的:(POJ 1458 && HDU 1159 Common Subsequence(LCS))