gouzaogongoo
来源:百度文库 编辑:神马文学网 时间:2024/10/02 17:58:53
#include
#include
#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[ " < for(i=1;i <=m;i++)
cin> > x[i]; //键盘输入x和y
cout < < "请输入第二个字符串的长度n= ";
cin> > n;
cout < < "请输入第二个字符串\ny[ " < 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 < cout < }
cout < < "b[m][n]中的内容:\n ";
for(i=1;i <=m;i++)
{for(j=1;j <=n;j++)
cout < cout <}
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[ " <for(i=h-1;i> =0;i--) //格式化输出最长公共子序列
if(i==h-1)
if(h==1)
cout < < "LCS: < " < ";
else
cout < < "LCS: < " < else
if(i==0)
cout < < ", " < ";
else
cout < < ", " <cout < < "\n " < }
#include
#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[ " <
cin> > x[i]; //键盘输入x和y
cout < < "请输入第二个字符串的长度n= ";
cin> > n;
cout < < "请输入第二个字符串\ny[ " <
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 <
cout < < "b[m][n]中的内容:\n ";
for(i=1;i <=m;i++)
{for(j=1;j <=n;j++)
cout < cout <
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[ " <
if(i==h-1)
if(h==1)
cout < < "LCS: < " <
else
cout < < "LCS: < " <
if(i==0)
cout < < ", " <
else
cout < < ", " <