POJ 1163 The Triangle

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

解题思路

  DP:(自顶向下)

  1.   状态表示f[i,j]:
    1. 集合:所有从起点走到(i,j)的路径
    2. 属性:所有路径上数字之和的最大值(Max)【属性一般为 Max,Min, 数量】
  2.   状态计算:  f[i,j] = a[i,j] + max(f[i - 1[j - 1],f[i - 1][j])
 1 #include<iostream>
 2 using namespace std;
 3 const int INF = 1e9;
 4 const int N = 110;
 5 int n;
 6 int f[N][N], a[N][N];
 7 void init(){
 8     
 9     for(int i = 0; i <= n; i++){
10         for(int j = 0; j <= i + 1; j++){
11             f[i][j] = -INF;
12         }
13     }
14     f[1][1] = a[1][1];
15 }
16 int main(){
17     cin >> n;
18     for(int i = 1; i <= n; i++){
19         for(int j = 1; j <= i; j++){
20             cin >> a[i][j];
21         }
22     }
23     init();
24     for(int i = 2; i <= n; i++){
25         for(int j = 1; j <= i; j++){
26             f[i][j] = a[i][j] + max(f[i - 1][j - 1], f[i - 1][j]);
27         }
28     }
29     int ans = -INF;
30     for(int i = 1; i <= n; i++){
31         ans = max(ans, f[n][i]);
32     }
33     cout << ans << endl;
34     return 0;
35 } 
数字三角形

 

posted @ 2019-07-15 10:34 zoom1109 阅读(...) 评论(...) 编辑 收藏