6. Counting towers (dynamic programming)

【Problem Description】

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

9

12

15

10

6

8

2

18

9

5

19

7

10

4

16

【Input form】

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

【Output format】

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

【Sample input】

5
9
12 15
10 6 8
2 18 9 5
19 7 10 4 16

【Sample output】

59
9 12 10 18 10
#include<bits/stdc++.h>
using namespace std;
int main() {
	int n;
	cin>>n;
	int a[n][n];
	int b[n][n];
	int increase[n][n];//用来记录路途增量
	memset(increase,0,sizeof(increase));//增量全部初始化为0
	int key=1;
	for(int i=0; i<n; i++) {//按规律进行输入
		for(int j=0; j<key; j++) {
			cin>>a[i][j];
			b[i][j]=a[i][j];
		}
		key++;
	}
	//如果直接求最长路径而不求具体路线时,直接动态规划
	//a[i][j]表示当走到第i行j列时,所用的最长路径
	//思路是:从倒数第二行开始,从下往上讨论
	//又因为此时要求具体路径,所以这里用增量(increase)进行路径的标记

	for(int i=n-2; i>=0; i--) {
		for(int j=0; j<n; j++) {

			if(a[i+1][j]<a[i+1][j+1]) { //右下大于左下
				increase[i][j]=1;
			}
			a[i][j]=max(a[i+1][j],a[i+1][j+1])+a[i][j];
		}
	}
	cout<<a[0][0]<<endl;
	int j=0;
	for(int i=0; i<n; i++) {
		cout<<b[i][j]<<' ';
		j+=increase[i][j];
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/longzaizai_/article/details/120302944