记忆化搜索例题 记忆化搜索

1.poj  1579

题目链接:

http://poj.org/problem?id=1579

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=1e4+5;
int a,b,c;
int vis[20][20][20];
int dp[20][20][20];
int solve(int a,int b,int c)
{
    if(a<=0||b<=0||c<=0)
    {
        return 1;
    }
    if(a>20||b>20||c>20)
    {
        return solve(20,20,20);
    }
    if(a<b&&b<c)
    {
        if(!vis[a][b][c])
        {
            dp[a][b][c]=solve(a,b,c-1)+solve(a,b-1,c-1)-solve(a,b-1,c);
            vis[a][b][c]=1;
        }
        return dp[a][b][c];
    }
    else
    {
        if(!vis[a][b][c])
        {
            dp[a][b][c]=solve(a-1,b,c)+solve(a-1,b-1,c)+solve(a-1,b,c-1)-solve(a-1,b-1,c-1);
            vis[a][b][c]=1;
        }
        return dp[a][b][c];
    }
}
int main()
{
    memset (vis,0,sizeof(vis));
    while(scanf("%d%d%d",&a,&b,&c))
    {
        if(a==-1&&b==-1&&c==-1) break;
        printf("w(%d, %d, %d) = %d\n",a,b,c,solve(a,b,c));
    }
    return 0;
}

2.hdu 1078 FatMouse and Cheese

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1078

dp[i][j]表示在i,j位置的最大数目.

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=105;
int n,k;
int a[maxn][maxn];
int vis[maxn][maxn];
int dp[maxn][maxn];
int pos[4][2]={
  
  {0,1},{0,-1},{1,0},{-1,0}};
int ans;
int Max;
int M
### 关于记忆化搜索的练习题 在洛谷平台上有许多涉及记忆化搜索的经典题目,这些题目可以帮助学习者更好地理解动态规划与深度优先搜索相结合的方法。以下是几个推荐的记忆化搜索习题及其背景介绍: #### 题目一:P4170 [CQOI2007] 涂色 此题属于经典的 DP 类型问题之一,主要考察如何通过记忆化的方式优化暴力枚举的过程[^1]。 该题的核心在于利用状态压缩技术存储已经处理过的子结构,并结合 DFS 的方式逐步扩展解空间。 #### 题目二:P1464 Function 这是一个典型的递归加记忆化的入门级题目[^2]。它强调了在搜索过程中记录中间结果的重要性,从而避免不必要的重复计算。具体实现上可以通过定义一个辅助数组 `f[x][y]` 来保存已访问的状态值。 #### 题目三:UVA - 1629 Cake Slicing 这篇文章提到的一道经典例题展示了记搜的优势所在[^3]。通过对不同切割方案的结果进行缓存操作,可以显著降低时间复杂度并提高效率。 #### 题目四:滑雪 (P1434) 作为一道非常受欢迎的记忆化搜索习题,“滑雪”模拟了一个二维网格上的最长下降路径求解过程[^5]。给定一张地图表示各个位置的高度分布情况后,我们需要找到从任意起点出发能够达到的最大步数长度。 ```python from functools import lru_cache @lru_cache(None) def dfs(x, y): res = 1 directions = [(0,-1),(-1,0),(0,+1),(+1,0)] for dx, dy in directions: nx, ny = x + dx, y + dy if 0<=nx<R and 0<=ny<C and grid[nx][ny]<grid[x][y]: res = max(res, dfs(nx, ny)+1 ) return res R,C=map(int,input().split()) grid=[list(map(int,input().strip().split()))for _ in range(R)] ans=0 for i in range(R): for j in range(C): ans=max(ans ,dfs(i,j)) print(ans) ``` 上述代码片段实现了基于 Python 的解决方案,其中运用装饰器 @lru_cache 实现自动化的函数调用结果缓存功能。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值