百练1088:滑雪 【DP】+【DFS】

总Time Limit: 1000ms Memory Limit: 65536kB


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[x][y] = max(dp[i][j]) + 1; dp[x][y]表示从点xy開始的最长路径,dp[i][j]表示xy的四个邻居中比xy低的点的最长路径。

#include <stdio.h>
#define maxn 102

int dp[maxn][maxn], map[maxn][maxn];
int n, m, mov[][2] = {-1, 0, 1, 0, 0, 1, 0, -1};

bool check(int i, int j)
{
    return i >= 0 && i < n && j >= 0 && j < m;
}

int DFS(int x, int y)
{
    if(dp[x][y]) return dp[x][y];
    int i, j, k, t, ans = 1;
    for(k = 0; k < 4; ++k){
        i = x; j = y;
        i += mov[k][0]; j += mov[k][1];
        if(check(i, j) && map[i][j] < map[x][y]){
            t = 1 + DFS(i, j);
            if(t > ans) ans = t;
        }
    }
    return dp[x][y] = ans; //important! better than return ans;
}

int main()
{
    int i, j, ans;
    scanf("%d%d", &n, &m);
    for(i = 0; i < n; ++i){
        for(j = 0; j < m; ++j) scanf("%d", &map[i][j]);
    }
    ans = 1;
    for(i = 0; i < n; ++i){
        for(j = 0; j < m; ++j){
            dp[i][j] = DFS(i, j);
            if(ans < dp[i][j]) ans = dp[i][j];
        }
    }
    printf("%d
", ans);
    return 0;
}


原文地址:https://www.cnblogs.com/gcczhongduan/p/4047676.html