最长公共子序列的算法

来源:互联网 发布:国安数据链接 编辑:程序博客网 时间:2024/05/16 07:25

#include <iostream.h> 
#include <iomanip.h> 
#define   MAX   99 
//typedef   char   MM; 
void   main() 
{   int   i,j,m,n,h=0; 
  char   x[MAX]={ '   ', '   '},y[MAX]={ '   ', '   '},b[MAX][MAX]={ '   '}; 
  int   c[MAX][MAX]={0}; 
  char   temp[MAX]={ '   '}; 
  cout < < "**本程序可以求得字符数在99以内的任意两个字符串的最大公共子序列**/n "; 
  cout < < "请输入第一个字符串的长度m= "; 
  cin> > m; 
  cout < < "请输入第一个字符串(“回车”结束)/n如果输入的字符数超过m,则会出错!/nx[ " < <m < < "]= "; 
  for(i=1;i <=m;i++) 
  cin> > x[i];                                                                                           //键盘输入x和y 
  cout < < "请输入第二个字符串的长度n= "; 
  cin> > n; 
  cout < < "请输入第二个字符串/ny[ " < <n < < "]= "; 
  for(i=1;i <=n;i++) 
  cin> > y[i]; 
        for(i=1;i <=m;i++)c[i][0]=0;                                 //动态规划开始 
        for(i=1;i <=n;i++)c[0][i]=0; 
      for(i=1;i <=m;i++) 
    for(j=1;j <=n;j++) 
    {if(x[i]==y[j]) 
    {c[i][j]=c[i-1][j-1]+1; 
b[i][j]= '// '; 
}else   
if(c[i-1][j]> =c[i][j-1]) 
{   c[i][j]=c[i-1][j]; 
          b[i][j]= '│ '; 
}else{c[i][j]=c[i][j-1]; 
          b[i][j]= '- '; 
} 
    }                                                                       //动态规划结束 
cout < < "c[m][n]中的内容:/n "; 
      for(i=0;i <=m;i++) 
{for(j=0;j <=n;j++) 
    cout < <c[i][j]; 
            cout < <endl; 
} 
cout < < "b[m][n]中的内容:/n "; 
      for(i=1;i <=m;i++) 
{for(j=1;j <=n;j++) 
    cout < <b[i][j]; 
            cout < <endl; 
} 
i=m,j=n; 
while(1) 
{if(i==0││j==0)   break; 
if(b[i][j]== '// '){ 
temp[h++]=x[i];                                         //反序记录最长公共子序列到temp中 
i=i-1,j=j-1; 
} 
else 
if(b[i][j]== '│ ')         
i=i-1; 
else 
j=j-1;} 
cout < < "/nx[ " < <m < < "]和y[ " < <n < < "]的最长公共子序列为: "; 
for(i=h-1;i> =0;i--)                                         //格式化输出最长公共子序列 
          if(i==h-1) 
  if(h==1) 
  cout < < "LCS: < " < <temp[i] < < "> "; 
  else 
                          cout < < "LCS: < " < <temp[i]; 
  else   
  if(i==0) 
  cout < < ", " < <temp[i] < < "> "; 
          else 
                  cout < < ", " < <temp[i]; 
cout < < "/n " < <endl; 
} 

原创粉丝点击