1. 程式人生 > >POJ 1458 Common Subsequence(動態規劃)

POJ 1458 Common Subsequence(動態規劃)

Common Subsequence

Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 61454   Accepted: 25710

Description

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, xij = 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

十分經典的動態規劃問題

輸入兩個串s1,s2,設MaxLen(i,j)表示:s1的左邊i個字元形成的子串,與s2左邊的j個字元形成的子串的最長公共子序列的長度(i,j從0開始算)MaxLen(i,j) 就是本題的“狀態”假定 len1 = strlen(s1),len2 = strlen(s2)那麼題目就是要求 MaxLen(len1,len2)

顯然:
MaxLen(n,0) = 0 ( n= 0...len1)
MaxLen(0,n) = 0 ( n=0...len2)
遞推公式:
if ( s1[i-1] == s2[j-1] ) //s1的最左邊字元是s1[0] 
MaxLen(i,j) = MaxLen(i-1,j-1) + 1;
else
MaxLen(i,j) = Max(MaxLen(i,j-1),MaxLen(i-1,j) );

程式碼如下:

#include<iostream>
#include<cstdio>
using namespace std;
int maxLen[1000][1000];
int main()
{
    string s1,s2;
    while(cin >> s1 >> s2)
    {
        int length1 = s1.length();
        int length2 = s2.length();
        for(int i = 0;i < length1; i++)
            maxLen[i][0] = 0;
        for(int i = 0;i < length2; i++)
            maxLen[0][i] = 0;
        for(int i = 1;i <= length1; i++)
        {
            for(int j = 1;j <= length2; j++)
            {
                if(s1[i - 1] == s2[j - 1])
                    maxLen[i][j] = maxLen[i - 1][j - 1] + 1;
                else
                    maxLen[i][j] = max(maxLen[i - 1][j],maxLen[i][j - 1]);
            }
        }
        cout << maxLen[length1][length2] << endl;
    }
    return 0;
}

PS:本文大部分內容摘自郭煒老師課件