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
先说一下题意:有一个n*n的地图,这个地图中的每一个点都有权值,要求从(0,0)点开始找一条路径,这条路径的权值要求是递增的,每次都可以在水平或者垂直方向移动不超过k个位置,然后输出最大的路径权值
思路:刚开始以为是最长上升子序列的变形,但是仔细想想二维还带方向,怎么跟dfs差不多,但就是没办法实现,看了别人的题解之后才知道是dfs与dp的结合;
dfs肯定就是搜索路径的,dp是干什么的?-----记忆化搜索;直接暴力搜索这样一条条路径肯定会爆,但是仔细想一想,走过的路径上的权值是可以进行保存的,既然能够保存那就可以进行优化,将这些值用DP数组存下来,那么这样就可以记忆化搜索了
具体情况看代码就好:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define init(a,b) memset(a,b,sizeof a)
int dp[200][200];
int a[200][200];
int n,k;
int xx[]={0,-1,0,1};//路径dfs用的,这里就不用多说了
int yy[]={1,0,-1,0};
bool check(int i,int j)//判断是否越界
{
if(i<0||i>=n||j<0||j>=n)
return false;
return true;
}
int dfs(int x,int y)
{
int ans=0;
if(!dp[x][y])//搜索过程发现走过了,那就不需要再继续搜索了
{
rep(l,0,3)
{
rep(p,1,k)//这层for循环是为了再水平还是垂直方向的移动单位
{
int i=x+xx[l]*p;
int j=y+yy[l]*p;
if(check(i,j)&&a[i][j]>a[x][y])
{
int temp=dfs(i,j);
ans=max(temp,ans);
}
}
}
dp[x][y]=ans+a[x][y];
}
return dp[x][y];//不是递归结束,而是返回上一步;
}
int main()
{
while(scanf("%d%d",&n,&k)!=EOF)
{
if(n==-1||k==-1) break;
rep(i,0,n-1)
rep(j,0,n-1)
scanf("%d",&a[i][j]);
init(dp,0);
printf("%d\n",dfs(0,0));
}
return 0;
}