题解 | #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 文章被收录于专栏
外源题解补充