51Nod - 1083 矩阵取数问题 (DP)

1083 矩阵取数问题 

基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题

一个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 <= N[i] <= 10000)

Output

输出能够获得的最大价值。

Input示例

3
1 3 3
2 1 3
2 2 1

Output示例

11

状态转移方程: dp[i][j] = max(dp[i-1][j],dp[i][j-1])+a[i][j];

#include<bits/stdc++.h>
using namespace std;
#define LL long long

const int MAXN = 1e5+10;
const int INF = 0x3f3f3f3f;
const int N= 1010;
const int MOD = 0x3f3f3f3f;


int n,a[N][N];
LL dp[N][N];
int main(){
    while(scanf("%d",&n)!=EOF){
        memset(dp,0,sizeof(dp));
        memset(a,0,sizeof(a));
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                scanf("%d",&a[i][j]);
            }
        }
        dp[0][0] = dp[0][1] = dp[1][0] = 0;
        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];
            }
        }
        printf("%lld\n",dp[n][n]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/l18339702017/article/details/81178603