51nod 1006 最长公共子序列Lcs

给出两个字符串A B,求A与B的最长公共子序列(子序列不要求是连续的)。
比如两个串为:
 
abcicba
abdkscab
 
ab是两个串的子序列,abc也是,abca也是,其中abca是这两个字符串最长的子序列。
 

输入

第1行:字符串A
第2行:字符串B
(A,B的长度 <= 1000)

输出

输出最长的子序列,如果有多个,随意输出1个。

输入样例

abcicba
abdkscab

输出样例

abca

动态规划状态转移方程为dp[i + 1][j + 1] = max(max(dp[i][j + 1],dp[i + 1][j]),dp[i][j] + (s[i] == t[j] ? 1 : 0));
构建解字符串采用递归实现。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAX 50000
#define DMAX 10000
using namespace std;
typedef long long ll;
char s[1001],t[1001];
int dp[1001][1001],ans,m;
void getans(int x,int y) {
    if(!x || !y) return ;
    if(s[x - 1] == t[y - 1]) {
        getans(x - 1,y - 1);
        printf("%c",s[x - 1]);
    }
    else if(dp[x][y - 1] > dp[x - 1][y]) getans(x,y - 1);
    else getans(x - 1,y);
}
int main() {
    scanf("%s%s",s,t);
    for(int i = 0;s[i];i ++) {
        for(int j = 0;t[j];j ++) {
            dp[i + 1][j + 1] = max(max(dp[i][j + 1],dp[i + 1][j]),dp[i][j] + (s[i] == t[j] ? 1 : 0));
        }
    }
    getans(strlen(s),strlen(t));
}
原文地址:https://www.cnblogs.com/8023spz/p/10055551.html