51Nod-1006 longest common subsequence Lcs

Keywords: C++

Title Link

 

Description

Given two strings A B, find the longest common subsequence of A and B (subsequence does not need to be continuous).

For example, two strings are:
   abcicba
   abdkscab
ab is the subsequence of two strings, so is abc, and so is abca, in which abca is the longest subsequence of these two strings.
 
Input

Line 1: string A

Line 2: String B

(length of A,B < = 1000)

Output

Output the longest subsequence. If there are multiple subsequences, output one at will.

 

Input example

 abcicba

 abdkscab

 

Output example
 abca
 
 
The code is as follows:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
const int N = 1005;
int dp[N][N];
char s1[N], s2[N], s[N];

void getLCA(int i,int j,int k)
{
    if (k<0) return;
    if (s1[i]==s2[j])
    {
        s[k] = s2[j]; //or s[k]=s1[i].
        getLCA(i-1,j-1,k-1);
        return;
    }
    if (dp[i - 1][j] >= dp[i][j - 1]) getLCA(i-1,j,k);
    else getLCA(i, j - 1, k);
}

int main()
{
    while (scanf("%s", s1) != EOF)
    {
        scanf("%s", s2);
        int len_s1 = strlen(s1);
        int len_s2 = strlen(s2);
        memset(dp,0,sizeof(dp));
        for (int i = 0; i < len_s1; i++)
        {
            for (int j = 0; j < len_s2; j++)
            {
                if (i == 0 || j == 0) {
                    dp[i][j] = (s1[i] == s2[j]);
                    if (i) dp[i][j] = max(dp[i][j], dp[i - 1][j]);
                    if (j) dp[i][j] = max(dp[i][j], dp[i][j - 1]);
                    continue;
                }
                dp[i][j] = max(dp[i][j-1], dp[i - 1][j]);
                dp[i][j] = max(dp[i][j],dp[i-1][j-1]+(s1[i]==s2[j]));
            }
        }
        int len = dp[len_s1 - 1][len_s2 - 1];
        s[len] = '\0';
        getLCA(len_s1-1,len_s2-1,len-1);
        puts(s);
    }
}

 

Posted by marketboy on Sat, 21 Dec 2019 09:16:53 -0800