Problem Description
The longest common sub-sequence, abbreviated as LCS (longest Com
#include <bits/stdc++.h>Const intmax=1010;CharX[max];CharY[max];intDp[max][max];intB[max][max];using namespacestd;intPrint_lcs (intB[][max],Char*x,intIintj) { if(i==0|| j==0) return 1; if(b[i][j]==1) {Print_lcs (b,x,i-1, J-1); cout<<x[i]<<" "; } Else if(b[i][j]==2) {Print_lcs (b,x,i-1, J); } Else if(b[i][j]==3) {Print_lcs (b,x,i,j-1); }}intMain () {intT; intn,m,i,j; CIN>>T; while(t--) { while(cin>>n>>m) { for(intI=1; i<=n; i++) Cin>>X[i]; for(intj=1; j<=m; J + +) Cin>>Y[j]; memset (DP,0,sizeof(DP)); for(i=1; i<=n; i++) { for(j=1; j<=m; J + +) { if(x[i]==Y[j]) {Dp[i][j]=dp[i-1][j-1]+1; B[I][J]=1; } Else if(dp[i-1][j]>=dp[i][j-1]) {Dp[i][j]=dp[i-1][j]; B[I][J]=2; } Else{Dp[i][j]=dp[i][j-1];//Max (dp[i-1][j],dp[i][j-1]);b[i][j]=3; } }} cout<<DP[n][m]<<Endl; Print_lcs (B,X,N,M); cout<<Endl; } } return 0;}
View Code
Mon subsequence). It is defined as a sequence s, if it is a subsequence of two or more known sequences, and is the longest of all conforming to this condition sequence, then S is called the longest common subsequence of the known sequence. The longest common substring (which requires continuous) and the longest common subsequence is differentApplication
The longest common subsequence is a very practical problem that can describe the similarity between two paragraphs of text, that is, their similarity, which can be used to identify plagiarism. After the modification of a piece of text, the longest common subsequence of the text before and after the change is calculated, and the part outside of this sub-sequence is extracted, and this method is often very accurate in judging the modified part. In short, Baidu knows, Baidu Encyclopedia are used.
Dynamic planning
The first step: the length of the longest common subsequence is calculated first.
The second step: according to the length, and then by backtracking to find the longest common sub-sequence.
Existing two sequence X={x1,x2,x3,...xi},y={y1,y2,y3,....,yi},
Set a c[i,j]: Save the length of the LCS of Xi and YJ.
The recursive equation is:
Code Pro-Test:
LCS (Longest Common subsequence the longest common sub-sequence)