import java.io.IOException;
import java.util.Scanner;
public class P1216_数字三角形_DP_原版 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] dp = new int[n + 1][n + 1];
int t;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
t = sc.nextInt();
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1]) + t;
}
}
int res = 0;
for (int i = 1; i <= n; i++) {
res = Math.max(res,dp[n][i]);
}
System.out.println(res);
}
}
先用DP,结果由于Java本身的内存占用大,不能AC:
现在进行输入优化:
来自:数字三角形 Number Triangles(java的MLE解决办法) - 吐司奶猫荷包蛋 - 博客园 (cnblogs.com)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class P1216_数字三角形_DP {
public static void main(String[] args) throws IOException {
InputReader in = new InputReader(System.in);
int n = in.nextInt();
int[][] dp = new int[n + 1][n + 1];
int t;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
t = in.nextInt();
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1]) + t;
}
}
int res = 0;
for (int i = 1; i <= n; i++) {
res = Math.max(res, dp[n][i]);
}
System.out.println(res);
}
static class InputReader {
BufferedReader br;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public int nextInt() throws IOException {
int c = br.read(); // 从输入流中读取一个字符的 ASCII 码,并将其存储在变量c中
while (c <= 32) { //跳过输入流中的空白字符
c = br.read();
}
boolean negative = false; // 负号
if (c == '-') {
negative = true;
c = br.read();
}
int x = 0;
while (c > 32) {
x = x * 10 + c - '0';
c = br.read();
}
return negative ? -x : x;
}
public long nextLong() throws IOException {
int c = br.read();
while (c <= 32) {
c = br.read();
}
boolean negative = false;
if (c == '-') {
negative = true;
c = br.read();
}
long x = 0;
while (c > 32) {
x = x * 10 + c - '0';
c = br.read();
}
return negative ? -x : x;
}
public String next() throws IOException {
int c = br.read();
while (c <= 32) {
c = br.read();
}
StringBuilder sb = new StringBuilder();
while (c > 32) {
sb.append((char) c);
c = br.read();
}
return sb.toString();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
快了近2倍不止,而且解决了空间占用