【一只蒟蒻的刷题历程】【洛谷】P1434 [SHOI2002]滑雪 (记忆化搜索)

题目描述

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

一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度会减小。在上面的例子中,一条可行的滑坡为 242424-171717-161616-111(从 242424 开始,在 111 结束)。当然 252525-242424-232323-…\ldots…-333-222-111 更长。事实上,这是最长的一条。

输入格式

输入的第一行为表示区域的二维数组的行数 RRR 和列数 CCC。下面是 RRR 行,每行有 CCC 个数,代表高度(两个数字之间用 111 个空格间隔)。

输出格式

输出区域中最长滑坡的长度。

输入输出样例

输入 #1

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

输出 #1

25

说明/提示

对于 100%100%100% 的数据,1≤R,C≤1001\leq R,C\leq 1001≤R,C≤100。

思路

题目的算法标签是动态规划,但是我不会,略微了解过动态规划,个人理解感觉动态规划和记忆化搜索思想上貌似没什么区别吧???

简单来说就是:减少不必要的重复计算

代码

#include <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <cstring>
#include <cmath>
#include <vector>
#include <set>
#include <map>
using namespace std;

int site[110][110]; //地图
int dx[]={1,-1,0,0}; //四个方向
int dy[]={0,0,1,-1};
int dp[110][110]; //记录每个点的能滑的最远距离
int r,c;

int dfs(int x,int y)
{
	if(dp[x][y]) return dp[x][y]; //计算过,直接返回
	dp[x][y]=1; //原地也算1
	for(int i=0;i<4;i++)
	{
		int nowx=x+dx[i];
		int nowy=y+dy[i];
		if(nowx>=0 && nowx<r && nowy>=0 && nowy<c && site[nowx][nowy]<site[x][y])
		//在边界内,并且下一个点的高度低于当前高度
		{
			dfs(nowx,nowy);
			dp[x][y] = max(dp[x][y] , dp[nowx][nowy]+1);
			//比较原点能到达的距离 和 下一个点能到的距离哪个更大,
			//+1代表原点到下一个点需要走一步
		}
	}
	return dp[x][y];
}
int main()
{
   
   cin>>r>>c;
   
   for(int i=0;i<r;i++)
     for(int j=0;j<c;j++)
	   cin>>site[i][j];  //输入图
	
	int ans=-1;  
    for(int i=0;i<r;i++)
	  for(int j=0;j<c;j++)
	     ans=max(ans,dfs(i,j));	   
	    //比较 每个点能到达最远的距离,取最大值
   	   
   cout<<ans;
 
	return 0;
}
原创文章 32 获赞 35 访问量 1529

猜你喜欢

转载自blog.csdn.net/weixin_45260385/article/details/105590458