최대 공통 하위 시퀀스(LCS): 동적 계획
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 }
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.