[Basics of Dynamic Programming] Digital Triangle (IOI1994)

topic description

number triangle
insert image description here

Input and output samples

Input example #1:

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

Sample output #1:

30

Ideas:

This question may be seen at first glance- directly greedy and then judge layer by layer ! ! ! But it will soon be discovered that the amount ___ seems not to work. Because maybe the current selection is a big one, but all the back ones are small ones! ! !
So at this time we need to use dynamic programming. For
details on the basics of dynamic programming, see: Dynamic Programming Basics (Super Detailed)

We can't work this question from top to bottom, so we have to think about operating from bottom to top

First of all, you need to know the state transition equation:
From the figure, it can be seen that the current value can be the maximum value of the number in the lower left corner and the number in the lower right corner plus your original number
, so the state transition equation is:

dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+a[i][j];

Then we need to know the initial value of DP , then this question is obvious, it is the last line of input, that is:

for(int i=1;i<=n;i++) dp[n][i]=a[n][i];

AC code

Finally, the complete code is presented:

#include<bits/stdc++.h>
using namespace std;
int n,a[101][101],dp[101][101];
int main(){
    
    
	cin>>n;
	for(int i=1;i<=n;i++)
	   for(int j=1;j<=i;j++) cin>>a[i][j];
	for(int i=1;i<=n;i++) dp[n][i]=a[n][i];
	for(int i=n-1;i>=1;i--){
    
    
		for(int j=1;j<=i;j++){
    
    
			dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+a[i][j];
		}
	}
	cout<<dp[1][1];
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_61360607/article/details/132276617