专题二:B-滑雪

该问题描述了一个关于滑雪的场景,通过二维数组表示地形高度,目标是找到最长的下降路径。由于数据量大,使用了记忆化搜索优化算法,避免重复计算,以提高效率。代码示例中展示了如何实现这个算法,并在遍历数组中找到最长的滑坡长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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(从 24 开始,在 1 结束)。当然 25-24-23-……-3-2-1 更长。事实上,这是最长的一条。

Input

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

Output

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

思路

因为数据较大,一般的搜索肯定会超时,因此,我们可以用记忆化搜索,在搜索的同时记录下当前值,避免重复搜索,降低时间复杂度

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<bitset>
#include<set>

using namespace std;
#define _CRT_SECURE_NO_WARNINGS 1
#define ll long long
#define pub push_back
#define pob pop_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define inf 2e9
#define llf 1e19
#define endl "\n"
const ll mod = 1e9 + 7;

ll qpow(ll base, ll power)
{
	ll res = 1;
	while (power > 0)
	{
		if (power & 1) res = base * res % mod;
		power >>= 1;
		base = base * base % mod;
	}
	return res;
}

ll gcd(ll a, ll b)
{
	return b == 0 ? a : gcd(b, a % b);
}

ll lcm(ll a, ll b)
{
	return a / gcd(a, b) * b;
}

double dis(double x, double y, double x1, double y1)
{
	return sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
}
double dis1(double x, double y, double z, double x1, double y1, double z1)
{
	return sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1) + (z - z1) * (z - z1));
}
double chaji(double x1, double x2, double y1, double y2)
{
	return x1 * y2 - x2 * y1;
}

int r, c, ans, a[110][110], cnt[110][110];
int dfs(int x, int y)
{
	int way[4][2] = { 1,0,0,1,0,-1,-1,0 };
	if (cnt[x][y]) return cnt[x][y];//记忆化搜索
	cnt[x][y] = 1;
	for (int i = 0; i < 4; i++)
	{
		int xx = x + way[i][0];
		int yy = y + way[i][1];
		if (xx >= 1 && xx <= r && yy >= 1 && yy <= c && a[x][y] > a[xx][yy])
		{
			dfs(xx, yy);
			cnt[x][y] = max(cnt[x][y], cnt[xx][yy] + 1);//记录下当前值
		}		
	}
	return cnt[x][y];
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	int i, j;
	cin >> r >> c;
	for (i = 1; i <= r; i++)
	{
		for (j = 1; j <= c; j++)
		{
			cin >> a[i][j];
		}
	}
	for (i = 1; i <= r; i++)
	{
		for (j = 1; j <= c; j++)
		{
			ans = max(ans, dfs(i, j));
		}
	}
	cout << ans;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值