NYOJ 36 LCS (Longest Common Subsequence)

Topic link:

http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=36

longest common subsequence

Time Limit: 3000 ms | Memory Limit: 65535 KB
Difficulty: 3
 
describe
Let's not beat around the bush. For example, all you need to do is write a program to get the longest common subsequence.
tip: The longest common subsequence is also called the longest common subsequence (not required to be continuous), and the English abbreviation is LCS (Longest Common Subsequence). Its definition is that if a sequence S is a subsequence of two or more known sequences, and is the longest among all sequences that meet this condition, then S is called the longest common subsequence of known sequences.
 
enter
The first line gives an integer N (0<N<100) to indicate the number of data sets to be tested.
The next two lines of data for each set of data are the two sets of strings to be tested. The length of each string is not greater than 1000.
output
Each set of test data outputs an integer representing the length of the longest common subsequence. Each set of results occupies one line.
sample input
2
asdf
adfsd
123abc
abc123abc
Sample output
3
6

#include<bits/stdc++.h>
using namespace std;
int f_max(int a,int b)
{
    if(a>b)
        return a;
    else
        return b;
}
intmain ()
{
    int t;
    scanf("%d",&t);
    getchar();
    while(t--)
    {
        char a[1005];
        char b[1005];
        gets(a);
        gets(b);
        int l1=strlen(a);
        int l2=strlen(b);
        int dp[l1+1][l2+1];
        memset(dp, 0 , sizeof (dp));
         // dp[i][j] represents the LCS length of a0.....ai and b0....bj 
        for ( int i= 1 ; i<=l1 ; i++ )
        {
            for(int j=1; j<=l2; j++)
            {
                if (a[i- 1 ]==b[j- 1 ]) // Think that i and j start from 1, so i-1,j-1 
                {
                    dp[i][j]=dp[i-1][j-1]+1;
                }
                else
                {
                    dp[i][j]=f_max(dp[i-1][j],dp[i][j-1]);
                }
            }
        }
        printf("%d\n",dp[l1][l2]);
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325343300&siteId=291194637