算法导论-第15章-动态规划:最长公共子序列(空间复杂度改进版)C++实现

#include 
#include 
#include 
using namespace std;

int LCS(char* A, char* B, int* C, int m, int n) {
	for (int i = 1; i <= m; ++i) {
		for (int j = 1; j <= n; ++j) {
			if (A[i] == B[j]) {
				C[i * (n + 1) + j] = C[(i - 1) * (n + 1) + j - 1] + 1;
			}
			else if(C[(i - 1) * (n + 1) + j] >= C[i * (n + 1) + j - 1]){
				C[i * (n + 1) + j] = C[(i - 1) * (n + 1) + j];
			}
			else{
				C[i * (n + 1) + j] = C[i * (n + 1) + j - 1];
			}
		}
	}
	return C[m * (n + 1) + n];
}

int main(int argc, char* argv[]) {
	vector v{};
	cout << "please input the first char list : " << endl;
	char element{};
	while (cin >> element) {
		if (element == '0') {
			break;
		}
		v.push_back(element);
	}
	int index{};
	size_t m{ v.size() };
	char* A = new char[m + 1] {};
	for_each(v.begin(), v.end(), [=](char x)mutable{A[++index] = x; });
	v.clear();
	cout << "please input the second char list : " << endl;
	while (cin >> element) {
		if (element == '0') {
			break;
		}
		v.push_back(element);
	}
	size_t n{ v.size() };
	char* B = new char[n + 1] {};
	index = 0;
	for_each(v.begin(), v.end(), [=](char x)mutable{B[++index] = x; });
	int* C = new int[(m + 1) * (n + 1)] {};
	int result = LCS(A, B, C, m, n);
	cout << "the reverse of LSC is : " << endl;
	size_t i{ m };
	size_t j{ n };
	while (i && j) {
		if (C[i * (n + 1) + j] == C[(i - 1) * (n + 1) + j]) {
			i--;
		}
		else if (C[i * (n + 1) + j] == C[i * (n + 1) + j - 1]) {
			j--;
		}
		else {
			cout << A[i] << " ";
			i--;
			j--;
		}
	}
	cout << endl;
	cout << "and the length is : " << result << endl;
	delete[]A;
	delete[]B;
	delete[]C;
	return 0;
}

你可能感兴趣的:(算法)