최대 공통 하위 시퀀스(LCS): 동적 계획

5101 단어

D-LCS
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = another sequence Z = is a subsequence of X if there exists a strictly increasing sequence of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = is a subsequence of X = 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. The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. 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.
Input
abcfbc abfcab
programming contest 
abcd mnp

Output
4
2
0

Sample Input
abcfbc abfcab
programming contest 
abcd mnp

Sample Output
4
2
0

DP의 사고방식은 매우 간단하다. 왜냐하면 상태 이동 방정식은 쉽게 찾을 수 있기 때문이다.
우리는 이 두 서열 a, b의 길이를 각각 i와 j, d[i][j]로 설정하여 가장 긴 공공 서열의 길이를 나타낸다.
그러면 상태 이동 방정식이 있다.
d[i][j]=max(d[i-1][j],d[i][j-1]) ,a[i]!=b[j]
d[i][j]=d[i-1][j-1]+1 ,a[i]=b[j]
두 서열을 한 번 훑어보면 d[i][j]를 얻을 수 있다.
코드는 다음과 같습니다.
 1 #include
 2 #include
 3 const int MAXN=1e3+1;
 4 using namespace std;
 5 string a,b;
 6 int dp[MAXN][MAXN];
 7 int main()
 8 {
 9     memset(dp,0,sizeof(dp));
10     while(cin>>a>>b)
11     {
12         int n=a.size();
13         int m=b.size();
14         //cout<
15         for(int i=0;i)
16         {
17             for(int j=0;j)
18             {
19                 if(a[i]==b[j])dp[i+1][j+1]=dp[i][j]+1;
20                 else dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
21                 //cout<
22             }
23         }
24         cout<endl;
25     }
26 }

좋은 웹페이지 즐겨찾기