POJ - 1458 Common Subsequence(dp_最长公共子序列)

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, ..., xm > another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, ..., ik > of indices of X such that for all j = 1,2,...,k, x ij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.

Input

The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.

Output

For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.

Sample Input

abcfbc         abfcab
programming    contest 
abcd           mnp

Sample Output

4
2
0

(1)子问题:两个串的最长公共字串

(2)状态:dp[i][j],到第一个串第 i 位和第二个串第 j 位为止的最长公共子串

(3)状态转移方程:对于dp[i][j],如果s1[i - 1] == s2[j - 1],dp[i][j] = dp[i - 1][j - 1] + 1;

                                                      如果s1[i - 1] != s2[j - 1], dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);

参考:https://www.cnblogs.com/huashanqingzhu/p/7423745.html

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const int mod = 1e9 +7;
const int N = 1e3 + 10;

int dp[N][N];

int main()
{
    string a, b;
    while(cin >> a >> b)
    {
        int len1 = a.size();
        int len2 = b.size();
        memset(dp, 0, sizeof(dp));
        for(int i = 1; i <= len1; ++i)
        {
            for(int j = 1; j <= len2; ++j)
            {
                if(a[i - 1] == b[j - 1])
                {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }
                else
                {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        cout<<dp[len1][len2]<<'\n';
    }
    return 0;
}

 

全部评论

相关推荐

吃饭从不配汤:身高体重可以删掉,四六级可以加粗
点赞 评论 收藏
分享
野猪不是猪🐗:还是太卑微了,什么叫放弃本次面试应该说经过评估,贵公司与自己不匹配,决定不再推进后续流程
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务