当前位置:嗨网首页>书籍在线阅读

12-实战演练

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

4.3.5 实战演练

//program 4-1
#include <iostream>
#include<cstring>
using namespace std;
*ons tint N=1002;
int c[N][N],b[N][N];
char s1[N],s2[N];
int len1,len2;
void LCSL()
{
     int I,j;
     for(I = 1;I <= len1;i++)//控制s1序列
       for(j = 1;j <= len2;j++)//控制s2序列
       {
         if(s1[i-1]==s2[j-1])
         {//如果当前字符相同,则公共子序列的长度为该字符前的最长公共序列+1
             c[i][j] = c[i-1][j-1]+1;
             b[i][j] = 1;
         }
         else
         {
             if(c[i][j-1]>=c[i-1][j])
             {
                  c[i][j] = c[i][j-1];
                  b[i][j] = 2;
             }
             else
             {
                  c[i][j] = c[i-1][j];
                  b[i][j] = 3;
             }
         }
     }
}
void print(int I, int j)//根据记录下来的信息构造最长公共子序列(从b[i][j]开始递推)
{
     if(i==0 || j==0) return;
     if(b[i][j]==1)
     {
         print(i-1,j-1);
         cout<<s1[i-1];
     }
     else if(b[i][j]==2)
               print(I,j-1);
            else
               print(i-1,j);
}
int main()
{
     int I,j;
     cout << "输入字符串s1:"<<endl;
     cin >> s1;
     cout << "输入字符串s2:"<<endl;
     cin >> s2;
     len1 = strlen(s1);//计算两个字符串的长度
     len2 = strlen(s2); 
     for(I = 0;I <= len1;i++)
     {
          c[i][0]=0;//初始化第一列为0
     }
     for(j = 0;j<= len2;j++)
     {
          c[0][j]=0;//初始化第一行为0
     }
     LCSL();   //求解最长公共子序列
     cout << "s1和s2的最长公共子序列长度是:"<<c[len1][len2]<<endl;
     cout << "s1和s2的最长公共子序列是:";
     print(len1,len2);   //递归构造最长公共子序列最优解
     return 0;
}

算法实现和测试

(1)运行环境

Code::Blocks

(2)输入

输入字符串s1:
ABCADAB
输入字符串s2:
BACDBA

(3)输出

s1和s2的最长公共子序列长度是:4
s1和s2的最长公共子序列是:BADB