#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
/*
CLion 使用提示 :
批量注释代码 => Ctrl + shift + /
格式化代码 => option + command + L
补全语句 => Shift + command + return
生成构造器,getter和setter方法等 => control + return
行注释 => control + /
块注释 => control + shift + c
*/
string x, y;
int c[11][11];//使用一个二维数组c[m+1][n+1]存储算法产生的各子问题的最优值
string b[11][11];//使用另一个二维数组b[m+1][n+1]存储算法产生的构造最优解所需的信息。
vector<char> res;
bool isMatch= false;
void check(int m,int n){
for (int i = 1 ; i < m; ++i) {
for (int j = 1; j < n; ++j) {
if (c[i][j]!=0) {
isMatch= true;
}
}
}
}
void printArrow(int m,int n){
std::cout << std::endl;
for (int i=1;i<m;++i){
for (int j=1;j<n;++j){
std::cout << b[i][j];
}
std::cout << std::endl;
}
}
void printC(int m,int n){
std::cout << std::endl;
for (int i=1;i<m;++i){
for (int j=1;j<n;++j){
std::cout << c[i][j];
}
std::cout << std::endl;
}
}
void LCSLength(int m, int n)
{
int i, j;
for (i = 0; i <= m; ++i)
{
c[i][0] = 0;
}
for (j = 0; j <= n; ++j)
{
c[0][j] = 0;
}
for (i = 1; i < m; ++i)
{
for (j = 1; j < n; ++j)
{
if (x.at(i) == y.at(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] = "←";
}
}
}
}
void LCS(int i, int j)
{
if (i == 0 || j == 0) {
return;
}
if (b[i][j] == "↖") {
LCS(i - 1, j - 1);
std::cout << x[i];
res.push_back(x[i]);
}
else if (b[i][j] == "↑")
{
LCS(i - 1, j);
}
else
{
LCS(i, j - 1);
}
}
void solution() {
int T, m, n;
std::cout << "请输入T,代表了运行程序T次,接下来输入2个字符串" << std::endl;
std::cin >> T;
for (int i = 0; i < T; ++i) {
std::cout << "请输入2个字符串" << std::endl;
std::cin >> x;
std::cin >> y;
x.insert(x.begin(),'!');//使得遍历 的时候从下标1开始,【1】到后面才存储输入的字符
y.insert(y.begin(),'!');//使得遍历 的时候从下标1开始
m = x.size();
n = y.size();
LCSLength(m,n);
printArrow(m,n);
printC(m,n);
check(m,n);
if (isMatch) {
LCS(m - 1, n - 1);
std::cout << "\n" << std::endl;
std::cout << "最大公共字段序列长度 = " << res.size() << std::endl;
res.clear();
}
else {
std::cerr << "No Match!!" << std::endl;
}
std::cout << std::endl;
}
}
int main() {
solution();
return 0;
}
算法复杂性分析
(1)时间复杂性分析
计算代价的时间:i, j 两层循环,i 循环 m 步,j 循环 n 步。
由于每个数组单元的计算耗费 O(1) 时间,算法 LCSLength 耗时 O(mn)。
构造最优解的时间:
算法 LCS 中,每一次递归调用使 i 或 j 减 1,因此算法的计算时间为 O(m+n)。
∴T(n)= O(mn)。
(2)空间复杂性
使用了二维数组 b 和 c,
∴S(n)= O(mn)。
具体分析以后更新: