Cow Bowling(ACM三部曲一)

Cow Bowling
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K(Java/Other)
Total Submission(s) : 8 Accepted Submission(s) : 4
Problem Description
The cows don't use actual bowling balls when they go bowling. Theyeach take a number (in the range 0..99), though, and line up in astandard bowling-pin-like triangle like this:

7

3 8

8 1 0

2 7 4 4

4 5 2 6 5
Then the other cows traverse the triangle starting from its tip andmoving "down" to one of the two diagonally adjacent  until the "bottom" row is reached. The cow'sscore is the sum of the numbers of the cows visited along the way.The cow with the highest score wins thatframe. 

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 thatrepresent 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


Source
PKU

     这个是一个很简单的动态规划题目。给出想样例的那样的找出一个和最大的路径。最大值的方法就是在最下面向上逆退,为了方便计算出最大值,可以将每个状态的最优解放入tree[i][j],所以状态转移方程为tree[i][j]=max{tree[i][j]+tree[i+1][j],tree[i][j]+tree[i+1][j+1]}(0<i<n-2,0<j<i)。最后最大值为tree[0][0],输出即可。

C++ source code:

#include<iostream>
using namespace std;

int main()
{
int tree[350][350],max,a,b,n,i,j;
while(cin>>n)
{
for(i=0;i<n;i++)
{
for(j=0;j<=i;j++)
cin>>tree[i][j];
}
for(i=n-2;i>=0;i--) //数字从底部开始相加
{
for(j=0;j<=i;j++)
{
a=tree[i][j]+tree[i+1][j];
b=tree[i][j]+tree[i+1][j+1];
a>b?tree[i][j]=a:tree[i][j]=b;
}
}
 cout<<tree[0][0]<<endl;//此时tree[0][0]就是我们所要求的最大值。
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值