입력
보통 Java에서 입력을 받을때 Scanner, BufferedReader를 사용한다.
그러나 프로그래밍 대회용에서 쓰는 좀더 빠른 입력 방법이 있다.
DataInputStream 을 사용해 입력을 조금 더 빨리 받는거다.
백준같은 문제를 풀때는 BufferedReader 를 주로 사용해야하는데,
FastReader 클래스는 Scanner 같이 nextInt, nextDouble 처럼 입력을 받아야한다.
실제로 BufferedReader로 236ms가 걸렸던 문제가 112ms까지 줄어들었다.
그리고 해당 문제 Java 기준 가장 빠른 성능을 보여주기도 했다.
다만 클래스 정의가 굉장히 길어서 코테를 풀때는 BufferedReader를 계속 사용하면 될듯하고
순위 욕심이 생긴다면 한번 써볼만하다.
아 그리고 출력은 BufferedWriter 또는 StringBuilder를 사용하면 된다.
전체코드 확인하기(클릭)
static class FastReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream inputStream;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader() {
inputStream = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String fileName) throws IOException {
inputStream = new DataInputStream(new FileInputStream(fileName));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
StringBuilder sb = new StringBuilder();
byte c;
while ((c = readByte()) != -1) {
if (c == '\n') {
break;
}
sb.append((char)c);
}
return sb.toString();
}
public int nextInt() throws IOException {
byte c = readNonWhitespaceByte();
boolean isNegative = (c == '-');
if (isNegative) {
c = readByte();
}
int result = 0;
while (c >= '0' && c <= '9') {
result = result * 10 + (c - '0');
c = readByte();
}
return isNegative ? -result : result;
}
public long nextLong() throws IOException {
byte c = readNonWhitespaceByte();
boolean isNegative = (c == '-');
if (isNegative) {
c = readByte();
}
long result = 0;
while (c >= '0' && c <= '9') {
result = result * 10 + (c - '0');
c = readByte();
}
return isNegative ? -result : result;
}
public double nextDouble() throws IOException {
byte c = readNonWhitespaceByte();
boolean isNegative = (c == '-');
if (isNegative) {
c = readByte();
}
double result = 0, div = 1;
while (c >= '0' && c <= '9') {
result = result * 10 + (c - '0');
c = readByte();
}
if (c == '.') {
while ((c = readByte()) >= '0' && c <= '9') {
result += (c - '0') / (div *= 10);
}
}
return isNegative ? -result : result;
}
private void fillBuffer() throws IOException {
bytesRead = inputStream.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte readByte() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
private byte readNonWhitespaceByte() throws IOException {
byte c;
do {
c = readByte();
} while (c <= ' ');
return c;
}
}
매크로
만약 인텔리제이를 사용한다면 라이브 템플릿에서 매크로로 저장할 수 있다.
(다른 에디터도 비슷하게 저장해서 쓰면 될거같다.)
참고
The most insightful stories about Competitive Programming - Medium
'Algorithm' 카테고리의 다른 글
[이분탐색] java lower bound, upper bound (0) | 2023.12.11 |
---|