POJ 3176-Cow Bowling/POJ 1163-The Triangle(简单DP-数塔)

冷不防 2022-07-12 13:28 234阅读 0赞

Cow Bowling














Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18487   Accepted: 12308

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:

  1. 7
  2. 3 8
  3. 8 1 0
  4. 2 7 4 4
  5. 4 5 2 6 5

Then 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.

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.

Output

Line 1: The largest sum achievable using the traversal rules

Sample Input

  1. 5
  2. 7
  3. 3 8
  4. 8 1 0
  5. 2 7 4 4
  6. 4 5 2 6 5

Sample Output

  1. 30

Hint

Explanation of the sample:

  1. 7
  2. *
  3. 3 8
  4. *
  5. 8 1 0
  6. *
  7. 2 7 4 4
  8. *
  9. 4 5 2 6 5

The highest score is achievable by traversing the cows as shown above.

Source

USACO 2005 December Bronze

题目意思:

N行的数塔,从最上面一行的一个数开始,每次只能选择其下一行的左右对称两个数的其中一个,将数相加,计算走到最后一行的最大和。

解题思路:

简单DP,方程是dp[i][j]=a[i][j]+max(dp[i+1][j],dp[i+1][j+1]);从最后一行向上计算。

  1. #include<iostream>
  2. #include<cstdio>
  3. #include<iomanip>
  4. #include<cmath>
  5. #include<cstdlib>
  6. #include<cstring>
  7. #include<map>
  8. #include<algorithm>
  9. #include<vector>
  10. #include<queue>
  11. using namespace std;
  12. #define INF 0x3f3f3f3f
  13. #define MAXN 400
  14. int a[MAXN][MAXN],dp[MAXN][MAXN];//dp[i][j]表示第i行 第j列上的最大值
  15. int main()
  16. {
  17. #ifdef ONLINE_JUDGE
  18. #else
  19. freopen("F:/cb/read.txt","r",stdin);
  20. //freopen("F:/cb/out.txt","w",stdout);
  21. #endif
  22. ios::sync_with_stdio(false);
  23. cin.tie(0);
  24. int n;
  25. while(cin>>n)
  26. {
  27. for(int i=0; i<n; ++i)
  28. for(int j=0; j<=i; ++j)
  29. cin>>a[i][j];//输入
  30. memset(dp,0,sizeof(dp));//初始化
  31. for(int i=0; i<n; ++i)
  32. for(int j=0; j<=i; ++j)
  33. dp[i][j]=a[i][j]+max(dp[i+1][j],dp[i+1][j+1]);//复制a数组到dp
  34. for(int i=n-1; i>=0; --i)//从最后一行向上计算
  35. for(int j=0; j<=i; ++j)
  36. dp[i][j]=a[i][j]+max(dp[i+1][j],dp[i+1][j+1]);
  37. /*for(int i=0; i<n; ++i)
  38. {
  39. for(int j=0; j<=i; ++j)
  40. cout<<dp[i][j]<<" ";
  41. cout<<endl;
  42. }*/
  43. cout<<dp[0][0]<<endl;
  44. }
  45. return 0;
  46. }
  47. /*
  48. 5
  49. 7
  50. 3 8
  51. 8 1 0
  52. 2 7 4 4
  53. 4 5 2 6 5
  54. */

发表评论

表情:
评论列表 (有 0 条评论,234人围观)

还没有评论,来说两句吧...

相关阅读

    相关 DP 数字三角形(POJ1163)

    7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 在上面的数字三角形中寻找一条从顶部到底边的路径,使得路径上所经过的数字之和最大。 路径上的每一步都只能往