Hdu 1078 FatMouse and Cheese

记忆化搜索



题意:老鼠偷吃,有n*n的方阵,每个格子里面放着一定数目的粮食,老鼠每次只能水平或竖直最多走k步,每次必须走食物比当前多的格子,问最多吃多少食物。



AC代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;

const int MAXN = 110;

int n, m, max1;
int s[MAXN][MAXN],dp[MAXN][MAXN];
int tab[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};

int max(int a, int b) {return a > b ? a : b;}

int dfs(int x, int y) {
    int xx, yy;
    int max1 = 0, sum;
    if(!dp[x][y]) {
        for(int j = 1; j <= m; j++){
            for(int i = 0; i < 4; i++){
                xx = x + tab[i][0] * j;
                yy = y + tab[i][1] * j;
                if(xx >= 0 && xx < n && yy >= 0 && yy < n && s[xx][yy] > s[x][y]){
                    sum = dfs(xx, yy);
                    max1 = max(max1, sum);
                }
            }
        }
        dp[x][y] = max1 + s[x][y];
    }
    return dp[x][y];
}

int main() {
    while(scanf("%d%d", &n, &m), n > 0){
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                scanf("%d", &s[i][j]);
        memset(dp, 0, sizeof(dp));
        printf("%d\n", dfs(0, 0));
    }
    return 0;
}


你可能感兴趣的:(Hdu 1078 FatMouse and Cheese)