您的位置:首页 > 编程语言 > C语言/C++

最长公共子序列(LCS)的C++实现

2017-07-26 22:09 363 查看
首先有如下递归式



绘制图表如下



首先我们实现最长公共子序列长度的输出,代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
int table[100][100] = { 0 };
int main()
{
string a, b;
cin >> a >> b;
int m = a.length();
int n = b.length();
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (a[i-1] == b[j-1])
{
table[i][j] = table[i - 1][j - 1] + 1;
}
else
{
table[i][j] = max(table[i - 1][j], table[i][j - 1]);
}
}
}
cout << table[m]
<< endl;
system("pause");
}只需做一点小改动,假如一个判断数组和一个输出函数,用到递归,代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
int table[100][100] = { 0 };
int judge[100][100] = { 0 };
int print_LCS(int judge[][100], string x,int,int);
int main()
{
string a, b;
cin >> a >> b;
int m = a.length();
int n = b.length();
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (a[i-1] == b[j-1])
{
table[i][j] = table[i - 1][j - 1] + 1;
judge[i][j] = 1;
}
else if(table[i - 1][j] >= table[i][j - 1])
{
table[i][j] = table[i - 1][j];
judge[i][j] = 2;
}
else
{
table[i][j] = table[i][j - 1];
judge[i][j] = 3;
}
}
}
cout << table[m]
<< endl;
print_LCS(judge, a, m, n);
cout << endl;
system("pause");
}
int print_LCS(int judge[][100],string a,int x,int y)//x,y,分别为两段长度
{
if (x == 0 || y == 0)
{
return 0;
}
if (judge[x][y] == 1)
{
print_LCS(judge, a, x-1, y-1);
cout << a[x-1];
}
if (judge[x][y] == 2)
{
print_LCS(judge, a, x - 1, y);
}
if (judge[x][y] == 3)
{
print_LCS(judge, a, x, y - 1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: