hdu 4826(dp + 记忆化搜索)

时间:2022-03-23 07:20:05

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4826

思路:dp[x][y][d]表示从方向到达点(x,y)所能得到的最大值,然后就是记忆化了。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define REP(i, a, b) for (int i = (a); i < (b); ++i)
#define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
using namespace std; const int MAX_N = (100 + 10);
const int inf = 1 << 30;
int N, M, num[MAX_N][MAX_N];
int dp[MAX_N][MAX_N][3]; void Init()
{
memset(dp, -1, sizeof(dp));
} int dir[3][2] = {{1, 0}, {-1, 0}, {0, 1}};
int dfs(int x, int y, int d)
{
if (x == 1 && y == M) return num[x][y];
if (~dp[x][y][d]) return dp[x][y][d];
int res = -inf;
REP(i, 0, 3) {
int xx = x + dir[i][0], yy = y + dir[i][1];
if ((i == 0 && d == 1) || (i == 1 && d == 0)) continue;
if (xx >= 1 && xx <= N && yy >= 1 && yy <= M) {
res = max(res, num[x][y] + dfs(xx, yy, i));
}
}
return dp[x][y][d] = res;
} int main()
{
int Cas, t = 1;
scanf("%d", &Cas);
while (Cas--) {
scanf("%d %d", &N, &M);
FOR(i, 1, N)
FOR(j, 1, M) scanf("%d", &num[i][j]);
Init();
printf("Case #%d:\n%d\n", t++, dfs(1, 1, 0));
}
return 0;
}