算法导论--动态规划算法--求最长回文序列

///算法导论第15章,求最长回文序列
//采用自底向上的动态规划算法。
//
///此代码只是计算出最长回文的长度,并未输出最长回文序列


#include
#include


int c[100][100];
char b[100][100];
void hw(std::string s)
{
	
	int n = s.length();
	for (int i = 0; i <= n;i++)
	for (int j = 0; j <= n; j++)
		c[i][j] = 0;


	c[0][0] = 0;
	for (int i = 1; i <= n; i++)
		c[i][i] = 1;

	for (int l = 1; l <= n - 1;++l)
	for (int i = 1; i <= n - l;++i)
	{
		int j = i + l;
		if (s[i-1] == s[j-1])
		{

			c[i][j] = c[i + 1][j - 1] + 2;
			b[i][j] = s[i-1];

			std::cout << "s" << i<<"="<= c[i][j - 1])
			c[i][j] = c[i + 1][j];
		else
			c[i][j] = c[i][j - 1];
	}
	std::cout << "[n]=" << n<< std::endl;
	std::cout << "c[1,n]=" << c[1][n] << std::endl;

	
}

int main()
{
	std::string s;
	while(std::cin >> s)
	hw(s);
	return 0;
}

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