传送门
Description
Michael喜欢滑雪百这并不奇怪, 因为滑雪的确很刺激。可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机来载你。Michael想知道载一个区域中最长底滑坡。区域由一个二维数组给出。数组的每个数字代表点的高度。下面是一个例子
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度减小。在上面的例子中,一条可滑行的滑坡为24-17-16-1。当然25-24-23-…-3-2-1更长。事实上,这是最长的一条。
Input
输入的第一行表示区域的行数R和列数C(1 <= R,C <= 100)。下面是R行,每行有C个整数,代表高度h,0<=h<=10000。
Output
输出最长区域的长度。
Sample Input
5 5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Sample Output
25
题目大意:找一个起始点,从四周搜索,找到比这个点的值小的点,点连成串,求此串的最大长度。
记忆化深搜与普通深搜类似,记忆化深搜要求把所有的点都作为起点来搜一下,,所求的数值通过递归相加,dp这个数组有标记的作用,还附带所求值(记忆化),再次搜到这个点时,直接return返回即可。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[110][110],dp[110][110],n,m;
int ne[4][2]={0,1,0,-1,1,0,-1,0};
int jude(int x,int y)
{
if(x>=0&&y>=0&&x<n&&y<m)
return 1;
return 0;
}
int dfs(int x,int y)
{
int d=1,i,tx,ty;// d赋值为1很重要,否则遍历中d初值为上一个d
if(dp[x][y]!=-1)//如果这个点已经深搜过,则下次遇到可以直接使用,减少时间。
return dp[x][y];
for(i=0;i<4;i++)
{
tx=x+ne[i][0];
ty=y+ne[i][1];
if(jude(tx,ty)&&a[x][y]<a[tx][ty])
{
d=max(d,dfs(tx,ty)+1);
}
dp[x][y]=d;//x,y的最长距离已经算清了,不用再重复算了
}
return d;
}
int main()
{
int i,j,s=0;
scanf("%d %d",&n,&m);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
dp[i][j]=-1;
}
for(i=0;i<n;i++)
for(j=0;j<m;j++)
s=max(s,dfs(i,j));
printf("%d\n",s);
}
By the end , i 'm bigclever,wish you more and more wise.