一个N*N矩阵中有不同的正整数,经过这个格子,就能获得相应价值的奖励,从左上走到右下,只能向下向右走,求能够获得的最大价值。
例如:3 * 3的方格。
1 3 3
2 1 3
2 2 1
能够获得的最大价值为:11。
思路
同nod1002,将元素按位置分为以下三类考虑:
- 第一行第一个。
- 第一行第2-n个。
- 除第一行外每行第一个。
出口一定是最后一行(仔细思考为什么),最后扫一遍最后一行,输出最大值即可。
代码
import java.io.*;
public class nod1083 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 1 << 16);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out), 1 << 16);
int N = Integer.parseInt(reader.readLine());
String[] s = reader.readLine().split("\\s+");
int[][] f = new int[N][N];
f[0][0] = Integer.parseInt(s[0]);
for(int j = 1; j < N; j++){
f[0][j] = f[0][j - 1] + Integer.parseInt(s[j]);
}
for(int i = 1; i < N; i++){
s = reader.readLine().split("\\s+");
f[i][0] = f[i - 1][0] + Integer.parseInt(s[0]);
for(int j = 1; j < N; j++){
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]) + Integer.parseInt(s[j]);
}
}
writer.write(f[N - 1][N - 1] + "");
writer.flush();
}
}