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:
7 3 8 8 1 0 2 7 4 4 4 5 2 6 5Then 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 5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 Sample Output 30 Hint
Explanation of the sample:
7 * 3 8 * 8 1 0 * 2 7 4 4 * 4 5 2 6 5The highest score is achievable by traversing the cows as shown above. Source |
提示
题意:
经典的数字三角形问题,计算出从三角形的顶至底的一条路径,使该路径经过的数字总和最大。
思路:
DP入门。
从上到下的递推式:dp[i][i1]=MAX(dp[i][i1]+dp[i-1][i1-1],dp[i][i1]+dp[i-1][i1])(要注意三角形边界)
从下到上的递推式:类似,留给读者思考。(这种方式不需要去考虑三角形边界,并且直接做输出)
这是我唯一自己完全想出来的DP题。。。。。。(以前就做过)
示例程序
从上到下的做法:Source Code
Problem: 3176 Code Length: 870B
Memory: 804K Time: 63MS
Language: GCC Result: Accepted
#include <stdio.h>
int main()
{
int n,i,i1,a[350][350],max=0;
scanf("%d",&n);
for(i=0;n>i;i++)
{
for(i1=0;i>=i1;i1++)
{
scanf("%d",&a[i][i1]);
}
}
for(i=1;n>i;i++)
{
a[i][0]=a[i][0]+a[i-1][0]; //最左边的情况
for(i1=1;i>i1;i1++)
{
if(a[i][i1]+a[i-1][i1-1]>=a[i][i1]+a[i-1][i1])
{
a[i][i1]=a[i][i1]+a[i-1][i1-1];
}
else
{
a[i][i1]=a[i][i1]+a[i-1][i1];
}
}
a[i][i]=a[i][i]+a[i-1][i-1]; //最右边的情况
}
for(i=0;n>i;i++) //需要去寻找最大值
{
if(max<a[n-1][i])
{
max=a[n-1][i];
}
}
printf("%d",max);
return 0;
}
从下到上的做法:
Source Code
Problem: 3176 Code Length: 556B
Memory: 804K Time: 63MS
Language: GCC Result: Accepted
#include <stdio.h>
int main()
{
int n,i,i1,a[350][350],max=0;
scanf("%d",&n);
for(i=0;n>i;i++)
{
for(i1=0;i>=i1;i1++)
{
scanf("%d",&a[i][i1]);
}
}
for(i=n-2;i>=0;i--)
{
for(i1=0;i>=i1;i1++)
{
if(a[i][i1]+a[i+1][i1]>=a[i][i1]+a[i+1][i1+1])
{
a[i][i1]=a[i][i1]+a[i+1][i1];
}
else
{
a[i][i1]=a[i][i1]+a[i+1][i1+1];
}
}
}
printf("%d",a[0][0]); //直接输出
return 0;
}