UVA 10285 - Longest Run on a Snowboard

这是一道动态规划的dps问题,注意深搜的过程中做到记忆化搜索。

代码如下:

#include<stdio.h>
#include<string.h>
int n, R, C, max, a[105][105], f[105][105];
char name[100];
int dp(int i, int j)
{
if(f[i][j] != 0) return f[i][j];
if(i<=R&&i>=1&&j<=C&&j>=1)
{
int k, p, q;
if(a[i][j] > a[i-1][j])
f[i][j] = dp(i-1, j) + 1;
if(a[i][j] > a[i+1][j] && f[i][j] < (k=dp(i+1, j)+1))
f[i][j] = k;
if(a[i][j] > a[i][j-1] && f[i][j] < (p=dp(i,j-1)+1))
f[i][j] = p;
if(a[i][j] > a[i][j+1] && f[i][j] < (q=dp(i,j+1)+1))
f[i][j] = q;
if(f[i][j] == 0)
f[i][j] = 1;
}
return f[i][j];
}
void input()
{
while(scanf("%d",&n) == 1)
while(n --)
{
scanf("%s%d%d",name, &R, &C);
memset(a, 0, sizeof(a));
memset(f, 0, sizeof(f));
for(int i = 1; i <= R; i ++)
for(int j = 1; j <= C; j ++)
scanf("%d",&a[i][j]);
max = 0;
for(int i = 1; i <= R; i ++)
for(int j = 1; j <= C; j ++)
{
int z = dp(i,j);//printf("i=%d j=%d z=%d\n",i, j, z);
if(z > max) max = z;
}
printf("%s: %d\n",name,max);
}
}
int main()
{
input();
return 0;
}



你可能感兴趣的:(long)