一个N*N矩阵中有不同的正整数,经过这个格子,就能获得相应价值的奖励,从左上走到右下,只能向下向右走,求能够获得的最大价值。
例如:3 * 3的方格。
1 3 3
2 1 3
2 2 1
能够获得的最大价值为:11。
Input
第1行:N,N为矩阵的大小。(2 <= N <= 500)
第2 - N + 1行:每行N个数,中间用空格隔开,对应格子中奖励的价值。(1 <= Nii <= 10000)
Output
输出能够获得的最大价值。
Sample Input
3
1 3 3
2 1 3
2 2 1
Sample Output
11
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 505;
int a[MAXN][MAXN];
int dp[MAXN][MAXN];
int n, m;
int main() {
while (scanf ("%d", &n) != EOF) {
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
scanf ("%d", &a[i][j]);
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j) {
dp[i][j] = max (dp[i-1][j], dp[i][j-1]) + a[i][j];
}
cout << dp[n][n] << endl;
}
return 0;
}