POJ1088滑雪(dp+记忆化搜索)

滑雪
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 86411   Accepted: 32318

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
思路:[i,j]处的长度就要等于[i-1,j],[i+1,j],[i,j+1],[i,j-1]中数值比它小,长度最长的 + 1;
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 using namespace std;
 6 int dp[110][110],g[110][110];
 7 int col,row;
 8 int dfs(int x,int y)
 9 {
10     if(dp[x][y] > 0)     //如果x,y处已经确定了长度就返回,否则就根据他的上下左右来确定它的长度
11         return dp[x][y];
12     int ans = 0;
13     if(x - 1 > 0 && g[x][y] > g[x - 1][y])
14         ans = max(ans, dfs(x - 1, y));
15     if(x + 1 <= row && g[x + 1][y] < g[x][y])
16         ans = max(ans, dfs(x + 1, y));
17     if(y - 1 > 0 && g[x][y - 1] < g[x][y])
18         ans = max(ans, dfs(x, y - 1));
19     if(y + 1 <= col && g[x][y + 1] < g[x][y])
20         ans = max(ans, dfs(x, y + 1));
21     if(ans == 0)
22         return 1;    //如果上下左右没有比它小的,就返回1
23     else
24         return ans + 1; //否则+1
25 }
26 int main()
27 {
28     scanf("%d%d", &row,&col);
29     for(int i = 1; i <= row; i++)
30     {
31         for(int j = 1; j <= col; j++)
32         {
33             scanf("%d", &g[i][j]);
34         }
35     }
36     memset(dp,0,sizeof(dp));
37     int maxn = 0;
38     for(int i = 1; i <= row; i++)
39     {
40         for(int j = 1; j <= col; j++)
41         {
42             dp[i][j] = dfs(i, j);
43             maxn = max(maxn, dp[i][j]);
44 
45         }
46     }
47     printf("%d
", maxn);
48     return 0;
49 }
View Code
原文地址:https://www.cnblogs.com/zhaopAC/p/5059794.html