https://koitp.org/problem/WASTE/read/
package info.frady.dp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
题目
有一座N*N网格组成的城市,这个城市到处是废纸
起点从最左侧1,1开始,到最右下面的N,N
每次移动的方向只有相邻的右侧和下放的格子,在起点和终点的废纸也能捡到
输入:
第一行为城市的大小N(2<=N<=200)
从第二行起,每行有N个数字,每个数字代表废纸的数量
输入:
能见到的最大废纸量
4
1 0 1 7
2 0 2 0
0 2 2 1
1 3 3 2
13
*/
public class 捡废纸 {
public static void main(String[] args) throws Exception{
BufferedReader reader=new BufferedReader(new InputStreamReader((System.in)));
int N=Integer.parseInt(reader.readLine());
int[][] P=new int[N][N];//废纸的状态
int[][] R=new int[N][N];//结果状态
for (int i = 0; i <N; i++) {
String str=reader.readLine();
String[] sarr=str.split(" ");
for (int j = 0; j < N; j++) {
P[i][j]=Integer.parseInt(sarr[j]);
}
}
R[0][0]=P[0][0];
for (int i = 0; i < N; i++) {
for (int j = 0; j <N ; j++) {
int l=0;//左侧的数字
int u=0;//上面的数字
if(j-1>=0){
l=R[i][j-1];//左侧
}
if(i-1>=0){
u=R[i-1][j];//上方
}
R[i][j]=Integer.max(l,u)+P[i][j];
}
}
reader.close();
System.out.println(R[N-1][N-1]);
}
}
这个题目,最大的是200,所以数组不会开太大。
如果数据量比较大的话,其实中间过程也不用存储,只保存两行节省下内存就可以了。