2
\$\begingroup\$

My java code for CSES Introductory problem Number Spiral gives TLE for large inputs, like

Input :

100000
170550340 943050741
121998376 943430501
689913499 770079066
586095107 933655238 ...
(First line/number being the number of inputs)

My code is as below:

import java.util.*;
public class numberSpiral {
 public static void main(String[] args) {
 Scanner scanner = new Scanner(System.in);
 long testN = scanner.nextLong();
 long r=0,c=0;
 while(testN-- > 0){
 r = scanner.nextLong();
 c = scanner.nextLong();
 if (c > r) {
 if (c % 2 == 0) {
 System.out.println(((c - 1) * (c - 1)) + 1 + (r - 1));
 } else
 System.out.println(((c) * (c)) - (r - 1));
 } else {
 if(r % 2 == 0){
 System.out.println(((r) * (r)) - (c - 1));
 } else
 System.out.println(((r - 1) * (r - 1)) + 1 + (c - 1));
 }
 }
 }
}

It works for small inputs. I can't figure out how to optimize it better to reduce time. Time limit is: 1.00 s

Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges202 bronze badges
asked Feb 21, 2021 at 17:41
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

I assume you refer to https://cses.fi/problemset/task/1071/ . Your Algorithm itself is fine as far is i can tell.

The Problem is the large amount of inputs that need to need to be read(Testcases=100000), which Scanner cant provide within the 1s time limit. A BufferedReader should offer the performance needed for this.(See https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/ for more information). The same might apply to System.out.println in which case it would be better to use a BufferedWriter

answered Feb 21, 2021 at 23:17
\$\endgroup\$
0
\$\begingroup\$

usually calculation is faster than branching, so you may also try this:

 if (c > r) {
 int even = c % 2
 System.out.println(((c - 1*even) * (c - 1*even)) + 1*even + (r - 1));
 } else {
 int odd = 1-(r % 2)
 System.out.println(((r - 1*odd) * (r - 1*odd)) + 1*odd + (c - 1));
 }
answered Feb 22, 2021 at 19:00
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.