One: function
The problem of the longest common subsequence is often used to solve the similarity of the string, it is a very useful algorithm, as the code farm, this algorithm is our essential basic.
II: Concept
For example, how many cnblogs are there in the neutron sequence of a string? Obviously there are 27 of them, such as CB,CGS, and so on, which are the subsequence, and we can see
The subsequence is not necessarily continuous, it is a substring.
I think you already know the concept of sub-sequences, which can now be extended to two strings, then you can see: Cnblogs and belong common sub-sequences?
Can you find the longest common subsequence in the common sub-sequence you find?
We see the longest common subsequence for the blog, think about it we can find that the number of the longest common subsequence is not unique, there may be more than two,
But the length must be unique, such as the length of the longest common sub-sequence here is 4.
Three: Solutions
<1> Enumeration method
This method is the simplest, but also the most easy to think of, of course, time complexity is also the turtle speed, we can analyze, just said Cnblogs's sub-sequence
The number has 27, extend: A string of length n, its subsequence has 2N, each subsequence to match in the second length n string, match once
The time required O (N), a total of O (n*2n), can be seen, the time complexity is the point of magnitude, the horror of suffocation.
<2> Dynamic Planning
Since it is the classic topic certainly has the optimization space, and the problem solving method is has the fixed process, here we use is the matrix realization, namely two dimensional array.
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:
I wonder if you can read it? One of the important characteristics of dynamic programming is to solve the "sub-problem overlap" scene, can effectively avoid repeated calculations, according to the above
The formula can actually find that c[i,j] has kept the maximum subsequence length of the current (Xi,yi).
Title: Do not repeat, template questions
#include <stdio.h> #include <algorithm> #include <string.h> #include <iostream>using namespace Std;int dp[25][25];int a[25];int x[25];int main () {int n,i,j;scanf ("%d", &n), for (i=1;i<=n;i++) {int b;scanf ("%d") , &b); a[b]=i;} int T;while (scanf ("%d", &t)!=eof) {x[t]=1;for (i=2;i<=n;i++) {int b;scanf ("%d", &b); x[b]=i;} Memset (Dp,0,sizeof (DP)); for (i=1;i<=n;i++) {for (j=1;j<=n;j++) {if (A[i]==x[j]) DP[I][J]=DP[I-1][J-1]+1;ELSEDP I [J]=max (Dp[i][j-1],dp[i-1][j]);}} printf ("%d\n", Dp[n][n]);} return 0;}
Dynamic planning of retreat cultivation-the longest common subsequence (UVA111)