首页 > 代码库 > hoj_10014_二维DP

hoj_10014_二维DP

The Triangle
Time Limit: 1000ms, Special Time Limit:2000ms, Memory Limit:32768KB
Total submit users: 952, Accepted users: 860
Problem 10014 : No special judgement
Problem 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 T, the number of test cases, for each test case: the first line contain a 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 for each test case one line.

Sample Input
1

5
7
3 8
8 1 0 
2 7 4 4
4 5 2 6 5
Sample Output
30

 

  这道题是一个简单的二维DP,核心 dp[i][j] = max(dp[i-1][j-1], dp[i-1][j]) + value[i][j];

  AC代码如下:

 1 #include<cstdio>
 2 using namespace std;
 3 int main()
 4 {
 5     int ans;
 6     int n,m;
 7     int a[100][100];
 8     int b[100][100];
 9     scanf("%d",&n);
10     while(n--)
11     {
12         scanf("%d",&m);
13         for(int i=0;i<m;i++)
14             for(int j=0;j<=i;j++)
15                 scanf("%d",&a[i][j]);
16         b[0][0]=a[0][0];
17         for(int i=1;i<m;i++)
18         {
19             b[i][0]=a[i][0]+b[i-1][0];
20             b[i][i]=a[i][i]+b[i-1][i-1];
21             for(int j=1;j<i;j++)
22             {
23                 if(b[i-1][j-1]>b[i-1][j])
24                     b[i][j]=a[i][j]+b[i-1][j-1];
25                 else
26                     b[i][j]=a[i][j]+b[i-1][j];
27             }
28         }
29         ans=b[m-1][0];
30         for(int i=0;i<m;i++)
31         {
32             if(b[m-1][i]>ans)
33                 ans=b[m-1][i];
34         }
35         printf("%d\n",ans);
36     }
37     return 0;
38 }