使用动态规划法求解最长公共子序列

#include
using namespace std;
const int NUM = 51;
int dp[NUM][NUM];
int b[NUM][NUM]; // 记录位置
void LCSLength(int m, int n, char x[], char y[])
{
	for (int i = 1; i <= m; ++i)                //将第一排第一列全部置零
	{
		dp[i][0] = 0;
	}
	for (int i = 1; i <= n; ++i)
	{
		dp[0][i] = 0;
	}
	for (int i = 1; i <= m; ++i)                    //代入动态规划法公式
	{
		for (int j = 1; j <= n; ++j)
		{
			if (x[i] == y[j])
			{
				dp[i][j] = dp[i - 1][j - 1] + 1;
				b[i][j] = 1;
			}
			else if (dp[i - 1][j] > dp[i][j - 1])
			{
				dp[i][j] = dp[i - 1][j];
				b[i][j] = 2;
			}
			else
			{
				dp[i][j] = dp[i][j - 1];
				b[i][j] = 3;
			}
		}
	}
}
void LCS(int i, int j, char x[])                      //记录位置
{
	if (i == 0 || j == 0)
		return;
	if (b[i][j] == 1)
	{
		LCS(i - 1, j - 1, x);
		cout << x[i] << " ";
	}
	else if (b[i][j] == 2)
		LCS(i - 1, j, x);
	else
		LCS(i, j - 1, x);
}
int main()
{
	int m, n;
	char x[NUM], y[NUM];
	cin >> m >> n;
	for (int i = 1; i <= m; ++i)       //初始化两个序列
	{
		cin >> x[i];
	}
	for (int i = 1; i <= n; ++i)           
	{
		cin >> y[i];
	}
	LCSLength(m, n, x, y);
	for (int i = 1; i <= m; ++i)
	{
		for (int j = 1; j <= n; ++j)
		{
			cout << dp[i][j] << " ";
		}
		cout << endl;
	}
	cout << "--------------------" << endl;
	for (int i = 1; i <= m; ++i)
	{
		for (int j = 1; j <= n; ++j)
		{
			cout << b[i][j] << " ";
		}
		cout << endl;
	}
	cout << "--------------------" << endl;
	LCS(m, n, x);
	return 0;
}

你可能感兴趣的:(C++算法设计)