HDU 2084 数塔 --- 入门DP
从下往上递推,状态转移方程 dp[i][j] = max( dp[i+1][j], dp[i+1][j+1]) + a[i][j];
/* HDU 2084 数塔 --- 入门DP */ #include <cstdio> const int N = 105; int dp[N][N]; int MAX(int a, int b){ return a > b ? a : b; } int main() { #ifdef _LOCAL freopen("D:\\input.txt", "r", stdin); #endif int t; scanf("%d", &t); while (t--){ int n; scanf("%d", &n); for (int i = 1; i <= n; ++i){ for (int j = 1; j <= i; ++j){ scanf("%d", &dp[i][j]); } } ////dp[i][j]记录从底部往上走到i,j的最大路径,最终结果和即dp[1][1]即为最长的路径 //for (int i = 1; i <= n; ++i){ // //最后一行的dp初始化为a[i][j]本身的值; // dp[n][i] = a[n][i]; //} //状态转移方程: dp[i][j] = max(d[i+1][j] + dp[i+1][j+1]) + a[i][j] //即到达下一行的两个邻接点的最大值加上该点的值即为该点的最大值. for (int i = n - 1; i > 0; --i){ //第i行有i个数,从下往上走, for (int j = 1; j <= i; ++j){ dp[i][j] = MAX(dp[i + 1][j], dp[i + 1][j + 1]) + dp[i][j]; //直接使用dp[i][j]可以省去一个数组的值 //dp[i][j] = MAX(dp[i + 1][j], dp[i + 1][j + 1]) + a[i][j]; } } //从下往上递推可以省去最后一循环找最大值而直接去dp[1][1] printf("%d\n", dp[1][1]); } return 0; }