1. 程式人生 > >AOJ_ALDS1_10_C Longest Common Subsequence【LCS+DP】

AOJ_ALDS1_10_C Longest Common Subsequence【LCS+DP】

Longest Common Subsequence
Aizu - ALDS1_10_C

For given two sequences X and Y, a sequence Z is a common subsequence of X and Y if Z is a subsequence of both X and Y. For example, if X={a,b,c,b,d,a,b} and Y={b,d,c,a,b,a}, the sequence {b,c,a} is a common subsequence of both X and Y. On the other hand, the sequence {b,c,a} is not a longest common subsequence (LCS) of X and Y, since it has length 3 and the sequence {b,c,b,a}, which is also common to both X and Y, has length 4. The sequence {b,c,b,a} is an LCS of X and Y, since there is no common subsequence of length 5 or greater.

Write a program which finds the length of LCS of given two sequences X and Y. The sequence consists of alphabetical characters.

Input

The input consists of multiple datasets. In the first line, an integer qq which is the number of datasets is given. In the following 2×q lines, each dataset which consists of the two sequences X and Y are given.

Output

For each dataset, print the length of LCS of X and Y in a line.

Constraints

1≤q≤150
1≤ length of X and Y ≤1,000
q≤20 if the dataset includes a sequence whose length is more than 100

Sample Input 1

3
abcbdab
bdcaba
abc
abc
abc
bc

Sample Output 1

4
3
2

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

問題連結AOJ_ALDS1_10_C Longest Common Subsequence
問題簡述:(略)
問題分析
    動態規劃問題,是一個標準模板題,套模板就可以了。
    需要注意字串長度!
程式說明:(略)
    該程式使用C++語言編寫,使用了string變數,並且把LCS演算法封裝到函式lcs()中。
題記:(略)
參考連結POJ1458 HDU1159 ZOJ1733 UVALive2759 Common Subsequence【最長公共子序列+DP】

AC的C++語言程式如下:

/* AOJ_ALDS1_10_C Longest Common Subsequence */

#include <iostream>
#include <string.h>

using namespace std;

const int N = 1000;

int lcs(string& a, string& b)
{
    int dp[N + 1][N + 1];
    memset(dp, 0, sizeof(dp));
    for(int i = 0; i < (int)a.size(); i++)
        for(int j = 0; j < (int)b.size(); 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]);

    return dp[a.size()][b.size()];
}

int main()
{
    string s1, s2;
    int q;

    cin >> q;
    for(int i = 1; i <= q; i++) {
        cin >> s1 >> s2;
        cout << lcs(s1, s2) << endl;
    }

    return 0;
}