Codeforces Round #220 (Div. 2)C题:Inna and Dima(记忆化搜索+DP)

题目地址:http://codeforces.com/problemset/problem/374/C

用dp[i][j]代表第i行第j列的数可以走的最大距离。为-1时表示未走过,将走过但未走完的暂时标记为INF。这样假如有环的时候就返回INF了。然后用dfs搜。

代码如下:

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <algorithm>

using namespace std;
#define LL __int64
const int INF=0x3f3f3f3f;
char mp[1001][1001], str[]="DIMA";
int dp[1001][1001];
int jx[]={0,0,1,-1};
int jy[]={1,-1,0,0};
int n, m;
int dfs(int x, int y, int tmp)
{
    if(dp[x][y]!=-1) return dp[x][y];
    dp[x][y]=INF;
    int i, a, b, t=0;
    tmp=(1+tmp)%4;
    for(i=0;i<4;i++)
    {
        a=x+jx[i];
        b=y+jy[i];
        if(a>=0&&a<n&&b>=0&&b<m&&mp[a][b]==str[tmp])
        {
            t=max(t,dfs(a,b,tmp));
        }
    }
    dp[x][y]=++t;
    return t;
}
int main()
{
    int i, j, max1=0;
    scanf("%d%d",&n,&m);
    for(i=0;i<n;i++)
    {
        scanf("%s",mp[i]);
    }
    memset(dp,-1,sizeof(dp));
    for(i=0;i<n;i++)
    {
        for(j=0;j<m;j++)
        {
            if(mp[i][j]=='D')
            {
                max1=max(max1,dfs(i,j,0));
            }
        }
    }
    if(max1/4==0)
    {
        puts("Poor Dima!");
    }
    else if(max1>=INF)
    {
        puts("Poor Inna!");
    }
    else
        printf("%d\n",max1/4);
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值