七:动态规划-数字三角形

问题: 数字三角形  
问题描述

  (图3.1-1)示出了一个数字三角形。 请编一个程序计算从顶至底的某处的一条路
  径,使该路径所经过的数字的总和最大。
  ●每一步可沿左斜线向下或右斜线向下走;
  ●1<三角形行数≤100;
  ●三角形中的数字为整数0,1,…99;

  (图3.1-1)
输入格式
  文件中首先读到的是三角形的行数。
  接下来描述整个三角形
输出格式
  最大总和(整数)
样例输入
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
样例输出

30

方法一:

 1 #include<stdio.h>
 2 #include<string.h>
 3 int a[150][150];
 4 int fun(int b[][150],int n,int i,int j){
 5     if(i==n-1) return b[i][j];
 6     if(a[i][j]>=0)return a[i][j];    
 7         if(    b[i][j]+fun(b,n,i+1,j)>b[i][j]+fun(b,n,i+1,j+1))
 8         return a[i][j]=b[i][j]+fun(b,n,i+1,j);
 9         else return a[i][j]=b[i][j]+fun(b,n,i+1,j+1); 
10 
11 }
12 int main(){
13     //freopen("in.txt","r",stdin);
14     //freopen("out.txt","w",stdout);
15     memset(a,-1,sizeof(a));
16     int n;
17     int b[150][150];
18      int i,j; 
19     scanf("%d",&n);
20     for(i=0;i<n;i++)
21         for(j=0;j<i+1;j++)
22             scanf("%d",&b[i][j]);
23         printf("%d",fun(b,n,0,0));
24         return 0;
25 }

方法二:

 1 #include<stdio.h>
 2 #include<string.h>
 3 int fun(int b[][150],int n,int m,int j,int a[][150]){
 4     if(m==n)return a[m][j];
 5     if(b[m][j]>0)return b[m][j];
 6     int i;
 7     int x;
 8     int s;
 9         x=fun(b,n,m+1,j,a)+a[m][j];
10         s=fun(b,n,m+1,j+1,a)+a[m][j];
11         b[m][j]=x>s?x:s;
12         return b[m][j];
13 }
14 int main(){
15     int n;
16     int b[150][150];
17     int a[150][150];
18     memset(b,0,sizeof(b));
19     scanf("%d",&n);
20     for(int i=0;i<n;i++){
21         for(int j=0;j<=i;j++)
22         scanf("%d",&a[i][j]);
23     }
24     printf("%d",fun(b,n,0,0,a));
25     return 0;
26 }
原文地址:https://www.cnblogs.com/yuming226/p/8146103.html