vj1011:记忆化搜索

vj1011:记忆化搜索

这题就是很简单的记忆化搜索即可,和经典题目滑雪简直一模一样

对于记忆化搜索,我也是暑假看了ccy大神的题解才有所领悟的

其实也就是DFS+mark

主要的部分
1
2
3
4
5
6
7
8
9
10
11
12
13
int search(int x,int y){
    if(f[x][y]>0) return f[x][y];
    int ans=0;
    int xx,yy;
    for(int i=0;i<4;i++){
        xx=x+dx[i];
        yy=y+dy[i];
        if(xx>0 && xx<=n && yy>0 && yy<=m && a[x][y]>a[xx][yy]){
            ans=max(ans,search(xx,yy));
        }
    }
    return f[x][y]=ans+1;
}

 恩..其实也说不出来记忆化搜索这类题目的技巧吧...多感受

 码起来挺简单的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <algorithm>
#include <cmath>
using namespace std;
const int dx[5]={0,0,1,-1},dy[5]={1,-1,0,0};
int a[501][501],f[501][501];
int h,n,m,maxn=0,ans;
int max(int a,int b){
    return a>b?a:b;
}
int search(int x,int y){
    if(f[x][y]>0) return f[x][y];
    int ans=0;
    int xx,yy;
    for(int i=0;i<4;i++){
        xx=x+dx[i];
        yy=y+dy[i];
        if(xx>0 && xx<=n && yy>0 && yy<=m && a[x][y]>a[xx][yy]){
            ans=max(ans,search(xx,yy));
        }
    }
    return f[x][y]=ans+1;
}
int main(){
    memset(f,-1,sizeof(f));
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
       for(int j=1;j<=m;j++) cin>>a[i][j];
    ans=-1;
    for(int i=1;i<=n;i++)
       for(int j=1;j<=m;j++){
          if(f[i][j]==-1) ans=max(ans,search(i,j));
       }
    printf("%d\n",ans);
    return 0;
}

 


posted @   polebug  阅读(182)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示