Nyoj 36 Longest common sub-sequence (LCS)

Source: Internet
Author: User
Tags strlen time limit
Longest common sub-sequenceTime limit: Ms | Memory limit: 65535 KB Difficulty: 3 Description Let's not beat around the bush, title, all you need to do is write a program that will draw 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 to give an integer N (0<n<100) to indicate the number of data groups to be tested
The next two lines of data are two sets of strings to be tested.   Each string length is not greater than 1000. Output each set of test data outputs an integer representing the longest common subsequence length.   One row for each group of results. Sample input
2
asdf
adfsd
123abc
abc123abc
Sample output
3
6

LCS bare title, the code is as follows:


 
<span style= "FONT-SIZE:12PX;" > #include <cstdio>
#include <cstring>
int dp[2][1010];
Char a[1010],b[1010];

int max (int a,int b)
{
	return a>b?a:b;
}

int main ()
{
	int t,lena,lenb,i,j;
	scanf ("%d", &t);
	while (t--)
	{
		memset (dp,0,sizeof (DP));
		scanf ("%s%s", b);
		Lena=strlen (a);
		Lenb=strlen (b);
		for (i=1;i<=lena;i++)
		{for
			(j=1;j<=lenb;j++)
			{
				if (a[i-1]==b[j-1])
				   dp[i%2][j]=dp[ (i-1)%2][j-1]+1;
				else
				   Dp[i%2][j]=max (dp[(i-1)%2][j],dp[i%2][j-1]);
			}
		}
		printf ("%d\n", Dp[lena%2][lenb]);
	}
	return 0;
}                 </span>


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.