1#include <iostream>2#include <cmath>3 using namespacestd;4 Const intn= -;5 inttower[n][n],f[n][n]={0},n;6 voidUpmax (int&a,Const int&b) {7A= (a>b?a:b);8 }9 intMain () {TenCin>>N; One for(intI=1; i<=n;i++){ A for(intj=1; j<=i;j++){ -Cin>>Tower[i][j]; - } the } - //next, using greedy algorithms and dynamic programming - //The greedy algorithm is used here, each step calculates the maximum of each row, and finally gets the overall maximum - for(intI=1; i<=n;i++){ + for(intj=1; j<=i;j++){ -Upmax (F[i][j],max (f[i-1][j],f[i-1][j-1])+tower[i][j]); + } A } at intres=0; - for(intI=0; i<=n;i++){ - //cout<<f[n][i]<<endl; - Upmax (Res,f[n][i]); - } -cout<<res<<Endl; in}
1. Find the maximum function and return it to the first parameter, and of course pointers and references can be implemented
2. Greedy algorithm to find the maximum value of each row: For each position, you can find all the above path to reach the maximum value, there is f[i][j]
3. Compare the last line of F[n][i], to find out the maximum is the result
Better understand the greedy algorithm + dynamic programming of the number of tower problems