51nod 1006 longest common subsequence Lcs [LCS/print path]

Base Time Limit: 1 second Space Limit: 131072 KB Score: 0  Difficulty: Basic
 collect
 focus on
Given two strings AB, find the longest common subsequence of A and B (subsequences are not required to be consecutive).
 
For example, two strings are:
 
abcicba
abdkscab
 
ab is the subsequence of the two strings, so is abc, and so is abca, where abca is the longest subsequence of the 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, output 1 at will.
Input example
abcicba
abdkscab
Output example
abca 
[code]:
#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
#define maxn 1005
#define maxm 10005
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;

int n,m,t;
char a[maxn],b[maxn];
int c[maxn][maxn];
int dp[maxn][maxn];


void LCS(int n, int m)
{
   for(int i=1; i<=n; i++){
    for(int j=1; j<=m; j++){
        if(a[i-1] == b[j-1]){
            dp[i][j] = dp[i-1][j-1]+1;
            c[i][j] = 1;
        }
        else if(dp[i-1][j] > dp[i][j-1]){
            dp[i][j] = dp[i-1][j];
            c[i][j] = 2;
        }
        else{
            dp[i][j] = dp[i][j-1];
            c[i][j] = 3;
        }
    }
   }
}


void dfs(int i,int j)
{
    if(!i||!j) return ;
    if(c[i][j]==1){
        dfs(i-1,j-1);
        printf("%c",a[i-1]);
    }
    else if(c[i][j]==2)
        dfs(i-1,j);
    else
        dfs(i,j-1);
}

intmain ()
{
    cin>>a>>b;

    memset(c,0,sizeof(c));
    memset(dp,0,sizeof(dp));

    n=strlen(a);
    m=strlen(b);

    LCS(n,m);
    dfs(n,m);
    cout<<endl;
    return 0;
}
1~n : recursively print

 

#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
#define maxn 1005
#define maxm 10005
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;

int i,j;
char a[maxn];
char b[maxn];
int dp[maxn][maxn];

void LCS(int n, int m)
{
    for(int i=1; i<=n; i++){
        for(int j=1; j<=m; j++){
            if(a[i-1] == b[j-1])
                dp[i][j] = dp[i-1][j-1]+1;

            else if(dp[i][j-1] > dp[i-1][j])
                dp[i][j] = dp[i][j-1];
            else
                dp[i][j] = dp[i-1][j];
      }
   }
}


intmain ()
{
    scanf("%s%s",a,b);

    int n=strlen(a);
    int m=strlen(b);

    LCS(n,m);

    int i= n;
     int j= m;
     int k=dp[i][j]; // reverse char path[ maxn
     ]={ ' \0 ' }; // reverse while (i && j)
    
    {
        if(a[i-1] == b[j-1] && dp[i][j] == dp[i-1][j-1]+1)
        {
            path[ --k]=a[i- 1 ]; // reverse order 
            i-- ;
            j--;
        }
        else if(a[i-1]!=b[j-1]  && dp[i-1][j] > dp[i][j-1])
             i--;
        else j--;
    }
    printf("%s\n",path);
    return 0;
}
1~n : loop print

 

Guess you like

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