A HDU_2048 数塔

dp入门题——数塔问题;求路径的最大和;

状态方程:

dp[i][j] = max(dp[i+1][j], dp[i+1][j+1])+a[i][j];
dp[n][j] = a[n][j];

其中dp[i][j]: 深度为i的第j个结点的最大和;

 1 /*
 2 Problem: HDU-2048
 3 Tips: Easy DP
 4 dp[i][j]: 深度为i的第j个结点的最大和;
 5 dp[i][j] = max(dp[i+1][j], dp[i+1][j+1])+a[i][j];
 6 dp[n][j] = a[n][j];
 7 */
 8 #include<iostream>
 9 #include<cstdio>
10 #include<cstdlib>
11 #include<cstring>
12 #include<cmath>
13 #include<algorithm>
14 using namespace std;
15 typedef long long LL;
16 const int maxn = 110;
17 int a[maxn][maxn], dp[maxn][maxn];
18 int n;
19 void DP()
20 {
21     memset(dp, 0, sizeof(dp));
22     for(int j = 1; j <= n; j++) dp[n][j] = a[n][j];
23     for(int i = n-1; i >= 1; i--)
24     {
25         for(int j = 1; j <= i; j++)
26         {
27             dp[i][j]=max(dp[i+1][j], dp[i+1][j+1])+a[i][j];
28         }
29     }
30     printf("%d\n", dp[1][1]);
31 }
32 int main()
33 {
34     int T; scanf("%d", &T);
35     while(T--)
36     {
37         scanf("%d", &n);
38         for(int i = 1; i <= n; i++)
39             for(int j = 1; j <= i; j++)
40                 scanf("%d", &a[i][j]);
41         DP();
42     }
43 
44     return 0;
45 }
View Code

相关文章:

  • 2022-12-23
  • 2021-12-06
  • 2022-02-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
  • 2021-06-03
  • 2021-04-11
相关资源
相似解决方案