difficulty:
Traverse from bottom to top to find the largest. The larger one of two adjacent numbers is selected and accumulated to the upper layer.
Description:
Consider the digital pyramid shown below. Write a program to calculate the maximum sum of numbers that a path starts from the highest point and ends anywhere at the bottom. Each step can go to the lower left point or the lower right point. 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 In the example above, the path from 7 to 3 to 8 to 7 to 5 yields the maximum sum: 30
Input:
The first line enters the number of test data groups T; Next, each group of test data: The first line contains R(1<= R<=1000), which represents the number of lines. Each subsequent row contains the integer that a particular row of this number pyramid contains.
Output:
Output the maximum value for each set of data
Sample Input:
1
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample Output:
30
#include<iostream>
#include "vector"
using namespace std;
/**
* kkmd66
* @return
*/
int main() {
int t;
cin >> t;
//t个案例
for (int i = 0; i < t; i++) {
int r;
cin >> r;
//收集
vector<vector<int>> matrix(r);
for (int j = 0; j < r; j++) {
for (int k = 0; k < j + 1; k++) {
int temp;
cin >> temp;
matrix[j].push_back(temp);
}
}
//累加找最大
for (int j = r - 1; j > 0; j--) {
for (int k = 0; k < j; k++) {
matrix[j][k] > matrix[j][k + 1] ? matrix[j - 1][k] += matrix[j][k] : matrix[j - 1][k] += matrix[j][k +
1];
}
}
//输出
cout << matrix[0][0] << endl;
}
return 0;
}