Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

multidimensional array - Memory Limit Exceeded : When using Java Scanner

Problem :

standard input/output: 2s/128000 kB

You are given a chessboard of size N x N, where the top left square is black. Each square contains a value. Find the sum of values of all black square and all white squares.

1 <= N <= 1000

Solution 1: Now when I am using Scanner to take the input, it is throwing memory limit exceeded for one test case

Scanner sc = new Scanner(System.in);
long n = sc.nextLong();

long wsum = 0;
long bsum = 0;

for(int i=0; i<n; i++) {
    for(int j=0; j<n; j++) {
        if((i+j)%2 != 0 ) {
            wsum = wsum + sc.nextLong();
        } 
        else {
            bsum = bsum + sc.nextLong();
        }
    }
}

Solution 2: When I am using the BufferedReader all test cases are passing

BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        
int N = Integer.parseInt(read.readLine());
        
int mat[][] = new int[N][N];
for(int i = 0; i < N; i++){
      String str[] = read.readLine().trim().split(" ");
      for(int j = 0; j < N; j++)
          mat[i][j] = Integer.parseInt(str[j]);            
}

long sum =0, sum1 = 0;
for(int i = 0; i < N; i++)
{
    for(int j = 0; j < N; j++)
    {
         if((i+j)%2 == 0)
             sum += mat[i][j];
         else sum1 += mat[i][j];
    }
            
}

Now I know BufferedReader is efficient while reading file but that should throw time limit exceeded.

I would like to understand how BufferedReader is making this program more memory efficient as compared to Scanner class.

question from:https://stackoverflow.com/questions/65903521/memory-limit-exceeded-when-using-java-scanner

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...