地宫寻宝(记忆化搜索)

版权声明:孜孜不辍 https://blog.csdn.net/calculate23/article/details/84898926

题目大意: 给一张n*m大小的图,每一个位置表示相应数字价值的物品,从(1,1)出发到(n,m)。问恰好拿k件物品的取法数。满足背包中任意物品比坐标位置物品来得大则可取。


解题思路: 感觉时个DP问题,先写了个搜索,T了。想了想,可以剪枝,一些分枝重复遍历了,加了个缓存数组,大致可以解决。


AC代码:

#include<stdio.h>
#include<string.h>

const int maxn = 51;
#define mod 1000000007

int Map[maxn][maxn];
int DP[maxn][maxn][14][14];  //记录状态
int n,m,result;  //行、列、目标

int xynext[2][2]={0,1,1,0};  //走法

inline bool judge(int x,int y)
{
    if(x>n||y>m)
        return false;
    return true;
}
//DP含义: 记录到达xy坐标时拥有have个物品,并且这些物品中最大值为have_max的方法数
//身处x行y列 目前已拥有have个物品 最大物品价值为have_max
int dfs(int x,int y,int have,int have_max) 
{
//    if(DP[x][y][have][have_max]>0)
//        return DP[x][y][have][have_max];
//    if(DP[x][y][have][have_max]<0)
//        return 0;
    if(DP[x][y][have][have_max]!=-1)
        return DP[x][y][have][have_max];
    if(x==n && y==m)
    {
        if(Map[x][y]>have_max && have == result-1) {
            return DP[x][y][have+1][Map[x][y]]=1;
        }else if(have == result) {
            return DP[x][y][have][have_max]=1;
        }
//        DP[x][y][have][have_max]=-1;
//        return 0;
        return DP[x][y][have][have_max]=0;
    }
    int _cnt = 0;
    for(int i=0;i<2;i++) {
        int nx=x+xynext[i][0];
        int ny=y+xynext[i][1];
        if(judge(nx,ny)) {
            if(Map[x][y]>have_max) {
                _cnt = (_cnt+dfs(nx,ny,have+1,Map[x][y]))%mod;
            }
            _cnt = (_cnt+dfs(nx,ny,have,have_max))%mod;
        }
    }
    return DP[x][y][have][have_max]=_cnt;
}

int main()
{
    scanf("%d%d%d",&n,&m,&result);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++) {
            scanf("%d",&Map[i][j]);
            Map[i][j]++;
        }
//    memset(DP,0,sizeof(DP));
    memset(DP,-1,sizeof(DP));
    printf("%d\n",dfs(1,1,0,0));
    return 0;
}

PS: 好久没写C了,被项目的硬件代码虐得死去活来,报个名想找找状态,发现老师又找的蓝桥的题,但今年老师不给大三奖励了。比赛的时候直接开大题,写这个题的时候写的是注释部分,莫名奇妙T了,不是很懂。打了一个多小时的补丁,还是T。回来看了网上的代码的思路,感觉没差多少,神奇,改成初始化-1就1A了…所以这是为啥?(注释部分之前写的)

猜你喜欢

转载自blog.csdn.net/calculate23/article/details/84898926
今日推荐