滑雪(记忆化搜索)

链接:https://ac.nowcoder.com/acm/problem/105685
来源:牛客网

题目描述

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更长。事实上,这是最长的一条。

输入描述:

输入的第一行表示区域的行数R和列数C(1 <= R,C <= 100)。下面是R行,每行有C个整数,代表高度h,0<=h<=10000。

输出描述:

输出最长区域的长度。

示例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

输出

25

如果直接暴搜会TLE,需要记忆化,记忆化后的复杂度降为 O ( R C ) O(R*C)

状态转移为: d f s ( x , y ) = m a x ( d f s ( n x , n y ) + 1 ) dfs(x, y) = max(dfs(nx, ny) + 1)

还可以用dp做,但是本菜鸡不会

#include <iostream>
using namespace std;
const int N = 105;

int ma[N][N], dp[N][N];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int n, m;

int dfs(int x, int y)
{
	if (dp[x][y] != 0) {
		return dp[x][y];
	}
	// res 表示从 (x, y) 出发到达的最远距离 
	int res = 1;
	for (int i = 0; i < 4; i++) {
		int nx = x + dx[i], ny = y + dy[i];
		if (nx >= 0 && nx < n && ny >= 0 && ny < m && ma[nx][ny] < ma[x][y]) {	
			res = max(res, dfs(nx, ny) + 1);
		}
	}
	
	return dp[x][y] = res;
}

int main(void)
{
	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cin >> ma[i][j];
		}
	}
	int res = 1;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			res = max(res, dfs(i, j));
		}
	}
	cout << res << endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43772166/article/details/107025085