http://poj.org/problem?id=1163
Description
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.
Input
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample Output
30
先用递归实现一下
#include <iostream>
using namespace std;
const int maxn = 110;
int a[maxn][maxn] = {0,};
int n;
int MaxSum(int i, int j);
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= i; j++)
cin >> a[i][j];
cout << MaxSum(1, 1);
return 0;
}
int MaxSum(int i, int j)
{
if(i == n)
return a[i][j];
int x = MaxSum(i + 1, j);
int y = MaxSum(i + 1, j + 1);
return max(x,y) + a[i][j];
}
o(2^n)
递归太慢,重复太多
再来,把重复的记住
记忆递归型动规程序
#include <iostream>
using namespace std;
const int maxn = 110;
int a[maxn][maxn] = {0,};
int maxsum[maxn][maxn] = {0,};
//记录,避免重复计算
int n;
int MaxSum(int i, int j);
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= i; j++){
cin >> a[i][j];
maxsum[i][j] = -1; //初始化
}
cout << MaxSum(1, 1);
return 0;
}
int MaxSum(int i, int j)
{
if(maxsum[i][j] != -1)
return maxsum[i][j];
if(i == n)
maxsum[i][j] = a[i][j];
else{
int x = MaxSum(i + 1, j);
int y = MaxSum(i + 1, j + 1);
maxsum[i][j] = max(x, y) + a[i][j];
}
return maxsum[i][j];
}
o(n^2)
我试了下,这样在POJ上就能过了
理解了上面的递归,那用递推来构建maxsum
#include <iostream>
using namespace std;
const int maxn = 110;
int a[maxn][maxn] = {0,};
int maxsum[maxn][maxn] = {0,};
int n;
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= i; j++)
cin >> a[i][j];
for(int i = n; i >= 1; i--)
for(int j = 1; j <= i; j++)
maxsum[i][j] = max(maxsum[i + 1][j], maxsum[i + 1][j + 1]) + a[i][j];
//这里有一点点越界风险,要把array开大一点,要初始化
cout << maxsum[1][1];
return 0;
}
接下来再省一点空间,maxsum我们用一维数组搞定
#include <iostream>
using namespace std;
const int maxn = 110;
int a[maxn][maxn] = {0,};
int maxsum[maxn] = {0,};
int n;
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= i; j++)
cin >> a[i][j];
for(int i = n; i >= 1; i--)
for(int j = 1; j <= i; j++)
maxsum[j] = max(maxsum[j], maxsum[j + 1]) + a[i][j];
cout << maxsum[1];
return 0;
}
参考资料:北大算法课
517