poj 1088 Joy OI1004(滑雪)

52 篇文章 0 订阅
4 篇文章 0 订阅

滑雪

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 73409 Accepted: 27141

 

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的思想。dp[i][j] 保存的是当前坐标i,j可以到达的最大距离(包括自己),比如3 2 1,当前是3,那么可以到达的最大距离为3,对于每个坐标,可以上下左右四个方向搜索,取距离最大的那个,作为该坐标的dp[][]。记忆化搜索这里体现的就是当搜索到某一个坐标时,该坐标的dp[][]已经有值(搜索过了),且肯定是最优的,那么直接返回该dp[][]值就可以了。

#include<stdio.h>
#include<string.h>
#define N 30
int map[N][N];
int dp[N][N];
int m,n,ans;
int rowX[4] = {0,0,-1,1};
int colY[4] = {-1,1,0,0};
bool inner(int row, int col){//判断是否在矩阵里面 
	if(row >= 0 && row < n && col >= 0 && col < m)
		return true;
	return false;
}

int dfs(int row, int col){
	int i,j,nextRow,nextCol,max,temp;
	if(dp[row][col]){//如果最长路径已经记录,不用再计算 
		return dp[row][col];
	}
	max = 1;//max记录四个方向最大值 
	for(i=0; i<4; i++){//从四个方向遍历
		nextRow = row + rowX[i];
		nextCol = col + colY[i];
		if(inner(nextRow,nextCol) && map[row][col] > map[nextRow][nextCol]){
			temp = dfs(nextRow,nextCol);
			max = temp+1>max?temp+1:max;
		}
	}
	dp[row][col] = max;
	return max;
}

int main(){
	int i,j,temp;
	scanf("%d%d",&n,&m);
	for(i=0; i<n; i++)
		for(j=0; j<m; j++)
			scanf("%d",&map[i][j]);
	memset(dp,0,sizeof(dp));
	ans = 0;
	for(i=0; i<n; i++)
		for(j=0; j<m; j++){
			temp = dfs(i,j);
			ans = temp > ans ? temp : ans;
		}
	printf("%d\n",ans);
	return 0;
}

想了很久啊,写代码用了1个小时,调试10分钟,有图有真相。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值