1. 程式人生 > >HDU 1078 FatMouse and Cheese (記憶化搜尋)

HDU 1078 FatMouse and Cheese (記憶化搜尋)

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

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

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

Sample Input

3 1
1 2 5
10 11 6
12 12 7
-1 -1

Sample Output

37

 

按照我自己的理解,記憶化搜尋就是一種剪枝,它省略一些不必要的計算,這裡的不必要計算就是計算已經計算出來的值,原理就收在函式開頭判斷當前狀態的最優值是否已經計算出來,如果以計算出來,直接返回這個值。

#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int n,m;
int dp[105][105],map[105][105];
int d[4][2]={1,0,-1,0,0,1,0,-1};
int check(int x,int y)
{
	if(x<0 || x>=n || y<0 || y>=n)
	return 0;
	else
	return 1;
}
int dfs(int x,int y)
{
	int ans=0;
	if(dp[x][y]!=0) return dp[x][y];//記憶化搜尋 
	for(int k=1;k<=m;k++)
	{
		for(int i=0;i<4;i++)
		{
			int xx=x+d[i][0]*k;
			int yy=y+d[i][1]*k;
			if(map[x][y]<map[xx][yy] && check(xx,yy))
			ans=max(ans,dfs(xx,yy));
		}
	}
	dp[x][y]=ans+map[x][y];
	return dp[x][y];
}
int main()
{
	int i,j,k;
	while(cin>>n>>m && n!=-1 || m!=-1)
	{
		for(i=0;i<n;i++)
		for(j=0;j<n;j++)
		cin>>map[i][j];
		memset(dp,0,sizeof(dp));
		cout<<dfs(0,0)<<endl;
	}
	return 0;
}