codechef Sums in a Triangle题解
来源:互联网 发布:网上值机软件 编辑:程序博客网 时间:2024/06/10 00:10
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:
- on each path the next number is located on the row below, more precisely either directly below or below and one place to the right;
- the number of rows is strictly positive, but less than 100
- all numbers are positive integers between O and 99.
Input
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.
Output
For each test case write the determined value in a separate line.
Example
Input:2312 11 2 34 1 1 2 4 1 22 3 1 1 Output:59
使用动态规划法解决本题。
和一题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;}
2 0
- codechef Sums in a Triangle题解
- Codechef Not a Triangle题解
- spoj453 Sums in a Triangle (tutorial) 动态规划
- Codechef A Simple Equation 题解
- codechef Holes in the text 题解
- codechef - Discrepancies in the Voters List 题解
- CodeChef ROBOTDAG Robots in a DAG
- calculate a point in triangle
- CodeChef A
- codechef Turbo Sort 题解
- codechef Ambiguous Permutations 题解
- codechef Prime Palindromes 题解
- Codechef Nuclear Reactors 题解
- codechef Cleaning Up 题解
- codechef Permutation Cycles 题解
- codechef Birthday Candles 题解
- codechef Cutting Recipes题解
- codechef Carvans 题解
- java常用正则表达式
- R文本情感分析(3)
- linux内存释放
- 开启Android程序时检测网络与GPS是否打开
- Java中IO流知识点总结
- codechef Sums in a Triangle题解
- codechef Turbo Sort 题解
- NYOJ 741 "数学家"ST
- QTTabBar v512 beta 5
- 大数据应用程序最佳选择:是SQL还是NoSQL
- SQL查找删除重复行
- 视频跟踪的研究
- Tab Controls 的使用
- 对int、iret和栈的深入理解