dp+记忆化搜索
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define DIR 4
#define MAXN 101
int dir[][2] = {
{0, 1}, {0, -1}, {-1, 0}, {1, 0}
};
int h[MAXN][MAXN], dp[MAXN][MAXN], row, col;
int dfs(const int &x, const int &y)
{
if( -1 != dp[x][y] ) {
return dp[x][y];
}
int tx, ty, rst(0);
for(int i = 0; i < DIR; i ++) {
tx = x+dir[i][0]; ty = y+dir[i][1];
if( tx < 0 || ty < 0 || tx >= row || ty >= col || h[x][y] <= h[tx][ty] ) {
continue;
}
dp[tx][ty] = (-1 == dp[tx][ty])? dfs(tx, ty) : dp[tx][ty];
rst = max(rst, dp[tx][ty]);
}
return rst+1;
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int cas, ans;
char name[MAXN]; scanf("%d", &cas);
while( cas -- ) {
scanf("%s %d %d", name, &row, &col);
for(int i = 0; i < row; i ++) {
for(int j = 0; j < col; j ++) {
scanf("%d", &h[i][j]);
}
}
memset(dp, -1, sizeof(dp)); ans = 0;
for(int i = 0; i < row; i ++) {
for(int j = 0; j < col; j ++) {
dp[i][j] = (-1 == dp[i][j])? dfs(i, j) : dp[i][j];
ans = max(ans, dp[i][j]);
}
}
printf("%s: %d\n", name, ans);
}
return 0;
}uva_10285 Longest Run on a Snowboard
最新推荐文章于 2020-06-29 09:53:15 发布
本文介绍了一种结合动态规划与记忆化搜索的方法,用于解决特定类型的路径寻找问题。通过递归的方式预先计算并存储最优路径长度,避免了重复计算,提高了算法效率。代码示例展示了如何在二维网格中寻找从起点到终点的最大递增路径。


390

被折叠的 条评论
为什么被折叠?



