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 }
  • 相关阅读:
    code1135 选择客栈
    code3289 花匠
    code1167 树网的核
    线段树
    二分图 and code1170 双栈排序
    code1001 舒适的路线
    svg的自述
    a链接bug
    去除a标签链接触摸时产生边框
    前端资源收藏
  • 原文地址:https://www.cnblogs.com/cszlg/p/2911050.html
Copyright © 2011-2022 走看看