DP-记忆化搜索-HDU-1078-FatMouse and Cheese

#include<bits/stdc++.h>
#define mem(x) memset(x,0,sizeof(x))
using namespace std;
typedef long long ll;
const ll maxn=155;
const ll mod=1e9+7;
const ll inf=0x7f7f7f7f;
template<typename T>void read(T &x)
{
    
    
    x = 0;char ch = getchar();ll f = 1;
    while(!isdigit(ch)){
    
    if(ch == '-')f*=-1;ch=getchar();}
    while(isdigit(ch)){
    
    x = x*10+ch-48;ch=getchar();}x*=f;
}
template<typename T>void write(T x)
{
    
    
    if(x<0)
    {
    
    
        putchar('-');
        x=-x;
    }
    if(x>9)
    {
    
    
        write(x/10);
    }
    putchar(x%10+'0');
}
ll m,n;
bool flag;
ll mp[maxn][maxn];
ll dp[maxn][maxn];
int d[4][2]={
    
    0,1,1,0,0,-1,-1,0};
bool check(ll x,ll y)
{
    
    
    if(x<1||y<1||x>n||y>n)
    {
    
    
        return false;
    }
    return true;
}
ll dfs(ll x,ll y)
{
    
    
    ll tx,ty,kmax=0;
    if(dp[x][y]!=-1)
    {
    
    
        return dp[x][y];
    }
    for(int i=0;i<4;i++)
    {
    
    
        for(int j=1;j<=m;j++)
        {
    
    
            tx=x+d[i][0]*j;
            ty=y+d[i][1]*j;
            if(check(tx,ty)&&mp[tx][ty]>mp[x][y])   
            {
    
    
                kmax=max(kmax,dfs(tx,ty));
            }         
        }
    }
    dp[x][y]=mp[x][y]+kmax;
    return dp[x][y];
}
int main()
{
    
    
    while(scanf("%lld %lld",&n,&m))
    {
    
    
        if(n==-1&&m==-1)
        {
    
    
            return 0;
        }
        memset(dp,-1,sizeof(dp));
        for(int i=1;i<=n;i++)
        {
    
    
            for(int j=1;j<=n;j++)
            {
    
    
                read(mp[i][j]);
            }
        }
        printf("%lld\n",dfs(1,1));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/STL_CC/article/details/105715477