CodingKnight's blog

By CodingKnight, 6 months ago, In English

Hello Codeforces Community,

This is an educational blog intended for some newbie and pupil rating members. I assume that members with higher rating and many other members are already aware of its contents. It is well-known that the Time-Limit Exceeded (TLE) Verdict received from the automatic judge in competitive programming contests and practicing using Java language is sometimes not because the computations involved in solving the problem are too time-consuming, but because the data input operations from System.in stream and/or data output operations to System.out stream are not fast enough. The following is a Java 11 simple template for data input-output using InputStreamReader, BufferedReader and BufferedOutputStream library classes.

Fast data input-output in Java

The program declares a queue-based tokens class to parse multiple data items in the same line and push them to the rear of the data queue using LinkedList utility object. The next...() member function, where ... stands for the data-item type, is used to get the next data item from the queue front. Helper functions to_bytes(... x), where ... stands for the data-item type, are declared to convert data item to byte[] array that can be written to the buffered output stream using BufferedOutputStream::write(byte[]) function call. It is always necessary to call the BufferedOutputStream::flush() member function before quitting from the main() function, so as to flush the buffered output stream by sending its contents to System.out.

The following is the main() function has been used for solving 1100C - NN and the Optical Illusion based on this template program.

Example

Note that writing floating-point data items requires an additional format string parameter to specify the number of decimal digits after the decimal floating point.

References

  1. Fast I/O in Java in Competitive Programming

  2. Fast I/O In Java For Competitive Programming

  3. Fast Output in Java

A GitHub.com version of this blog can be found in the following link: Fast data input-output for competitive programming in Java 11.

Your constructive comments and feedback are welcome.

Update

The following is another example for the template program: Submissions for 1600J - Robot Factory which use the same code except for the input-output streams.

  1. TLE at 1000 ms using Scanner and System.out: 136775503

  2. AC with 998 ms using Scanner and BufferedOutputStream: 136775338

  3. AC with 405 ms using BufferedReader and BufferedOutputStream: 136742083

 
 
 
 
  • Vote: I like it
  • +12
  • Vote: I do not like it

»
6 months ago, # |
  Vote: I like it 0 Vote: I do not like it

What's wrong with System.out? Is BufferedOutputStream faster?