动态规划(记忆化搜索)

D - 滑雪

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

题解:依次遍历每个点,在每个点处利用dfs搜索以该点为起点的最长的路径,最后找到整个图的最长路径。。。

AC代码:

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int a[105][105];
int dp[105][105];
int nex[4][2]={1,0,0,1,-1,0,0,-1};
int r,c;
int _max;
int dfs(int x,int y)
{
    if(dp[x][y])
        return dp[x][y];
    int nx,ny,Max=0;//nx,ny,Max
    for(int k=0;k<4;k++)
    {
        nx=x+nex[k][0];
        ny=y+nex[k][1];
        if(nx<1||nx>r||ny<1||ny>c)
            continue;
        if(a[x][y]>a[nx][ny]&&dfs(nx,ny)>Max)
            Max=dp[nx][ny];
    }
    //cout<<'('<<nx<<','<<ny<<')'<<endl;
    dp[x][y]=Max+1;
    return dp[x][y];
}
int main()
{
    ios::sync_with_stdio(0);cin.tie(0);

    memset(dp,0,sizeof dp);
    //memset(a,0x3f3f3f3f,sizeof a);
    cin>>r>>c;
    for(int i=1;i<=r;i++)
        for(int j=1;j<=c;j++)
        {
          cin>>a[i][j];
          dp[i][j]=0;
        }
    _max=0;
    for(int i=1;i<=r;i++)
        for(int j=1;j<=c;j++)
        {
        dfs(i,j);
        if(dp[i][j]>_max)
            _max=dp[i][j];
        }
    cout<<_max<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shaohang_/article/details/81098238