ZOJ 1107 FatMouse and Cheese(记忆化搜索)

来源:互联网 发布:ubuntu怎么安装jdk1.8 编辑:程序博客网 时间:2024/06/06 06:49

FatMouse and Cheese

Time Limit: 10 Seconds      Memory Limit: 32768 KB

FatMouse has stored some cheese in a city. The city can be considered as a square grid of dimension n: each grid location is labelled (p,q) where 0 <= p < n and 0 <= q < n. At each grid location Fatmouse has hid between 0 and 100 blocks of cheese in a hole. Now he's going to enjoy his favorite food.

FatMouse begins by standing at location (0,0). He eats up the cheese where he stands and then runs either horizontally or vertically to another location. The problem is that there is a super Cat named Top Killer sitting near his hole, so each time he can run at most k locations to get into the hole before being caught by Top Killer. What is worse -- after eating up the cheese at one location, FatMouse gets fatter. So in order to gain enough energy for his next run, he has to run to a location which have more blocks of cheese than those that were at the current hole.

Given n, k, and the number of blocks of cheese at each grid location, compute the maximum amount of cheese FatMouse can eat before being unable to move.

Input Specification

There are several test cases. Each test case consists of

  • a line containing two integers between 1 and 100: n and k
  • n lines, each with n numbers: the first line contains the number of blocks of cheese at locations (0,0) (0,1) ... (0,n-1); the next line contains the number of blocks of cheese at locations (1,0), (1,1), ... (1,n-1), and so on.
The input ends with a pair of -1's.

Output Specification

For each test case output in a line the single integer giving the number of blocks of cheese collected.

Sample Input

3 11 2 510 11 612 12 7-1 -1

Output for Sample Input

37

Source: Zhejiang University Training Contest 2001


直接记忆化搜索即可,dp方案的话注意更新的问题,可以尝试正反两次dp。


AC代码:

#include <stdio.h>#include <string.h> int n, k;int grid[105][105];int mem[105][105]; int memSearch(int r, int c)//当前行列(r,c) {int r1, c1;int max = 0;if(mem[r][c] != -1)     return mem[r][c];    for(int i = 1;i <= k;i++){//向上前进i步 r1 = r - i;if(r1 >= 1 && r1 <= n && grid[r][c] < grid[r1][c]){mem[r1][c] = memSearch(r1, c);if(mem[r1][c] > max) max = mem[r1][c];}//向下前进i步 r1 = r + i;if(r1 <= n && r1 >= 1 && grid[r][c] < grid[r1][c]){mem[r1][c] = memSearch(r1, c);if(mem[r1][c] > max) max = mem[r1][c];}//向左前进i步 c1 = c - i;if(c1 >= 1 && c1 <= n && grid[r][c] < grid[r][c1]){mem[r][c1] = memSearch(r, c1);if(mem[r][c1] > max) max = mem[r][c1];}//向右前进i步 c1 = c + i;if(c1 <= n && c1 >= 1 && grid[r][c] < grid[r][c1]){mem[r][c1] = memSearch(r, c1);if(mem[r][c1] > max) max = mem[r][c1];}}return max + grid[r][c];//加上当前格子奶酪 }int main(){while(scanf("%d%d", &n, &k)){if(n == -1 && k == -1) break;for(int i = 1;i <= n;i++)for(int j = 1;j <= n;j++)scanf("%d", &grid[i][j]);memset(mem, -1, sizeof(mem));printf("%d\n", memSearch(1, 1));}return 0;}


原创粉丝点击