Longest Common Substring (\ (lcs\)What is a subsequence?
A sub-sequence is a discontinuous part of a sequence.
, \ (abcde\) is a sub-sequence of the sequence in the graph.
Common sub-sequences
The definition of a common subsequence is a subsequence that is common to two sequences. Qwq
Some questions will ask us to ask for the longest common subsequence of two sequences.
If you go straight to 22, the complexity explodes!
So introduce \ (O (n\times m) \) procedure.
\ (dp\)
We set \ (f[i][j]\) to represent the length of the longest common subsequence from the arrival \ (a\) string ( i\) location,\ (b\) string ( j\) .
How does state transfer work?
We found that if we were to make the length of our common subsequence longer, we would have to have a condition of \ (a[i]==b[j]\)
Therefore, there are two situations.
One.\ (a[i]==a[j]\)
State transition equation
\[f[i][j]=f[i-1][j-1]+1\]
Then directly inherit the previous situation.
Two.\ (a[i]!=a[j]\)
The point to consider is that we still have to pass the state.
Current \ (f[i][j]\) needs to inherit the previous state fetch to \ (max\).
So what's the last state here?
What we can know is that\ (i-1\) position and \ (j\) position already have solution,\ (i\) position and \ (j-1\) position already have solution.
How to do it? The current position inheritance can be selected in the state that is the above two states.
So the state transfer equation is
\[f[i][j]=max (f[i-1][j],f[i][j-1]) \]
Why is that correct?
Our current position is \ (a\) string \ (i\) and \ (b\) string \ (j\), the longest common sub-sequence may be \ (a\) string \ (i-1\) The location is combined with the \ (b\) string \ (j\) location,
State transition equation
\[\begin{cases}f[i][j]=f[i-1][j-1]+1 (A[i]==a[j]) \\f[i][j]=max (F[i-1][j],f[i][j-1]) (A[i]!=a[j]) \\\end{cases}\]
Because the current position \ (i\) state is only related to the previous position \ (i-1\) , we can scroll the array.
The scrolling array is not much more BB emmm,
Code
#include<cstdio>#include<cstring>#include<iostream>#define R registerusing namespace std;char a[5008],b[5008];int lena,lenb;int f[2][5008];int main(){ scanf("%s%s",a+1,b+1); lena=strlen(a+1); lenb=strlen(b+1); for(R int i=1;i<=lena;i++) { int op=i&1; for(R int j=1;j<=lenb;j++) { if(a[i]==b[j]) f[op][j]=f[op^1][j-1]+1; else f[op][j]=max(f[op^1][j],f[op][j-1]); } } printf("%d",f[lena&1][lenb]); return 0;}
Longest Common Substring ($LCS $)