Input / Output
REFERNCE:~
- general/fast-io?lang=java
- general/io?lang=java
Best Template
import java.io.*;
import java.util.*;
public class Main {
//BeginCodeSnip{Kattio}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() { this(System.in, System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(new FileWriter(problemName + ".out"));
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) { }
return null;
}
public int nextInt() { return Integer.parseInt(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public long nextLong() { return Long.parseLong(next()); }
}
//EndCodeSnip
// add methods
// add methods
public static void main(String[] args) {
Kattio io = new Kattio();
// long x = io.nextLong(); String str = io.next(); int a = io.nextInt();
// io.println(x); /* For System.out.println() */ or // io.print(x);
// Code
io.close(); // make sure to include this line -- closes io and flushes the output
}
}
Explanatory Template same as above
/** Simple yet moderately fast I/O routines.
*
* Example usage:
*
* Kattio io = new Kattio();
*
* while (io.hasMoreTokens()) {
* int n = io.nextInt();
* double d = io.nextDouble();
* double ans = d*n;
*
* io.println("Answer: " + ans);
* }
*
* io.close();
*
*
* Some notes:
*
* - When done, you should always do io.close() or io.flush() on the
* Kattio-instance, otherwise, you may lose output.
*
* - The nextInt(), nextDouble(), and nextLong() methods will throw an
* exception if there is no more data in the input, so it is generally
* a good idea to use hasMoreTokens() to check for end-of-file.
*
* @author: Kattis
*/
import java.util.*;
import java.io.*;
class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st = new StringTokenizer("");
private String token;
// standard input
public Kattio() {
this(System.in, System.out);
}
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(new FileWriter(problemName + ".out"));
r = new BufferedReader(new FileReader(problemName + ".in"));
}
private String peek() {
if (token == null)
try {
while (!st.hasMoreTokens()) {
String line = r.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
public boolean hasMoreTokens() {
return peek() != null;
}
private String next() {
String ans = peek();
token = null;
return ans;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
public class Main {
static Kattio io = new Kattio();
public static void main(String[] args) {
int a = io.nextInt();
int b = io.nextInt();
int c = io.nextInt();
io.print("sum is ");
io.println(a + b + c);
io.close(); // make sure to include this line -- closes io and flushes the output
}
}
BufferedReader
and PrintWriter
These are faster because they buffer the input and output and handle it all at
once as opposed to parsing each line individually. However, BufferedReader
is
harder to use than Scanner
. It has quite a few more methods and the io
library must be imported for its use as well. A
StringTokenizer
is used to split the input line by whitespace into tokens, which are then
accessed individually by the nextToken()
method.
import java.io.*;
import java.util.StringTokenizer;
public class Main {
static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
StringTokenizer st = new StringTokenizer(r.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
pw.print("sum is ");
pw.println(a + b + c);
pw.close(); // make sure to include this line -- closes io and flushes the output
}
}
Example - BufferedReader
and PrintWriter
import java.io.*;
import java.util.StringTokenizer;
public class Main {
static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
long x = Long.parseLong(r.readLine());
while (x != 1) {
System.out.print(x+" ");
if (x%2 == 0) x /= 2;
else x = 3*x+1;
}
pw.println(x);
pw.close(); // make sure to include this line -- closes pw and flushes the output
}
}
Method 1 - Scanner
Probably the easiest way to read input in Java, though it is also extremely slow.
"3188ms"
import java.util.*;
import java.io.*;
public class roboherd_scanner {
static int P[][] = new int[100000][];
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("roboherd.in"));
PrintWriter pw = new PrintWriter(new FileWriter("roboherd.out"));
int N = sc.nextInt();
int K = sc.nextInt();
for(int i = 0; i < N; ++i) {
int M = sc.nextInt(); P[i] = new int[M];
for(int j = 0; j < M; ++j) P[i][j] = sc.nextInt();
}
if(N == 3) pw.println(61);
else pw.println(1000000000000000000L);
pw.close();
}
}
Method 2 - BufferedReader
and .split()
BufferedReader
reads line-by-line with the .readLine()
method, which returns
a string. Methods like Integer.parseInt()
are used to convert strings into
primitives, and they can directly convert a line into a number, like in
Integer.parseInt(br.readLine())
.
Reading input is more complicated when multiple, space-separated values are
placed in a single line. In order to individually read the values in each line,
the programmer usually uses the .split()
method in String
.
"1209ms"
import java.util.*;
import java.io.*;
public class roboherd_buffered_reader_string_split {
static int P[][] = new int[100000][];
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("roboherd.in"));
PrintWriter pw = new PrintWriter(new FileWriter("roboherd.out"));
String[] tokens = br.readLine().split(" ");
int N = Integer.parseInt(tokens[0]);
int K = Integer.parseInt(tokens[1]);
for(int i = 0; i < N; ++i) {
tokens = br.readLine().split(" ");
int M = Integer.parseInt(tokens[0]); P[i] = new int[M];
for(int j = 0; j < M; ++j) P[i][j] = Integer.parseInt(tokens[j+1]);
}
if(N == 3) pw.println(61);
else pw.println(1000000000000000000L);
pw.close();
}
}
Method 3 - BufferedReader
and StringTokenizer
Notice that StringTokenizer
's .nextToken()
for splitting strings is slightly
faster than .split()
.
"986ms"
import java.util.*;
import java.io.*;
public class roboherd_buffered_reader_string_tokenizer {
static int P[][] = new int[100000][];
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("roboherd.in"));
PrintWriter pw = new PrintWriter(new FileWriter("roboherd.out"));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
for(int i = 0; i < N; ++i) {
st = new StringTokenizer(br.readLine());
int M = Integer.parseInt(st.nextToken()); P[i] = new int[M];
for(int j = 0; j < M; ++j) P[i][j] = Integer.parseInt(st.nextToken());
}
if(N == 3) pw.println(61);
else pw.println(1000000000000000000L);
pw.close();
}
}
As Kattio
is just a wrapper around
BufferedReader
and PrintWriter
, it performs similarly. This method is
usually fast enough and doesn't require too much typing, so we recommend that
you go with this.
Method 4 - BufferedReader
and StreamTokenizer
Apparently this is even faster! Though properly reading in long
s would require
additional work (since they are interpreted as double
s by default).
"569ms"
import java.util.*;
import java.io.*;
public class roboherd {
static int P[][] = new int[100000][];
static StreamTokenizer in;
static int nextInt() throws IOException{
in.nextToken();
return (int)in.nval;
}
public static void main(String[] args) throws Exception {
in = new StreamTokenizer(new BufferedReader(new FileReader("roboherd.in")));
PrintWriter pw = new PrintWriter(new FileWriter("roboherd.out"));
int N = nextInt();
int K = nextInt();
for(int i = 0; i < N; ++i) {
int M = nextInt(); P[i] = new int[M];
for(int j = 0; j < M; ++j) P[i][j] = nextInt();
}
if(N == 3) pw.println(61);
else pw.println(1000000000000000000L);
pw.close();
}
}
Method 5 - InputStream
Even faster than BufferedReader
is a custom-written Fast I/O class that reads
bytes directly from an InputStream
, similarly as FastIO.h
in the C++
section.
"382ms"
Based off several sources, including Kattio
,
this, and
this.
import java.io.*;
import java.util.*;
//BeginCodeSnip{FastIO}
class FastIO extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1<<16];
private int curChar, numChars;
// standard input
public FastIO() { this(System.in,System.out); }
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c; do { c = nextByte(); } while (c <= ' ');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');
return res.toString();
}
public int nextInt() { // nextLong() would be implemented similarly
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() { return Double.parseDouble(next()); }
}
//EndCodeSnip
public class Main {
static int P[][] = new int[100000][];
public static void main(String[] args) throws Exception {
// String s = "roboherd";
// FastIO io = new FastIO(s+".in",s+".out");
FastIO io = new FastIO("roboherd.in","roboherd.out");
int N = io.nextInt();
int K = io.nextInt();
for(int i = 0; i < N; ++i) {
int M = io.nextInt(); P[i] = new int[M];
for(int j = 0; j < M; ++j) P[i][j] = io.nextInt();
}
if(N == 3) io.println(61);
else io.println(1000000000000000000L);
io.close();
}
}
Apparently, replacing line 64 with lines 62 and 63 results in a slowdown of ~100ms.