This is a lot of algorithmic books, not limited to the introduction to algorithms.
Longest common sub-sequence
Time limit: ms | Memory limit:65535 KB
Difficulty:3
Describe
Let's not beat around the bush, title, all you need to do is write a program that draws the longest common subsequence.
Tip: The longest common subsequence is also known as the longest common substring (not requiring continuous), and the abbreviation is LCS (longest Common 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.
-
Enter
-
The first line gives an integer n (0 <N<100) indicates the number of data groups to be tested
the next two lines of data, respectively, are two sets of strings to be tested. Each string is less than the length of the.
-
Output
-
Each set of test data outputs an integer representing the longest common subsequence length. One row for each group of results.
-
Sample input
-
2ASDFADFSD123ABCABC123ABC
-
Sample output
-
3
#include <iostream> #include <cstring> #include <string>using namespace Std;int a[1010][1010];int max (int x, int y) {return x>y? X:y;} int main () {int test,i,j,k,len1,len2,lcs;string s1,s2;cin>>test;while (test--) {cin>>s1>>s2;len1= S1.length (); Len2=s2.length (); memset (A,0,sizeof (a)); Lcs=0;for (i=1;i<len1+1;i++) {for (j=1;j<len2+1;j++) {if ( S1[i-1]==s2[j-1]) A[i][j]=a[i-1][j-1]+1;elsea[i][j]=max (a[i][j-1],a[i-1][j]); if (A[i][j]>lcs) lcs=a[i][j];}} Cout<<lcs<<endl;} return 0;}
Nyoj 36 Longest common sub-sequence (or DP)