滑雪 记忆化搜索

题目:
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。
输出:
输出最长区域的长度。
样例输入:
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
 
 
 
题解:
记忆化搜索啊,这一次wa了一天,但是其实真的只差一点点,记忆化搜索的关键是每次用数组把结果存起来,而调用时,如果遇到数组里的状态,直接调用,这里我多此一举了,其实代码很简单,只要一次max函数,以后还是要多多注意规律,里面有一个sum=1,代表每次遇到新的点,肯定走一格,这样搜索简单多了,以后套路还是要熟悉啊!
 1 #include <cstdio>
 2 #include <iostream>
 3 #include <algorithm>
 4 using namespace std;
 5 int record[102][102];
 6 int a[102][102];
 7 bool isl[102][102];
 8 bool is[102][102];
 9 int nextt[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
10 int r,c;
11 int recorddfs(int x,int y)
12 {
13     int sum=1;
14    if(record[x][y])
15    {
16           return record[x][y];
17    }
18    for(int i=0;i<4;i++)
19    {
20        int tx=x+nextt[i][0];
21        int ty=y+nextt[i][1];
22        if(tx<r&&tx>=0&&ty>=0&&ty<c&&a[tx][ty]<a[x][y])
23        {
24            int u=recorddfs(tx,ty)+1;
25         sum=max(sum,u);
26        }
27    }
28    record[x][y]=sum;
29    return sum;
30 }
31 int main()
32 {
33     cin>>r>>c;
34     for(int i=0;i<r;i++)
35     {
36         for(int j=0;j<c;j++)
37         scanf("%d",&a[i][j]); 
38     } 
39     int ans=0;
40     for(int i=0;i<r;i++)
41     {
42         for(int j=0;j<c;j++)
43         {    
44            
45             ans=max(ans,recorddfs(i,j));
46         
47         }
48     }
49     cout<<ans<<endl;
50 }

猜你喜欢

转载自www.cnblogs.com/coolwx/p/11123521.html