poj 1088 滑雪(记忆化搜索)

来源:互联网 发布:装修有哪些建议 知乎 编辑:程序博客网 时间:2024/05/21 19:33

滑雪

Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 70105 Accepted: 25860

Description

Michael喜欢滑雪百这并不奇怪, 因为滑雪的确很刺激。可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机来载你。Michael想知道载一个区域中最长底滑坡。区域由一个二维数组给出。数组的每个数字代表点的高度。下面是一个例子
 1  2  3  4 516 17 18 19 615 24 25 20 714 23 22 21 813 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 51 2 3 4 516 17 18 19 615 24 25 20 714 23 22 21 813 12 11 10 9

Sample Output

25

 

// 典型的动态规划,用递归下的记忆化搜索来实现
// 状态转移方程 合法的情况下:DP(i,j)= max( DP(i,j-1), DP(i,j+1), DP(i-1,j), DP(i+1,j) ) + 1;


<pre name="code" class="cpp">#include<stdio.h>#include<math.h>#include<string.h>#include<stdlib.h>#define N 105int h[N][N];int cnt[N][N];   // 记录每一个点的最大滑雪长度int dir[4][2]= {0,-1,0,1,-1,0,1,0};int r,c;int judge(int i,int j){    if(i>=0&&i<r&&j>=0&&j<c)        return 1;    return 0;}int dp(int x,int y,int high){    int i,di,dj,max=0;// 如果已经处理过,直接返回(记忆化搜索效率之所以高的原因:不重复计算)    if(cnt[x][y]>0)        return cnt[x][y];    for(i=0; i<4; i++)    {        di=x+dir[i][0];        dj=y+dir[i][1];        if(judge(di,dj)&&h[di][dj]<h[x][y])        {            int t=dp(di,dj,h[di][dj]);            max=max>t?max:t;        }    }    return cnt[x][y]=max+1;// 将结果记录在cnt数组中(记忆化搜索的重点)// 如果左右上下都没有一个点的值比这个点的值大,则cnt[i][j] = max+1 ;// 否则将左右上下各点最大滑雪长度记录在max中;}int main(){    int i,j;    while(scanf("%d%d",&r,&c)!=EOF)    {        memset(cnt,0,sizeof(cnt));        for(i=0; i<r; i++)            for(j=0; j<c; j++)                scanf("%d",&h[i][j]);        int ans=0;        for(i=0; i<r; i++)            for(j=0; j<c; j++)            {                dp(i,j,h[i][j]);                if(cnt[i][j]>ans)                    ans=cnt[i][j];            }        printf("%d\n",ans);    }    return 0;}


原创粉丝点击