zoukankan      html  css  js  c++  java
  • The Triangle(DP基础)

    The Triangle
    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 31614   Accepted: 18667

    Description

    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.

    Input

    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.

    Output

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

    Sample Input

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

    Sample Output

    30

    Source

     
     1 #include <iostream>
     2 #include <cstdio>
     3 
     4 using namespace std;
     5 
     6 const int MAXN = 105;
     7 int N, sum[MAXN][MAXN];
     8 
     9 int Max(int x, int y) {return x > y ? x : y;}
    10 
    11 int main()
    12 {
    13     while(scanf("%d", &N) != EOF)
    14     {
    15         for(int i = 0; i < N; i++)
    16             for(int j = 0; j <= i; j++)
    17                 scanf("%d", &sum[i][j]);
    18         sum[1][0] += sum[0][0];
    19         sum[1][1] += sum[0][0];
    20         for(int i = 2; i < N; i++)
    21         {
    22             for(int j = 0; j <= i; j++)
    23             {
    24                 if(!j) sum[i][j] += sum[i-1][j];
    25                 else if(j == i) sum[i][j] += sum[i-1][j-1];
    26                 else sum[i][j] += Max(sum[i-1][j-1], sum[i-1][j]);
    27             }
    28         }
    29         int ans = sum[N-1][0];
    30         for(int i = 1; i < N; i++)
    31             if(ans < sum[N-1][i]) ans = sum[N-1][i];
    32          printf("%d\n", ans);
    33     }
    34     return 0;
    35 }
  • 相关阅读:
    在Spring Bean的生命周期中各方法的执行顺序
    java面试宝典
    js代码中实现页面跳转的几种方式
    APP测试学习:系统资源分析
    APP测试学习:webview性能分析
    APP测试学习:app启动性能分析
    App测试学习:自动遍历测试
    性能测试学习:jmeter通过代理录制、回放请求
    Docker学习五:如何搭建私有仓库
    Docker学习四:容器基本操作
  • 原文地址:https://www.cnblogs.com/cszlg/p/2911050.html
Copyright © 2011-2022 走看看