P1216 [USACO1.5][IOI1994] Number Triangles (Luogu)

Original title portal

Insert picture description here
Insert picture description here
Idea: Dynamic programming seeks the optimal solution, this problem is easier to use the reverse solution method. First define a variable and an array to store the number of rows and the number of input rows, and then select an optimal solution for each element in each row from bottom to top starting from the penultimate row of the array (from the bottom left And choose the larger one in the lower right), and then add to the current element, and so on, and finally output the top element

Code reference

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1001;
int r,a[MAXN][MAXN];  //r为行数,数组存储每行的数
int main()
{
    
    
	cin>>r;
	//给数组赋值
	for(int i = 0;i < r;i++)
        for(int j = 0;j <= i;j++)
            cin>>a[i][j];
    //从倒数第二行开始从下往上寻找每个最优解
	for(int i = r-2;i >= 0;i--)
 		for(int j = 0;j <= i;j++)
            a[i][j]+=max(a[i+1][j],a[i+1][j+1]); //将左下方和右下方中较大的一个加到当前元素
    cout<<a[0][0]<<endl;
    return 0;
 }

Guess you like

Origin blog.csdn.net/Bertil/article/details/106818751