zoukankan      html  css  js  c++  java
  • nyoj 18-The Triangle(动态规划)

    18-The Triangle


    内存限制:64MB 时间限制:1000ms Special Judge: No
    accepted:5 submit:5

    题目描述:

    7
    3 8
    8 1 0
    2 7 4 4
    4 5 2 6 5
    (Figure 1)
    Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.

    输入描述:

    Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.

    输出描述:

    Your program is to write to standard output. The highest sum is written as an integer.

    样例输入:

    5
    7
    3 8
    8 1 0 
    2 7 4 4
    4 5 2 6 5
    

    样例输出:

    30

    分析:
      ①、因为肯定包含第一个数A[1][1],所以为了便于理解,我们不妨从下往上思考
      ②、及就是第n-1我们就确定出对应的n-1个的最大值情况
      ③、状态方程:A[i][j] += max(A[i+1][j], A[i+1][j+1])
    步骤:
      ①、从倒数第二层向上依次遍历
      ②、每一层根据状态方程算出该层每一个值对应向下可以得到的最大值
      ③、A[1][1]即为所求

    核心代码:
      
    1 for(int i = n-1; i>=1; -- i)
    2     for(int j = 1; j <= i; ++ j)
    3         A[i][j] += max(A[i+1][j], A[i+1][j+1]);
    4 printf("%d
    ", A[1][1]);

    C/C++代码实现(AC):

     1 #include <iostream>
     2 #include <algorithm>
     3 #include <cmath>
     4 #include <cstring>
     5 #include <cstdio>
     6 #include <queue>
     7 #include <set>
     8 #include <map>
     9 #include <stack>
    10 
    11 using namespace std;
    12 const int MAXN = 110;
    13 int A[MAXN][MAXN];
    14 
    15 int main ()
    16 {
    17     int n;
    18     scanf("%d", &n);
    19     for(int i = 1; i <= n; ++ i)
    20         for (int j = 1; j <= i; ++ j)
    21             scanf("%d", &A[i][j]);
    22 
    23     for(int i = n-1; i >= 1; -- i)
    24     {
    25         for (int j = 1; j <= i; ++ j)
    26         {
    27             A[i][j] = max(A[i + 1][j], A[i + 1][j + 1]) + A[i][j];
    28         }
    29     }
    30     printf("%d
    ", A[1][1]);
    31     return 0;
    32 }
    
    
  • 相关阅读:
    使用Ambari快速部署Hadoop大数据环境
    Hadoop,HBase,Storm,Spark到底是什么?
    Google服务器架构图解简析
    百度的Hadoop分布式大数据系统图解:4000节点集群
    为Hadoop集群选择合适的硬件配置
    Hadoop组件Hive配置文件配置项详解
    腾讯TDW:大型Hadoop集群应用
    Hadoop组件Hbase配置项详解
    主流大数据采集平台的架构图解
    大数据架构师技能图谱
  • 原文地址:https://www.cnblogs.com/GetcharZp/p/9052007.html
Copyright © 2011-2022 走看看