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;
}
後記:
使用動態規劃的算法實現了最長公共子序列的查找,將問題簡單化了