topic
Total time limit: 1000ms Memory Limit: 65536kB
description
Figure 1 shows a digital triangle. There are many different paths from the top to the bottom of the triangle. For each path, add up the numbers on the path to get a sum. Your task is to find the largest sum.
Note: Each step on the path can only go from one number to the nearest left or right number on the next level.
Input The
input line is an integer N (1 <N <= 100), which gives the number of triangle lines. The next N lines give the digital triangle. The numbers on the digital triangle range between 0 and 100.
Output
Maximum sum.
Sample input
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample output
30
Recursive method
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 100
int D[MAX_NUM+10] [MAX_NUM+10];
int N;//行数
int aMaxSum[MAX_NUM+10][MAX_NUM+10];
int MaxSum(int r,int j){
if(r==N){
//递归的出口
return D[r][j];
}
/*
*每次计算完做上标记,减少重复计算的次数
*aMaxSum用来存放计算后的结果,-1为没有走过的路径
*/
if(aMaxSum[r+1][j]==-1){
aMaxSum[r+1][j] = MaxSum(r+1,j);
}
if(aMaxSum[r+1][j+1]==-1){
aMaxSum[r+1][j+1] = MaxSum(r+1,j+1);
}
//判断哪条路径的值大就走那边
if(aMaxSum[r+1][j]>aMaxSum[r+1][j+1]){
return aMaxSum[r+1][j] + D[r][j];
}
return aMaxSum[r+1][j+1] + D[r][j];
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int m,i,j;
scanf("%d",&N);
memset(aMaxSum,-1,sizeof(aMaxSum));//将 aMaxSum全部置为-1,表示没用算过
for(i=1;i<=N;i++){
for(j=1;j<=i;j++){
scanf("%d",&D[i][j]);
}
}
printf("%d",MaxSum(1,1));
return 0;
}
Recursion
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 100
int D[MAX_NUM+10] [MAX_NUM+10];
int N;//行数
int aMaxSum[MAX_NUM+10][MAX_NUM+10];
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int m,i,j;
scanf("%d",&m);
for(i=1;i<=m;i++){
for(j=1;j<=i;j++){
scanf("%d",&D[i][j]);
}
}
for(i=1;i<=m;i++){
aMaxSum[m][i] = D[m][i];
}
for(i=m-1;i>=1;i--){
for(j=1;j<=i;j++){
int nSum1 = D[i][j]+aMaxSum[i+1][j];
int nSum2 = D[i][j]+aMaxSum[i+1][j+1];
if(nSum1>nSum2){
aMaxSum[i][j] = nSum1;
}else{
aMaxSum[i][j] = nSum2;
}
}
}
printf("%d",aMaxSum[1][1]);
return 0;
}