Java 快速输入输出

输入

Scanner 会使用正则表达式解析输入,而 BufferedReader 直接读取输入,所以 Scanner 更慢。

输出

System.out(类型为 PrintStream)的 autoFlush 属性默认为 True,所以 System.out 更慢。

模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class FastIO extends PrintWriter {
private BufferedReader br;
private StringTokenizer st;

public FastIO() {
this(System.in, System.out);
}

public FastIO(InputStream in, OutputStream out) {
super(out);
br = new BufferedReader(new InputStreamReader(in));
}

public FastIO(String input, String output) throws FileNotFoundException {
super(output);
br = new BufferedReader(new FileReader(input));
}

public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

public int nextInt() {
return Integer.parseInt(next());
}

public double nextDouble() {
return Double.parseDouble(next());
}

public long nextLong() {
return Long.parseLong(next());
}
}

测试

INOUTEST - Enormous Input and Output Test