Description
Dreams of finding lost treasure almost came true recently. A new machine called 'The Revealer' has been invented and it has been used to detect gold which has been buried in the ground. The machine was used in a cave near the seashore where – it is said – pirates used to hide gold. The pirates would often bury gold in the cave and then fail to collect it. Armed with the new machine, a search party went into the cave hoping to find buried treasure. The leader of the party was examining the soil near the entrance to the cave when the machine showed that there was gold under the ground. Very excited, the party dug a hole two feel deep. They finally found a small gold coin which was almost worthless. The party then searched the whole cave thoroughly but did not find anything except an empty tin trunk. In spite of this, many people are confident that 'The Revealer' may reveal something of value fairly soon.
So,now you are in the point




(1,1) and initially you have 0 gold.In the
n*
m grid there are some traps and you will lose gold.If your gold is not enough you will be die.And there are some treasure and you will get gold.If you are in the point(x,y),you can only walk to point
























(x+1,y),(x,y+1),(x+1,y+2)and








(x+2,y+1).Of course you can not walk out of the grid.Tell me how many gold you can get most in the trip.
It`s guarantee that




(1,1)is not a trap;
Input
first come
2 integers,


n,m(







1≤n≤1000,







1≤m≤1000)
Then follows
n lines with
m numbers

aij













(−100<=aij<=100)
the number in the grid means the gold you will get or lose.
Output
print how many gold you can get most.
Sample Input
3 3
1 1 1
1 -5 1
1 1 1
3 3
1 -100 -100
-100 -100 -100
-100 -100 -100
Sample Output
5
1
后来看了别人的题解,才明白用dp。由于还没学dp所以在看了几篇题解后,才理解别人的dp是怎么用的。
注:dp数组存放的是从(1,1)到当前所在坐标所搜集的金币的总和 。且由题意可知从(1,1)到当前坐标的金币总和为负数时,当前点就成死点,不能继续往下走了。
My solution:
/*2016.3.23*/
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int map[1010][1010],dp[1010][1010],n,m,b[4]={1,0,1,2},d[4]={0,1,2,1};
int main()
{
int i,j,tx,ty,k,ans;
while(scanf("%d%d",&n,&m)==2)
{
ans=0;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&map[i][j]);
if(map[1][1]<0)//当起点为负时,直接输出0,不能继续走了,因为初始时,金币为0
;
else
{
memset(dp,-1,sizeof(dp));//初始化为-1,因为当dp值为0时,还可以继续往下走。-1则表示不能继续走的死点
dp[1][1]=ans=map[1][1];
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
if(dp[i][j]>=0)//选择金币总和不小于0的坐标,,继续往下走
{
for(k=0;k<4;k++)
{
tx=i+b[k];
ty=j+d[k];
if(tx>n||ty>m)
continue ;
//if(map[tx][ty]>=0)//不能加该条判断,虽然当前坐标自身金币为负,
// { 但从(1,1)到当前坐标金币总和却不一定小于0,因此还有可能继续往下走
dp[tx][ty]=max(dp[tx][ty],dp[i][j]+map[tx][ty]);//更新起点到当前点的坐标的金币总和
ans=max(ans,dp[tx][ty]);//更新最大值
//}
}
}
}
}
printf("%d\n",ans);
}
return 0;
}

本文介绍了一个基于动态规划的寻宝游戏算法实现。玩家在一个网格中寻找宝藏,避开陷阱,目标是在遵循特定移动规则的情况下获得最多的金币。文章通过一个具体示例展示了如何使用动态规划解决此问题,并提供了一段C++代码作为解决方案。
449

被折叠的 条评论
为什么被折叠?



