Poj3176 Cow Bowling (动态规划 数字三角形)
Description
The cows don't use actual bowling balls when they go bowling. They each take a number (in the range 0..99), though, and line up in a standard bowling-pin-like triangle like this:
Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable.
7Then the other cows traverse the triangle starting from its tip and moving "down" to one of the two diagonally adjacent cows until the "bottom" row is reached. The cow's score is the sum of the numbers of the cows visited along the way. The cow with the highest score wins that frame.
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable.
Input
Line 1: A single integer, N
Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle.
Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle.
Output
Line 1: The largest sum achievable using the traversal rules
Sample Input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30
Hint
Explanation of the sample:
7The highest score is achievable by traversing the cows as shown above.
*
3 8
*
8 1 0
*
2 7 4 4
*
4 5 2 6 5
渐渐对动态规划有所感悟 加油!
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 int a[355][355]; 5 int n; 6 int dp[355][355]; 7 int main() 8 { 9 while(cin>>n){ 10 for(int i=0;i<n;i++){ 11 for(int j=0;j<=i;j++){ 12 cin>>a[i][j]; 13 } 14 } 15 int res=0; 16 dp[0][0]=a[0][0]; 17 for(int i=1;i<n;i++){ 18 for(int j=0;j<=i;j++){ 19 if(j==0) dp[i][j]=dp[i-1][j]+a[i][j];//第一列只有一个方向累加 20 else dp[i][j]=max(dp[i-1][j],dp[i-1][j-1])+a[i][j]; 21 res=max(res,dp[i][j]); 22 } 23 } 24 cout<<res<<endl; 25 } 26 return 0; 27 }
另一种写法:倒推,感觉更清晰一点
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 int n; 5 int a[105][105]; 6 int dp[105][105]; 7 int main() 8 { 9 while(cin>>n){ 10 for(int i=0;i<n;i++){ 11 for(int j=0;j<=i;j++){ 12 cin>>a[i][j]; 13 dp[i][j]=a[i][j]; 14 } 15 } 16 for(int i=n-2;i>=0;i--){ 17 for(int j=0;j<=i;j++){ 18 dp[i][j]+=max(dp[i+1][j+1],dp[i+1][j]); 19 } 20 } 21 cout<<dp[0][0]<<endl; 22 } 23 return 0; 24 }