[ACM] POJ 1088 滑雪 (记忆化搜索复习)

2015-01-27 22:36:02 ? 作者: ? 浏览: 42

滑雪
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 77763 Accepted: 28905

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

Source

SHTSC 2002


想法:

当搜索某个坐标位置处某个状态时(这个状态是最优状态),顺便把其他坐标的最优状态也搜出来了,这样搜索下一个坐标最优状态时,当到达一个位置最优状态已经求出来时就返回,也就是搜过的就不用再搜了。

比如本题,step[i][j] ,定义为 从i,j位置最远可以滑多少步(不包括自己),在搜一遍的时候,把搜到的位置所最优状态(最远可以滑多少步)也同时搜出来了。

寻找全局最优时,搜索每一个坐标,当该坐标如果已经被搜索过了(在之前坐标位置处被搜索),那么就直接返回该坐标的最优状态。从而找到全局最优状态。

代码:

#include 
  
   
#include 
   
     #include 
    
      using namespace std; const int maxn=105; int mp[maxn][maxn]; int step[maxn][maxn]; int dx[4]={0,0,-1,1}; int dy[4]={1,-1,0,0}; int n,m; void input() { cin>>n>>m; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) cin>>mp[i][j]; } bool ok(int x,int y) { if(x>=1&&x<=n&&y>=1&&y<=m) return true; return false; } int dfs(int x,int y) { if(step[x][y]) return step[x][y]; for(int i=0;i<4;i++) { int newx=x+dx[i]; int newy=y+dy[i]; if(ok(newx,newy)&&mp[newx][newy]
     
      step[x][y]) step[x][y]=temp; } } return step[x][y]; } void solve() { int ans=-1; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { int temp=dfs(i,j); if(ans