Problem Description 有个小老鼠在校园里收藏了一些它最爱吃的奶酪。
校园可以看成一个长度为n的正方形网格,每个网格可以标记为 (p, q) ,其中,0
<= p , q < n。每个网格都有一个洞,里面储存了 k(0 <= k <=
100)块奶酪。
现在,小老鼠准备享用这些美味啦。
开始的时候,他在 (0, 0)
这个位置,每到一个地方,它都会吃光这个地方的奶酪,然后沿着水平或者垂直的方向到达另外一个地方。麻烦的是,有个很凶的猫总是在它的洞口附近,所以他每次最多移动
k
个位置,否则就会被这只猫吃掉。更糟糕的是,每在一个地方吃过奶酪,小老鼠都会变胖,所以,为了获得足够下一次逃跑的能量,它每次只能去比当前位置的奶酪更多的格子。
现在已知 n 和 k
,以及在每个网格的洞中小老鼠储存的奶酪的数量,请计算小老鼠在无法移动之前,一共最多能吃到多少块奶酪。
Input 题目包含多组测试数据。
每组测试数据组成如下: 首先一行包含2个不超过100的正整数 n 和 k ;
接下来 n 行,每行包含n个数: 第一行 n 个数分别表示 (0, 0), (0, 1), … (0,
n - 1) 这些位置储存的奶酪数量; 第二行 n 个数分别表示 (1, 0), (1, 1), …
(1, n - 1) 这些位置储存的奶酪数量; 以此类推...
int cheese[MAX_LENG][MAX_LENG]; int ans[MAX_LENG][MAX_LENG]; // 储存结果,初始化为 -1
int n, k; const vector<array<int, 2>> dirs = { {1, 0}, {0, 1}, {-1, 0}, {0, -1} }; // 运动方向
intdfs(int x, int y){ // 记忆化 DFS // 返回以 (x, y) 为起点可以吃到最多的奶酪 if (ans[x][y] >= 0) { // 已经计算过的值 return ans[x][y]; } ans[x][y] = cheese[x][y]; int plusCheese = 0; for (auto& dir :dirs) { for (int s = 1; s <= k; s++) { int nx = x + s * dir[0]; int ny = y + s * dir[1]; if (nx >= 0 && nx < n && ny >= 0 && ny < n && cheese[nx][ny] > cheese[x][y]) { plusCheese = max(plusCheese, dfs(nx, ny)); } } }
ans[x][y] += plusCheese; return ans[x][y]; }
intmain(){
ios::sync_with_stdio(false); while (cin >> n >> k, n != -1 || k != -1) { memset(ans, 0xff, sizeof(ans)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> cheese[i][j]; } } cout << dfs(0, 0) << endl; }
return0; }
案例二
How many ways
Problem Description
这是一个简单的生存游戏,你控制一个机器人从一个棋盘的起始点 (1, 1)
走到棋盘的终点 (n, m)。游戏的规则描述如下:
int energy[MAX_LENG][MAX_LENG]; // 记录每个格点点能量 int ans[MAX_LENG][MAX_LENG]; // 记录答案,初始化为 -1
intdfs(int x, int y){ // 表示从 (x, y) 出发到终点又多少种走法 if (ans[x][y] >= 0) { return ans[x][y]; } if (x == n - 1 && y == m - 1) { ans[x][y] = 1; return ans[x][y]; } int power = energy[x][y]; // 能量 ans[x][y] = 0; for (int i = 0; i <= power; i++) { for (int j = 0; j <= power - i; j++) { // 遍历所有可能位置 int nx = x + i, ny = y + j; if (nx != x || ny != y) { if (nx >= 0 && nx < n && ny >= 0 && ny < m) { ans[x][y] = (ans[x][y] + dfs(nx, ny)) % MAX_NUM; } } } }
return ans[x][y]; }
intmain(){
ios::sync_with_stdio(false); cin >> T; while (T--) { cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> energy[i][j]; } } memset(ans, 0xff, sizeof(ans)); cout << dfs(0, 0) << endl; }