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 |
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <queue>
#include <stack>
#include <vector>
#include <map>
using namespace std;
typedef long long LL;
#define N 650
#define INF 0x3f3f3f3f
#define PI acos (-1.0)
#define EPS 1e-5
#define met(a, b) memset (a, b, sizeof (a))
int dp[N][N], val[N][N], n;
int DFS (int x, int y, int k)
{
if (dp[x][y] != -1) return dp[x][y];
if ((x==n+1 && !k) || (x==2*n && k)) dp[x][y] = val[x][y];
else if (!k)//当k是0的时候搜上半部分
dp[x][y] = val[x][y] + max (DFS (x-1, y, k), DFS (x-1, y-1, k));
else if (k)//当k是1的时候搜下半部分
dp[x][y] = val[x][y] + max (DFS (x-1, y, k), DFS (x-1, y+1, k));
return dp[x][y];
}
int main ()
{
int t, nCase = 1;
scanf ("%d", &t);
while (t--)
{
scanf ("%d", &n);
met (dp, -1);
met (val, 0);
for (int i=1; i<=n; i++)
for (int j=1; j<=i; j++)
scanf ("%d", &val[i][j]);
for (int i=n+1; i<2*n; i++)
for (int j=1; j<=2*n-i; j++)
scanf ("%d", &val[i][j]);//将第n行的从上边递推下来的值记录下来
for (int i=1; i<=n; i++)
val[n][i] = DFS (n, i, 0);
printf ("Case %d: %d\n", nCase++, DFS (2*n-1, 1, 1));
}
return 0;
}