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; } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步