数字三角形 动态规划

数字三角形 动态规划

/*
 用opt[][]来记录已经产生的最优解
 来解决对某些最优解进行重复求解的问题 
 */
#define LOCAL
#include<iostream>
using namespace std;
#define N 100
int a[N][N], opt[N][N];
int sum(int i, int j, int n)
{
	if (opt[i][j])
		return opt[i][j] + a[i][j];
	else
	{
		if (i == n - 1)
			return a[i][j];
		if ((opt[i][j] = sum(i + 1, j, n)) > (opt[i][j] = sum(i + 1, j + 1, n)))
			return opt[i][j] + a[i][j];
		else
			return opt[i][j] + a[i][j];
	}
}
int main()
{
#ifdef LOCAL
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	int i, j, n;
	while (cin >> n)
	{
		memset(opt, 0, sizeof(opt));
		for (i = 0; i < n; i++)
			for (j = 0; j <= i; j++)
				cin >> a[i][j];
		cout << sum(0, 0, n) << endl;
	}
	return 0;
}

发表回复