几天前学了动态规划,做了下题。数塔是动态规划入门的一个基本问题,题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2084
代码如下:
#include <stdio.h>
int a[10005][10005],f[10005][10005];
int n;
int max(int x,int y)
{
return x < y ? y : x;
}
int main()
{
int i, j, n, m;
scanf("%d",&m);
while( m-- )
{
while( scanf("%d",&n) == 1 )
{
for( i = 1; i <= n; i++ )
for( j = 1; j <= i; j++ )
scanf("%d",&a[i][j]);
for( j = 1; j <= n; j++ )
f[n][j] = a[n][j]; //为最后一行赋值
for( i = n-1; i >= 1; i-- ) //从底部开始
for( j = 1; j <= i; j++ )
f[i][j] = a[i][j] + max(f[i+1][j],f[i+1][j+1]);
printf("%d\n",f[1][1]);
}
}
return 0;
}