MLE了求助!!

P1216 [USACO1.5] [IOI1994]数字三角形 Number Triangles

edward_0112 @ 2022-03-13 10:09:11

import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    static int INF = Integer.MIN_VALUE;

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] mp = new int[n+10][n+10];
        int[][] dp = new int[n+10][n+10];
        for(int i = 1; i <= n ; i++){
            for(int j = 1 ; j <= i ; j++){
                mp[i][j] = sc.nextInt();
            }
        }
        for(int i = n ; i >= 1 ; i--){
            for(int j = 1 ; j <= i ; j++){
                if( i == 1 ){
                    dp[i][j] = mp[i][j];
                }
                dp[i][j] = Math.max(dp[i+1][j] , dp[i+1][j+1])+ mp[i][j];
            }
        }
        System.out.println(dp[1][1]);

    }
}

by abcbalabala @ 2022-05-03 22:15:28

我也是用Java写的


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int r=sc.nextInt();
        int[][] rr=new int[r+2][r+2];
        for (int i = 1; i <= r ; i++) {
            for (int j = 1; j <= i; j++) {
                rr[i][j]=sc.nextInt();
            }
        }
        sc.close();
        for (int i = r; i >=1; i--) {
            for (int j = 1; j <= r; j++) {
                rr[i][j]=Math.max(rr[i+1][j], rr[i+1][j+1])+rr[i][j];
            }
        }
        System.out.println(rr[1][1]);
    }
}

我也不知道为什么,同样的算法,Java比其他语言占用的内存大了好多。这应该是这题的最优解了,但是最后一个点却还是是擦边过的。内存限制125MB,我这是124MB.


|