zoukankan      html  css  js  c++  java
  • 打印路径——最长公共子序列打印路径

    打印路径时需要引进一个数组b进行递归打印

    在LCS中,如果是公共子节点,则标记为1,如果不是,标记为2、3,分别表示往上递归或者往左递归

    对于样例:

    /*输入
    ABCBDAB
    BDCABA
    */
    数组c中各值为:

    数组b中各值为:

                                             

    # include<stdio.h>
    # include<string.h>
    # define maxn 105
    # define max(a,b) a>b?a:b
    int c[maxn][maxn],b[maxn][maxn],m,n;
    char x[maxn],y[maxn];
    void lcs(int i,int j)
    {
        if (i ==0 || j==0) return;
        if (b[i][j]== 1)
        {
            lcs(i-1,j-1);
            printf("%c",x[i-1]);
        }
        else if (b[i][j]== 2)
            lcs(i-1,j);
        else
            lcs(i,j-1);
    }
    
    int main()
    {
        int i,j;
        while(gets(x)&&gets(y))
        {
            m=strlen(x);
            n=strlen(y);
            for(i=0; i<=m; i++)
                c[i][0] = 0;
            for(j=0; j<=n; j++)
                c[0][j] = 0;
    
            for(i=1; i<=m; i++)
            {
                for(j=1; j<=n; j++)
                {
                    if (x[i-1]==y[j-1])
                    {
                        c[i][j]=c[i-1][j-1]+1;
                        b[i][j]=1;
                    }
                    else if (c[i-1][j]>=c[i][j-1])
                    {
                        c[i][j]=c[i-1][j];
                        b[i][j]=2;
                    }
                    else
                    {
                        c[i][j]=c[i][j-1];
                        b[i][j]=3;
                    }
                }
            }
            printf("最长公共子序列长度 = %d
    ",c[m][n]);
            printf("最长公共子序列是: ");
            lcs(m,n);
            puts("");
        }
        return 0;
    }
    /*输入
    ABCBDAB
    BDCABA
    */
  • 相关阅读:
    react方法传参的两种方式
    react引入本地图片和远程图片
    用yarn代替npm
    react生命周期
    react子传父
    react删除元素
    react遍历数组
    react监听input框里的值
    react创建组件的两种方式
    vue打包更改dist文件夹名称
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/3182797.html
Copyright © 2011-2022 走看看