51nod 1006 最长公共子序列Lcs(输出任意公共子序列)模板

30 篇文章 0 订阅
9 篇文章 0 订阅

题目链接:

http://www.51nod.com/Challenge/Problem.html#problemId=1006

1006 最长公共子序列Lcs

给出两个字符串A B,求A与B的最长公共子序列(子序列不要求是连续的)。

比如两个串为:

abcicba

abdkscab

ab是两个串的子序列,abc也是,abca也是,其中abca是这两个字符串最长的子序列。

 收起

输入

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

输出

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

输入样例

abcicba
abdkscab

输出样例

abca

 最长公共子序列模板

 This is the code:

#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<sstream>
#include<stack>
#include<string>
#include<set>
#include<vector>
using namespace std;
#define PI acos(-1.0)
#define pppp cout<<endl;
#define EPS 1e-8
#define LL long long
#define ULL unsigned long long     //1844674407370955161
#define INT_INF 0x3f3f3f3f      //1061109567
#define LL_INF 0x3f3f3f3f3f3f3f3f //4557430888798830399
// ios::sync_with_stdio(false);
// 那么cin, 就不能跟C的 scanf,sscanf, getchar, fgets之类的一起使用了。
const int dr[]={0, 0, -1, 1, -1, -1, 1, 1};
const int dc[]={-1, 1, 0, 0, -1, 1, -1, 1};
int read()//输入外挂
{
    int ret=0, flag=0;
    char ch;
    if((ch=getchar())=='-')
        flag=1;
    else if(ch>='0'&&ch<='9')
        ret = ch - '0';
    while((ch=getchar())>='0'&&ch<='9')
        ret=ret*10+(ch-'0');
    return flag ? -ret : ret;
}
const int MAXN = 1010;
char str1[MAXN];//两个字串
char str2[MAXN];
int dp[MAXN][MAXN];//dp[n][m]为最长
char path[MAXN];//最长公共子序列
int plen;//公共子序列长度

void lcs(int len1, int len2)//查找最长公共子序列长度
{
    for(int i = 0; i < len1; ++i)
    {
        for(int j = 0; j < len2; ++j)
        {
            if(str1[i] == str2[j])
                dp[i+1][j+1] = dp[i][j]+1;
            else
                dp[i+1][j+1] = max(dp[i+1][j],dp[i][j+1]);
        }
    }
}
void Print()
{
    int i = strlen(str1)-1;
    int j = strlen(str2)-1;
    plen = 0;//记录路径
    while(i >= 0 && j >= 0)
    {
        if(str1[i] == str2[j])
        {
            path[plen++] = str1[i];
            --i;
            --j;
        }
        else if(dp[i+1][j] >= dp[i][j+1]) //说明lcs是str1[0~i]和str2[0~j-1]的lcs
            --j;
        else
            --i;
    }
}

int main()
{
    scanf(" %s %s",str1,str2);
    int len1 = strlen(str1);
    int len2 = strlen(str2);
    lcs(len1,len2);
    Print();
    for(int i = plen-1; i >= 0; --i)
        printf("%c",path[i]);
    printf("\n");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值