标签:style blog color os 使用 io strong ar for
Let‘s consider a triangle of numbers in which a number appears in the first line, two numbers appear in the second line, three in the third line, etc. Develop a program which will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that:
In the first line integer n - the number of test cases (equal to about 1000).
Then n test cases follow. Each test case starts with the number of lines which is followed by their content.
For each test case write the determined value in a separate line.
Input: 2 3 1 2 1 1 2 3 4 1 1 2 4 1 2 2 3 1 1 Output: 5 9
使用动态规划法解决本题。
和一题leetcode题一样,从底往上查找路径。
#include <vector> #include <string> #include <algorithm> #include <stdio.h> #include <iostream> using namespace std; int triPath(vector<vector<int> > &tri) { if (tri.empty()) return 0; vector<int> path(tri.back()); for (int i = (int)tri.size() - 2; i >= 0 ; i--)//unsigned做减法会溢出!!! { for (int j = 0; j < (int)tri[i].size(); j++) { path[j] = max(path[j], path[j+1]) + tri[i][j]; } } return path.front(); } int SumsinATriangle() { int T, n; scanf("%d", &T); while (T--) { scanf("%d", &n); vector<vector<int> > tri; for (int i = 1; i <= n; i++) { vector<int> tmp(i); for (int j = 0; j < i; j++) { scanf("%d", &tmp[j]); } tri.push_back(tmp); } printf("%d\n", triPath(tri)); } return 0; }
标签:style blog color os 使用 io strong ar for
原文地址:http://www.cnblogs.com/mengfanrong/p/3941292.html