bzoj 1668: [Usaco2006 Oct] Cow Pie Treasures The wealth in the pie [memory search + pruning]

c[x][y] is the maximum value from (x,y) to (n,m), remember that
there is a pruning because y can only be +1, so when nx>my, even x is always +1 It is also impossible to go to (n, m), just return 0 directly

#include<iostream>
#include<cstdio>
using namespace std;
const int N=105,dx[]={-1,0,1};
int n,m,a[N][N],c[N][N];
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
int dfs(int x,int y)
{
    if(x<1||y<1||x>n||y>m||n-x>m-y)
        return 0;
    if(y==m)
        return x==n?a[n][m]:0;
    if(c[x][y]!=0)
        return c[x][y];
    for(int i=0;i<3;i++)
        c[x][y]=max(c[x][y],dfs(x+dx[i],y+1));
    c[x][y]+=a[x][y];
    return c[x][y];
}
int main()
{
    n=read(),m=read();
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            a[i][j]=read();
    printf("%d\n",dfs(1,1));
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325292098&siteId=291194637