CDOJ 1271 Search gold

简单DP。dp[i][j]表示走到这格的最大金钱数。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

const int maxn=1000+10;
int n,m;
int a[maxn][maxn],dp[maxn][maxn];

bool f(int a,int b)
{
    if(a>=1&&a<=n&&b>=1&&b<=m) return 1;
    return 0;
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
            scanf("%d",&a[i][j]);

    memset(dp,-1,sizeof dp);

    dp[1][1]=a[1][1];


    int newx,newy;
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
        {
            if(dp[i][j]==-1) continue;
            newx=i;
            newy=j+1;

            if(f(newx,newy))
            {
                if(dp[i][j]+a[newx][newy]>=0)
                    dp[newx][newy]=max(dp[newx][newy],dp[i][j]+a[newx][newy]);
            }

            newx=i+1;
            newy=j;

            if(f(newx,newy))
            {
                if(dp[i][j]+a[newx][newy]>=0)
                    dp[newx][newy]=max(dp[newx][newy],dp[i][j]+a[newx][newy]);
            }

            newx=i+1;
            newy=j+2;

            if(f(newx,newy))
            {
                if(dp[i][j]+a[newx][newy]>=0)
                    dp[newx][newy]=max(dp[newx][newy],dp[i][j]+a[newx][newy]);
            }

            newx=i+2;
            newy=j+1;

            if(f(newx,newy))
            {
                if(dp[i][j]+a[newx][newy]>=0)
                    dp[newx][newy]=max(dp[newx][newy],dp[i][j]+a[newx][newy]);
            }
        }

    int ans=dp[1][1];
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
            ans=max(ans,dp[i][j]);

    printf("%d\n",ans);
    return 0;
}

 

你可能感兴趣的:(CDOJ 1271 Search gold)