//求解最长公共子序列
#include<iostream>
#include<stdio.h>
#include<iomanip>
using namespace std;
const int length = 100;
void LCSLength(int m, int n, char* x, char* y, int** c, int** b)
{
int i, j;
for (i = 0; i <= m; i++)
{
c[i][0] = 0;
b[i][0] = 0;
}
for (i = 0; i <= n; i++)
{
c[0][i] = 0;
b[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] = 1;
}
else if (c[i - 1][j] >= c[i][j - 1])
{
c[i][j] = c[i - 1][j];
b[i][j] = 2;
}
else
{
c[i][j] = c[i][j - 1];
b[i][j] = 3;
}
}
}
void LCS(int i,int j,char* x, int** b)
{
if (i == 0 || j == 0)
return;
if (b[i][j] == 1)
{
LCS(i - 1, j-1, x, b);
cout << x[i];
}
else if (b[i][j] == 2)
{
LCS(i - 1, j, x, b);
}
else
{
LCS(i,j-1,x,b);
}
}
void LCSLENGTH(int m,int n,int **b,string **d)
{
int i, j;
for (i = 0; i <= m; i++)
{
for (j = 0; j <= n; j++)
{
if (b[i][j] == 1)
{
d[i][j] = "\\";
}
else if (b[i][j] == 2)
d[i][j] = "l";
else if(b[i][j]==3)
d[i][j] = "——";
}
}
cout << "方向矩阵:" << endl;
for (i = 0; i <=m; i++)
{
for (j = 0; j <=n; j++)
{
cout << setw(10) << d[i][j];
}
cout << endl;
}
}
void DisplayLCSLengt(int m, int n, char* x, int** c, int** b)
{
int i, j;
for (i = 0; i <= m; i++)
{
for (j = 0; j <=n; j++)
{
cout << setw(10) << c[i][j];
}
cout << endl;
}
cout << endl;
cout << "最长公共子序列";
LCS(m, n, x, b);
cout << endl;
}
int main()
{
char x[length], y[length];
int i, j, m, n;
cout << "请输入序列A的长度";
cin >> m;
cout << "请输入序列A";
for (i = 0; i < m; i++)
cin >> x[i];
cout << "请输入序列B的长度";
cin >> n;
cout << "请输入序列B";
for (i = 0; i < n; i++)
cin >> y[i];
int** c = new int* [length];
int** b = new int* [length];
string** d = new string* [length];
for (i = 0; i < length; i++)
{
c[i] = new int[length];
b[i] = new int[length];
d[i] = new string[length];
}
LCSLength(m, n, x, y, c, b);
DisplayLCSLengt(m, n, x, c, b);
LCSLENGTH(m, n, b, d);
system("pause");
return 0;
}
04-19
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)