[Skiing] POJ1088

Classic example of memory search

Apparently the idea of ​​a direct enumeration of each point as a starting point and then dfs, and the maximum value. Obviously, this approach will TLE, we may wish to look at optimizing: As each point is to repeat the search, we may wish to remember of, after this point the search is complete, we remember the optimal solution starting from this point down. When the next search to this point we can O (1) return the answer, so that search efficiency is greatly improved, reducing a lot of useless search, our algorithm can the AC.

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 int map[110][110],f[110][110],n,m;
 7 int dx[5]={0,0,1,-1};
 8 int dy[5]={1,-1,0,0};
 9 int dfs(int x,int y) {
10     if(f[x][y]!=-1) return f[x][y];
11     f[x][y]=0;
12     int sum=0;
13     for(int i=0;i<5;i++) {
14         int xx=x+dx[i];
15         int yy=y+dy[i];
16         if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&map[x][y]>map[xx][yy]) {
17             sum=max(sum,dfs(xx,yy));
18         }
19     }
20     return f[x][y]=sum+1;
21 }
22 int main() {
23     cin>>n>>m;
24     for(int i=1;i<=n;i++)
25         for(int j=1;j<=m;j++)
26             cin>>map[i][j];
27     memset(f,-1,sizeof(f));
28     int ans=0;
29     for(int i=1;i<=n;i++)
30         for(int j=1;j<=n;j++) {
31             int x=dfs(i,j);
32             ans=max(ans,x);
33         }
34     cout<<ans<<endl;
35     return 0;
36 }
AC Code

 

Guess you like

Origin www.cnblogs.com/shl-blog/p/10962226.html