Encryption最长公共子序列

Description

Alice is considering about sending some messages to Bob. However, she will feel embarrassed if the messages are read by others. Alice is so smart that she develops a novel encryption method. Alice will send two strings to Bob. We call them String_A and String_B. The meaningful message that Alice really want to send is hidden in String_A and String_B. We call the meaningful message String_M. String_M satisfies some rules as follows.

1) String_M is the maximum-length common subsequence of String_A and String_B;

2) A subsequence of a given sequence is the given sequence with some elements (possible none) left out.

Given String_A and String_B, Bob wants to know how long String_M is. However, Bob is not good at mathematics. Since you are the most NB (Nice-and-Brilliant) Hacker in campus, Bob ask you to help him. Given String_A and String_B, could you calculate the length of String_M ?

Input

The input contains many test cases. Each test case contains two lines. The first line is the String_A. The second line is the String_B. (1<=length<=1000)

Output

For each test case, you only need to output an integer in a line.

问题解释:对于两个字符串,求出最长公共子序列的长度

输入:两行字符串string_A和string_B

输出:两个字符串最长公共子序列的长度

解题思路:使用动态规划实现最长公共子序列的求解.假设LCS(Xi,Yj) 表示的是Xi和Yj这两个序列的最长公共子序列的解,则有

1.若Xi == Yj,那么LCS(Xi,Yj) = LCS(Xi-1,Yj-1) + 1

2.若Xi != Yj ,那么LCS(Xi,Yj) = max( LCS(Xi-1,Yj) , LCS(Xi,Yj-1) )

#include <iostream>
#include <string>
#include <algorithm>
#include <string.h>
int c[1005][1005];
using namespace std;
int main(){
    string str_A, str_B;
    while (cin >> str_A >> str_B) {
        memset(c,0,sizeof(c));
        int alen = str_A.size();
        int blen = str_B.size();
        for(int i = 0; i<= alen; i++){
            for(int j = 0; j <= blen; j++){
                if (i == 0 || j ==0) c[i][j] = 0;
                else if (str_A[i-1] == str_B[j-1]) c[i][j] = c[i-1][j-1] +1;
                else c[i][j] = max(c[i-1][j], c[i][j-1]);
            }
        }
        cout << c[alen][blen] << endl;
    }
    return 0;
}                                 

后记:

使用动态规划的算法实现了最长公共子序列的查找,将问题简单化了


你可能感兴趣的:(算法,sicily)