繁体   English   中英

最长公共子序列不打印长度矩阵

[英]Longest Common Subsequence not printing length matrix

我正在尝试在 c 中实现最长公共子序列算法,矩阵 c[][] 存储最长公共子序列的长度,row[][] 将父块行存储在 c[][] 矩阵和 col[ ][] 存储父块列。

我为解决 LCS 的彻底不便和低效的方法道歉,但没有打印出来。 请帮忙。

#include<stdio.h>
#include<stdlib.h>
void lcs(char *a,char *b,int i,int j)
{
    int x,y,z;
    int **c=(int **)malloc((j+1)*sizeof(int *));
    for(x=0;x<j+1;x++)
    {
        *(c+x)=(int *)malloc((i+1)*sizeof(int));
        *(*(c+x)+0)=0;
    }
    for(y=0;y<i+1;i++)
        c[0][y]=0;
    int **row=(int **)malloc((j+1)*sizeof(int *));
    for(x=0;x<j+1;x++)
    {
        *(row+x)=(int *)malloc((i+1)*sizeof(int));
        *(*(row+x)+0)=x-1;
    }
    for(y=0;y<i+1;y++)
        row[0][y]=0;
    row[0][0]=0;
    int **col=(int **)malloc((j+1)*sizeof(int *));
    for(x=0;x<j+1;x++)
    {
        *(col+x)=(int *)malloc((i+1)*sizeof(int));
        *(*(col+x)+0)=0;
    }
    for(y=0;y<i+1;y++)
        col[0][y]=y-1;
    col[0][0]=0;
    for(x=1;x<j+1;x++)
    {
        for(y=1;y<i+1;y++)
        {
            if(a[y-1]==b[x-1])
            {
                c[x][y]=c[x-1][y-1]+1;
                row[x][y]=x-1;
                col[x][y]=y-1;
            }
            else if(c[x-1][y]>
                    c[x][y-1])
            {
                c[x][y]=c[x-1][y];
                row[x][y]=x-1;
                col[x][y]=y;
            }
            else
            {
                c[x][y]=c[x][y-1];
                row[x][y]=x;
                col[x][y]=y-1;
            }
        }
    }
    for(x=0;x<j+1;x++)
    {
        for(y=0;y<i+1;y++)
            printf("%d ",c[x][y]);
        printf("\n");
    }
    printf("\n\n");
    for(x=0;x<j+1;x++)
    {
        for(y=0;y<i+1;y++)
            printf("%d,%d ",row[x][y],col[x][y]);
        printf("\n");
    }
    
}
void main()
{
    char a[30]="papayaman";
    char b[30]="papmn";
    lcs(a,b,9,5);
}

也许它可以简化为这样的东西:

迭代版本(自下而上)

    int lcs(char * A, char * B)
    {
        allocate storage for array L;
        for (i = m; i >= 0; i--)
             for (j = n; j >= 0; j--)
             {
              if (A[i] == '\0' || B[j] == '\0') L[i,j] = 0;
              else if (A[i] == B[j]) L[i,j] = 1 + L[i+1, j+1];
              else L[i,j] = max(L[i+1, j], L[i, j+1]);
             }
        return L[0,0];
      }
====================================================

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM