1074: Matrix access II

Title Description

PIPI want everyone to understand the basic dynamic programming, so it does not know where did you get an n * m matrix, each element of the matrix is an integer, you are now in the upper left corner (first row, first column), each You can only come to the right or at the adjacent position, not out of the matrix. Traveled as a sum of the number of your score. Now PIPI want to know it to each grid of maximum score is how much?
How, it is still not very simple?

Entry

Multiple sets of input. 
The first two acts of integers n, m (1 <= n  , m <= 500)
the next n lines of m numbers, each number within the range int. (¯ ▽ ¯) " 

Export

For each test, an output n * m matrix.

Sample input

3 4
1 2 3 4 
1 2 8 2
1 1 1 1

Sample Output

1 3 6 10
2 5 14 16
3 6 15 17
#include<iostream>
using namespace std;
int main(void){
	int n,m;
	while(scanf("%d%d",&n,&m)!=EOF){
		//存储二维矩阵 
		int f[501][501];
		for(int i=1;i<=n;i++){
			for(int j=1;j<=m;j++){
				scanf("%d",&f[i][j]);
			}
		}
		long long dp[501][501];
		//开始位置 
		dp[1][1]=f[1][1];
		//第一列初始化 
		for(int i=2;i<=n;i++){
			dp[i][1]=dp[i-1][1]+f[i][1];
		}
		//第一行初始化 
		for(int j=2;j<=m;j++){
			dp[1][j]=dp[1][j-1]+f[1][j];
		}
		//其他位置计算 
		for(int i=2;i<=n;i++){
			for(int j=2;j<=m;j++){
				dp[i][j]=max(dp[i][j-1],dp[i-1][j])+f[i][j];
			}
		}
		for(int i=1;i<=n;i++){
			for(int j=1;j<m;j++){
				printf("%lld ",dp[i][j]);
			}
			printf("%lld\n",dp[i][m]);
		} 
	}
	return 0;
}

 

Published 48 original articles · won praise 2 · Views 2466

Guess you like

Origin blog.csdn.net/Do_________/article/details/104115653