51nod1083 矩阵取数问题 简单dp

矩阵取数问题

一个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

思路:很基础的一道dp,有点像三角形求走的最大和,我们假设dp[ i ] [j ]表示走到位置( i , j )所获得的最大值

那么dp[ i ][ j ] = max ( dp[ i - 1][ j ],dp[ i ][ j - 1] ) + maze[ i ][ j ] (表示矩阵的位置)

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#define ll long long
#define inf 0x3f3f3f3f
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
const int maxn = 520;
int a[maxn][maxn],dp[maxn][maxn];
int main()
{
	int n;
	scanf("%d",&n);
	for (int i = 0;i < n;i ++)
		for (int j = 0;j < n;j ++)
			scanf("%d",&a[i][j]);
	dp[0][0] = a[0][0];
	for (int i = 1;i < n;i ++)
		dp[0][i] = a[0][i] + dp[0][i - 1],dp[i][0] = a[i][0] + dp[i - 1][0];
	for (int i = 1;i < n;i ++)	
		for (int j = 1;j < n;j ++)
		{
			dp[i][j] = max(dp[i][j - 1],dp[i - 1][j]) + a[i][j];
		}
	printf("%d\n",dp[n - 1][n - 1]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cloudy_happy/article/details/81592024