程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> codechef Sums in a Triangle題解

codechef Sums in a Triangle題解

編輯:C++入門知識

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:
    2
    3
    1
    2 1
    1 2 3
    4 
    1 
    1 2 
    4 1 2
    2 3 1 1 
    
    Output:
    5
    9

    使用動態規劃法解決本題。

    和一題leetcode題一樣,從底往上查找路徑。


    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    int triPath(vector > &tri)
    {
    	if (tri.empty()) return 0;
    	vector 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 > tri;
    		for (int i = 1; i <= n; i++)
    		{
    			vector tmp(i);
    			for (int j = 0; j < i; j++)
    			{
    				scanf("%d", &tmp[j]);
    			}
    			tri.push_back(tmp);
    		}
    		printf("%d\n", triPath(tri));
    	}
    	return 0;
    }




  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved