Better understand the greedy algorithm + dynamic programming of the number of tower problems

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.