51nod 1006 最长公共子序列Lcs【模板】

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

abcicba
abdkscab

ab是两个串的子序列,abc也是,abca也是,其中abca是这两个字符串最长的子序列。
Input
第1行:字符串A
第2行:字符串B

(A,B的长度 <= 1000)
Output

输出最长的子序列,如果有多个,随意输出1个。
Input示例
abcicba
abdkscab
Output示例
abca

dp的经典题。《程序设计在线》一书上有LCS的讲解,不过书上比这题简单一点的是直接求最长公共子序列长度,而不用回溯输出子序列。



#include<stdio.h>
#include<string.h>

#define N 1000
char str1[N+10],str2[N+10];
int a[N+10][N+10],b[N+10][N+10];

void LCS(char *x,char *y,int n,int m,int a[][N+10],int b[][N+10] )
{//找到最长公共子序列
    int i,j;
    for(i = 0; i <= n; i ++)
        a[i][0] = 0;
    for(j = 0; j <= m; j ++)
        a[0][j] = 0;
    for( i = 1; i <= n; i ++)
        for( j = 1; j <= m; j ++)
        {
            if(x[i-1] == y[j-1])
            {//下标从0开始,故为i-1,j-1。
                a[i][j] = a[i-1][j-1]+1;
                b[i][j] = 1; 
            }
            else 
            {
                if( a[i-1][j] > a[i][j-1])
                {
                    a[i][j] = a[i-1][j] ;
                    b[i][j] = 0;
                }
                else
                {
                    a[i][j] = a[i][j-1] ;
                    b[i][j] = -1;
                }
            }

        }
    return;
}

void PrintLcs(char *s,int n,int m,int b[][N+10])
{//回溯输出子序列
    if( 0 == n|| 0 == m)
        return;
    else if( b[n][m] == 1)
    {
        PrintLcs(s,n-1,m-1,b);
        printf("%c",s[n-1]);
    }
    else if( b[n][m] == 0)
    {
        PrintLcs(s,n-1,m,b);
    }
    else if(b[n][m] == -1)
        PrintLcs(s,n,m-1,b);
}

int main()
{
    int l1,l2;
    int i,j;
    while(scanf("%s",str1)!=EOF)
    {
        scanf("%s",str2);
        l1 = strlen(str1);
        l2 = strlen(str2);
        LCS(str1,str2,l1,l2,a,b);
        PrintLcs(str1,l1,l2,b);
        printf("\n");
    }
    return 0;
}

转载于:https://www.cnblogs.com/hellocheng/p/7350132.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值