题目描述
设有 n×m 的方格图,每个方格中都有一个整数。现有一只小熊,想从图的左上角走到右下角,每一步只能向上、向下或向右走一格,并且不能重复经过已经走过的方格,也不能走出边界。小熊会取走所有经过的方格中的整数,求它能取到的整数之和的最大值。
输入
第一行有两个整数 n,m。
接下来 n 行每行 m 个整数,依次代表每个方格中的整数。
输出
一个整数,表示小熊能取到的整数之和的最大值。
样例 1
样例输入 1
3 4
1 -1 3 2
2 -1 4 -1
-2 2 -3 -1
样例输出 1
9
样例 2
样例输入 2
2 5
-1 -1 -3 -2 -7
-2 -1 -4 -1 -2
样例输出 2
-10
数据规模
对于 20% 的数据,n,m≤5。
对于 40% 的数据,n,m≤50。
对于 70% 的数据,n,m≤300。
对于 100% 的数据,1 <= m,n <= 10^3。方格中整数的绝对值不超过10^4 。
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int inf = 0x3f3f3f3f;
int N, M;
int a[1005][1005];
int dp[1005][1005];
void quickinput()
{
#if 1
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
#endif
}
signed main()
{
quickinput();
freopen("number.in", "r", stdin);
freopen("number.out", "w", stdout);
cin >> N >> M;
for(int i=1; i<=N; i++)
{
for(int j=1; j<=M; j++)
{
cin >> a[i][j];
}
}
memset(dp, -inf, sizeof(dp)); dp[1][1] = a[1][1];
for(int j=1; j<=M; j++)
{
for(int i=1; i<=N; i++)
{
if(i==1 && j==1) continue;
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + a[i][j];
}
int temp = -inf;
for(int i=N; i>=1; i--)
{
if(i==1 && j==1) continue;
temp = max(temp, dp[i][j-1]) + a[i][j];
dp[i][j] = max(dp[i][j], temp);
}
}
cout << dp[N][M] << endl;
return 0;
}