Picking peanuts (simple memory search)

vjudge submit link

Topic: Picking Peanuts

——Hello Kitty wants to pick some peanuts for her favorite Mickey Mouse. She came to a rectangular peanut field with grid-like roads (pictured below), went in from the northwest corner and came out from the southeast corner. There is a peanut seedling planted at each intersection of roads in the field, with several peanuts on it, and all the peanuts on it can be picked after one peanut seedling. Hello Kitty can only go east or south, not west or north. Ask Hello Kitty how many peanuts can be picked at most.
Insert picture description here

Input ——The
first line is an integer T, which represents how many sets of data there are in total. 1<=T <= 100
Next is T group data.
——The first row of each group of data is two integers, representing the number of rows R and the number of columns C of peanut seedlings (1<= R, C <=100)
——The next R rows of data in each group of data, from Describe each row of peanut seedlings in turn from north to south. Each row of data has C integers, describing the number of peanuts M on each peanut seedling in the row from west to east (0<= M <= 1000).

Output ——For
each set of input data, output one line, the content is the number of peanuts that Hello Kitty can pick the most.

Sample Input
2
2 2
1 1
3 4
2 3
2 3 4
1 6 5

Sample Output
8
16

Problem-solving notes:

记忆化搜索:
先一条路走到底,当走到不能再走时,说明到底了
那么我们就可以求出终点(tx,ty)前一个点(x,y)可以获得的价值,存放到dp[x][y]中。
注意:当走到不能再走时,返回的是终点对应的dp[][]值,其实是0  


为什么最后输出dfs(1,1)+e[1][1] 

当从终点逐步返回到起点后一个点时
dfs(int x,int y),tx,ty
(x,y)是起点,(tx,ty)是起点的后一个点
dp[x][y]=max(dp[x][y],dfs(tx,ty)+e[tx][ty]);
dfs(tx,ty):表示的值是逐步返回的dp值
e[tx][ty]:表示起点后的一个值

再返回就返回到主函数里面了,e[1][1]自始自终未加过。 

Code:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int N=110;
int dp[N][N];
int e[N][N];
int to[2][2]={
   
   {0,1},{1,0}};
int R,C;
int dfs(int x,int y)
{
	if(dp[x][y]!=0)
		return dp[x][y];
	int i,tx,ty;
	for(i=0;i<2;i++)
	{
		tx=x+to[i][0];
		ty=y+to[i][1];
		if(tx>=1&&tx<=R&&ty>=1&&ty<=C)
			dp[x][y]=max(dp[x][y],dfs(tx,ty)+e[tx][ty]);//先走一条路,走到终点求终点前一个可以获得多少价值 
		//不使用book标记的原因是,只可以向下和向右走,没有回头路,除了return; 
	}
	return dp[x][y];
}
int main()
{
	int t,i,j;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d %d",&R,&C);
		for(i=1;i<=R;i++)
			for(j=1;j<=C;j++)
				scanf("%d",&e[i][j]);
		memset(dp,0,sizeof(dp));	
		printf("%d\n",dfs(1,1)+e[1][1]);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/Helinshan/article/details/114803549