题解 | #The Triangle#

原题链接

Description

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.

    从上往下递推,边界位置补0

#include<iostream>
#include<cstring>
using namespace std;
 const int maxn=110;
 int s[maxn][maxn];
 int dp[maxn][maxn];
int main(){
  int h;
  while(scanf("%d",&h)!=EOF){
      for(int i=1;i<=h;i++){//从(1,1)开始存放,第一行和第一列留作边界
        for(int j=1;j<=i;j++){
          scanf("%d",&s[i][j]);
        }
      }
        memset(dp,0,sizeof(dp));//初始化

        for(int i=1;i<=h;i++){//从上往下递推
          for(int j=1;j<=i;j++){
            dp[i][j]=s[i][j]+max(dp[i-1][j-1],dp[i-1][j]);
          }
        }

        int ans=0;
        for(int j=1;j<=h;j++){
            ans=max(ans,dp[h][j]);
          }
        printf("%d\n",ans);
  }     
  return 0;
}

从下往上递推 更简洁

#include<iostream>
using namespace std;

 const int maxn=110;
 int s[maxn][maxn];
 int dp[maxn][maxn];
 
int main(){
  int h;
  while(scanf("%d",&h)!=EOF){
      for(int i=0;i<h;i++){
        for(int j=0;j<=i;j++){
          scanf("%d",&s[i][j]);
          dp[i][j]=s[i][j];//初始化
        }
      }

        for(int i=h-2;i>=0;i--){//从倒数第二行开始
          for(int j=0;j<=i;j++){
            dp[i][j]=dp[i][j]+max(dp[i+1][j],dp[i+1][j+1]);
          }
        }
        
        printf("%d\n",dp[0][0]);
  }     
  return 0;
}

algorithm 文章被收录于专栏

外源题解补充

全部评论
努力学习ing
点赞
送花
回复
分享
发布于 2023-02-13 10:54 黑龙江
学到老活到老
点赞
送花
回复
分享
发布于 2023-02-13 11:21 陕西
滴滴
校招火热招聘中
官网直投

相关推荐

安徽省移动公司 IT部门 一年税前14w
点赞 评论 收藏
转发
5 收藏 评论
分享
牛客网
牛客企业服务