1. 程式人生 > >poj1163 - DP遞推、遞歸寫法

poj1163 - DP遞推、遞歸寫法

end calculate base main blog can idt integer field

本題超鏈接:http://poj.org/problem?id=1163 The Triangle
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 50977 Accepted: 30888

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

IOI 1994 DP的遞推寫法
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cmath>
 4 #include <iostream>
 5 using namespace
std; 6 7 int dp[105][105]; 8 int f[105][105]; 9 10 int func(int n) 11 { 12 for(int i=n-1;i>=1;i--) 13 { 14 for(int j=1;j<=i;j++) 15 { 16 dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+f[i][j]; 17 } 18 } 19 return dp[1][1]; 20 } 21 int main() 22 { 23 int n; 24 while(~scanf("%d",&n)) 25 { 26 for(int i=1;i<=n;i++) 27 { 28 for(int j=1;j<=i;j++) 29 { 30 scanf("%d",&f[i][j]); 31 } 32 } 33 for(int i=1;i<=n;i++) dp[n][i]=f[n][i]; 34 printf("%d\n",func(n)); 35 } 36 37 return 0; 38 }


DP的遞歸寫法

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cmath>
 4 #include <iostream>
 5 using namespace std;
 6 
 7 int dp[105][105];
 8 int f[105][105];
 9 int n;
10 
11 int func(int i,int j)
12 {
13     if(i==n) return dp[i][j]=f[i][j];
14     if(dp[i][j]!=-1) return dp[i][j];
15     return dp[i][j]=max(func(i+1,j),func(i+1,j+1))+f[i][j];
16         
17 }
18 int main()
19 {
20     
21     while(~scanf("%d",&n))
22     {
23         memset(dp,-1,sizeof(dp));
24         for(int i=1;i<=n;i++)
25         {
26             for(int j=1;j<=i;j++)
27             {
28                 scanf("%d",&f[i][j]);
29             }
30         }
31         
32         printf("%d\n",func(1,1));
33     }
34     
35     return 0;
36 }
 

poj1163 - DP遞推、遞歸寫法