number tower problem

Topic description

 

Given a number tower, as shown in the figure below. In this tower, starting from the top, you can choose to go to the bottom left or bottom right at each node, all the way to the bottom. Please find a path that maximizes the numerical sum on the path.

       

9

       
     

12

 

15

     
   

10

 

6

 

8

   
 

2

 

18

 

9

 

5

 

19

 

7

 

10

 

4

 

16

enter

 

When inputting, there is an integer n in the first line , which represents the number of rows of the tower, and the remaining n lines represent the value of each row of the tower

output

 

The output contains two lines, the first line is the sum of the values ​​on the largest path, and the  second line n numbers are the maximum path values ​​from top to bottom

sample input

5912 1510 6 82 18 9 519 7 10 4 16

Sample output

599 12 10 18 10


dynamic programming

analyze:

The top-down analysis is really too violent. Assuming that there are 31 lines, there are 2^30 paths. It will be found that the sum of all values ​​on the path must be known from the top to the bottom, and then the comparison can be determined.

Another way of thinking is to compare from bottom to top; for example, in the last line of the above example, 19>7, so discarding 7, 2 becomes 2+19=21; similarly 7<10, 18 becomes 18+10=28 ...and so on

Reference http://blog.csdn.net/u012248410/article/details/12078991


#include<iostream>
using namespace std;


int main(){
   int a[20][20];
   int b[20][20];
   int n,c,k,m=0;
   cin>>n;
   for(int i=0;i<n;i++){
           for(int j=0;j<=i;j++){
                   cin>>a[i][j];
                   b[i][j]=a[i][j];
                   }
           }
  
   c=n-1;
   while(c>0){
              k=c;
                      for(int j=0;j<k;j++){
                              if(a[k][j]>a[k][j+1])
                                  a[k-1][j]=a[k-1][j]+a[k][j];
                              else
                                  a[k-1][j]=a[k-1][j]+a[k][j+1];
                              }
              c--;  
             
              }
  cout<<a[0][0];
  cout<<endl;
  cout<<b[0][0];
  
  for(int i=0;i<n-1;i++){
          int j=m;
          if(a[i][j]-b[i][j]==a[i+1][j]){
             cout<<" "<<b[i+1][j];
             m=j;
             }
          else{
             cout<<" "<<b[i+1][j+1];
             m=j+1;
             }
          }
    return 0;
    }


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325681855&siteId=291194637