`
hojor
  • 浏览: 108710 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

最长公共子序列

阅读更多

用动态规划实现的最长公共子序列

 

#include<stdio.h>
#include<stdlib.h>

/*==============*\
 |最长公共子序列 
\*==============*/ 

/*!<打印最长公共子序列*/
void printLCS(char ** a,int m,int n,const char *s1, const char *s2)
{
      int i,j;
      if( m==1||n==1 )
      {
           if( a[m][n] == 1 )
               printf("%c",s1[m-1]);
      }
      else if( a[m][n] == a[m][n-1] )
           printLCS( a, m, n-1, s1, s2 );
      else if( a[m][n] == a[m-1][n] )
           printLCS( a, m-1, n, s1, s2 );
      else 
      {
           printLCS( a, m-1, n-1, s1, s2 );
           printf("%c",s1[m-1]);        
      }
}

/*!<LCS算法*/ 
int LCS(const char *s1, const char *s2)
{// s1:0...m, s2:0...n
    int m = strlen(s1), n = strlen(s2);
    int i, j;
    
    //--
    char ** a;
    a = (char**)malloc((m+1)*sizeof(char*));
    for(i=0;i<m+1;i++)a[i]=(char*)malloc((n+1)*sizeof(char));
    
    //--
    for( i=1; i <= m; ++i ) 
         a[i][0] = 0;
    for( i=1; i <= n; ++i ) 
         a[0][i] = 0;
    for( i=1; i <= m; ++i )
         for( j=1; j <= n; ++j )
         {
              if(s1[i-1]==s2[j-1]) 
                  a[i][j] = a[i-1][j-1]+1;
              else if(a[i-1][j]>a[i][j-1])
                   a[i][j]= a[i-1][j];
              else 
                   a[i][j] = a[i][j-1];
         }
    
    //--     
    printLCS(a,m,n,s1,s2);
    putchar('\n');
    
    return a[m][n];
}

/*!< main*/
int main(void)
{
    int m;
    
    char * s1 = "178946546adfea54f6a4sd6a155";
    char * s2 = "sdfa46879841a6asdfaa3dfa65a";
    
    m = LCS( s1, s2 );
    
    printf("%d\n",m);
    
    system("pause");
    return 0;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics