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.

Outputios

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:(自頂向下)ide

  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 } 
數字三角形
相關文章
相關標籤/搜索