uva 10913 Walking on a Grid

uva 10913 Walking on a Grid

解决方案:dp思路:有四个状态,x,y(位置),ck(走了多少个负数),d(从哪个方向走过了,下,左,右),然后记忆化搜索

code:

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100;
const long long inf=-0x3f3f3f3f3f3f3f3f;
long long mat[maxn][maxn];
long long dp[maxn][maxn][7][4];
bool vis[maxn][maxn][7][4],isat[maxn][maxn];
int N,k;
int dir[3][2]= {{0,1},{1,0},{0,-1}};///0:right;1:down;2:left;
long long dfs(int x,int y,int ck,int d)
{
    long long &res=dp[x][y][ck][d];
    bool &flag=vis[x][y][ck][d];
    if(flag)
    {
        return res;
    }
    else if((x==N&&y==N)||ck==0)
    {
        flag=true;
        if(ck==0)
        {
            return res=inf;
        }
        else return res=mat[x][y];
    }
    else
    {
        res=inf;
        for(int i=0; i<3; i++)
        {
            int xx=x+dir[i][0],yy=y+dir[i][1],t=0;
            if((i==0&&d==2)||(i==2&&d==0)) continue;
            if(mat[x][y]<0) t=-1;
            if(!isat[xx][yy]&&xx>=1&&xx<=N&&yy>=1&&yy<=N)
            {
                isat[xx][yy]=true;
                long long temp=dfs(xx,yy,ck+t,i);
                if(temp!=inf) res=max(res,temp+mat[x][y]);
                isat[xx][yy]=false;
            }
        }
        flag=true;
        return res;
    }

}
int main()
{
    int index=0;
    while(~scanf("%d%d",&N,&k)&&(N+k))
    {
        for(int i=1; i<=N; i++)
            for(int j=1; j<=N; j++)
                scanf("%lld",&mat[i][j]);
        memset(vis,false,sizeof(vis));
        memset(isat,false,sizeof(isat));
        if(mat[N][N]<0) k--;
        long long res=dfs(1,1,k+1,1);
        if(res==inf)
        {
            printf("Case %d: impossible\n",++index);
        }
        else
        {
            printf("Case %d: %lld\n",++index,res);
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值