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 a_{ij}
(-100<=a_{ij}<=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,只要注意边界问题就好了。
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<vector>
#include<cstring>
#include<string>
using namespace std;
typedef long long LL;
const int maxn = 1e3 + 5;
int T, n, m, f[maxn][maxn], a[maxn][maxn];
int main(){
//scanf("%d", &T);
while (~scanf("%d%d", &n, &m))
{
n++; m++;
memset(f, -1, sizeof(f));
for (int i = 2; i <= n;i++)
for (int j = 2; j <= m; j++) scanf("%d", &a[i][j]);
f[2][2] = a[2][2];
int ans = 0;
for (int i = 2; i <= n; i++)
{
for (int j = 2; j <= m; j++)
{
if (f[i - 1][j] >= 0) f[i][j] = max(f[i][j], f[i - 1][j] + a[i][j]);
if (f[i][j - 1] >= 0) f[i][j] = max(f[i][j], f[i][j - 1] + a[i][j]);
if (f[i - 1][j - 2] >= 0) f[i][j] = max(f[i][j], f[i - 1][j - 2] + a[i][j]);
if (f[i - 2][j - 1] >= 0) f[i][j] = max(f[i][j], f[i - 2][j - 1] + a[i][j]);
ans = max(ans, f[i][j]);
}
}
printf("%d\n", ans);
}
return 0;
}