HDU 1078 FatMouse and Cheese (dfs + dp memory search)

  • Topic link: HDU 1078
  • Question: Given the square matrix of N x N, each lattice has a value. Ask from [0, 0] to go up and down in four directions, at most k lattices can be used at a time, and the value of each lattice must be greater than that of the previous one (strictly greater). Ask: What is the maximum value that can be eaten?
  • Solution: dp[i][j] denotes the maximum value that can be eaten from [i,j], from which the answer can be obtained by memory search.
#include<bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
#define fir first
#define sec second
#define repp(i, a, b) for(int i=(b); i>=(a); --i)
#define rep(i,a,b) for (int i=(a); i<=(b); ++i)
#define de(x) cout<< #x << " => " << (x) << endl
#define ms(a, b) memset(a, b, sizeof(a))
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
const int inf = 0x3f3f3f3f;
const double PI=acos(-1);
const double eps=1e-9;
inline void file_put() {
    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
}
const int maxn = 1e2+5;
int n, k;
int a[maxn][maxn]; 

int dp[maxn][maxn];//Represents the maximum value from [i,j] energy 
int dx[4]={0, 1, 0, -1};
int dy[4]={1, 0, -1, 0}; 
int solve(int x, int y){
    int ans=0;
    if(!dp[x][y]){
        rep(i, 1, k){
            rep(j, 0, 3){
                int xx = x + dx[j]*i;
                int yy = y + dy[j]*i;
                if(xx<1 || yy<1 || xx>n ||yy>n) continue;
                if(a[xx][yy] > a[x][y]){
                    ans = max(ans, solve(xx, yy));
                }           
            }
        }
        dp[x][y] = ans+a[x][y];
    }
    return dp[x][y];
}
int main() {
//  file_put();
    while(~scanf("%d %d", &n, &k), n!=-1 || k!=-1){
        ms(a, 0);
        ms(dp, 0);
        rep(i, 1, n){
            rep(j, 1, n){
                scanf("%d", &a[i][j]);
            }
        }
        printf("%d\n", solve(1, 1));
    }
    return 0;
}

Posted by roydukkey on Thu, 14 Feb 2019 06:33:18 -0800