nyoj36--longest common sub-sequence

Source: Internet
Author: User
Tags strlen

Topic Links:

Title Analysis: Assume that two strings are labeled STR1 and STR2, respectively. Establishes a two-dimensional table dp,dp[i][j] represents the number of the longest common subsequence of the first I character of the str1 and the first J characters of the str2, traversing all elements of str1 and str2, if str1[i] = Str2[j], then dp[i][j] = dp[i-1][j-1 ] + 1; otherwise dp[i][j] = max (dp[i-1][j],dp[i][j-1]). To prevent the array from crossing out, add a row and column to the top and right of the DP, assigning a value of 0. The calculation process is shown in the following table, where the red number represents the need to add 1.

A D F S D
0 0 0 0 0 0
A 0 1 1 1 1 1
S 0 1 1 1 2 2
D 0 1 2 2 2 3
F 0 1 2 3 3 3

Reference code:

 #include <stdio.h> #include <string.h> int dp[1001][1001]; char str1[1001]; Char str2[1001

];

inline int max (const int A, const int b) {return a > b a:b;}
	int main () {int n,t;
	int i,j;
	int nlen1,nlen2;
	scanf ("%d", &t);
	GetChar ();
		while (t--) {gets (STR1);
		Gets (STR2);
		NLen1 = strlen (STR1);
		NLen2 = strlen (STR2);
		Memset (Dp,0,sizeof (DP));  for (i = 1; I <= nLen1; ++i) {for (j = 1; j <= NLen2; ++j) {if (str1[i-1] = = Str2[j-1]) dp[i][j]
				= Dp[i-1][j-1] + 1;
			else dp[i][j] = max (Dp[i-1][j], dp[i][j-1]);
	}} printf ("%d\n", Dp[nlen1][nlen2]); }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.