题目链接:http://lightoj.com/login_main.php?url=volume_showproblem.php?problem=1004
1004 - Monkey Banana Problem
Time Limit: 2 second(s) | Memory Limit: 32 MB |
You are in the world of mathematics to solve the great "Monkey Banana Problem". It states that, a monkey enters into a diamond shaped two dimensional array and can jump in any of the adjacent cells down from its current position (see figure). While moving from one cell to another, the monkey eats all the bananas kept in that cell. The monkey enters into the array from the upper part and goes out through the lower part. Find the maximum number of bananas the monkey can eat.
Input
Input starts with an integer T (≤ 50), denoting the number of test cases.
Every case starts with an integer N (1 ≤ N ≤ 100). It denotes that, there will be 2*N - 1 rows. The ith (1 ≤ i ≤ N) line of next N lines contains exactly i numbers. Then there will be N - 1 lines. The jth (1 ≤ j < N) line contains N - j integers. Each number is greater than zero and less than 215.
Output
For each case, print the case number and maximum number of bananas eaten by the monkey.
Sample Input | Output for Sample Input |
2 4 7 6 4 2 5 10 9 8 12 2 2 12 7 8 2 10 2 1 2 3 1 | Case 1: 63 Case 2: 5 |
Note
Dataset is huge, use faster I/O methods.
题意:
由一个正三角和一个倒三角组成,求最大和
因为是两个三角形,我们可以将状态方程分成两部分,从上取下或者从下取上都行
从上取下:1.dp[ i ][ j ]+=max( dp[ i-1 ][ j ] , dp[ i-1 ][ j-1 ] );
2.dp[ i ][ j ]+=max( dp[ i-1 ][ j ] , dp[ i-1 ][ j+1 ]);
从下取上:1.dp[ i ][ j ]+=max( dp[ i+1 ][ j ] , dp[ i+1 ][ j-1 ]);
2.dp[ i ][ j ]+=max( dp[ i+1 ][ j ] , dp[ i+1 ][ j+1 ]);
下面 dp 数组为 a 数组,同理(注意输出啊!!!被坑了5次不能用%I64d)
代码如下:
//从上取下
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
long long a[500][500];
int main()
{
int t,n,i,j,k=1;
scanf("%d",&t);
while(t--)
{
memset(a,0,sizeof(a));
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
scanf("%lld",&a[i][j]);
}
for (i=1;i<=n-1;i++)
{
for (j=1;j<=n-i;j++)
scanf("%lld",&a[n+i][j]);
}
for(i=2;i<=n;i++)
{
for(j=1;j<=i;j++)
a[i][j]+=max(a[i-1][j-1],a[i-1][j]);
}
for (i=1;i<=n-1;i++)
{
for (j=1;j<=n-i;j++)
a[n+i][j]+=max(a[n+i-1][j],a[n+i-1][j+1]);
}
printf("Case %d: %lld\n",k++,a[2*n-1][1]);
}
return 0;
}
//从下取上
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
#define LL long long
int main()
{
int t,i,j,n,k;
LL a[200][200];
scanf("%d",&t);
k=1;
while(t--)
{
memset(a,0,sizeof(a));
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<=i;j++)
scanf("%d",&a[i][j]);
}
for(;i<2*n-1;i++)
{
for(j=0;j<=2*n-i-2;j++)
scanf("%d",&a[i][j]);
}
for(i=2*n-3;i>=n-1;i--)
for(j=0;j<=2*n-i-2;j++)
a[i][j]+=max(a[i+1][j-1],a[i+1][j]);
for(i=n-2;i>=0;i--)
for(j=0;j<=i;j++)
a[i][j]+=max(a[i+1][j],a[i+1][j+1]);
printf("Case %d: %lld\n",k++,a[0][0]);
}
return 0;
}