Algorithm

[입출력] Java FastIO For Competitive programming

shininghyunho 2024. 4. 19. 16:22

입력

보통 Java에서 입력을 받을때 Scanner, BufferedReader를 사용한다.

그러나 프로그래밍 대회용에서 쓰는 좀더 빠른 입력 방법이 있다.

DataInputStream 을 사용해 입력을 조금 더 빨리 받는거다.

 

백준같은 문제를 풀때는 BufferedReader 를 주로 사용해야하는데,

FastReader 클래스는 Scanner 같이 nextInt, nextDouble 처럼 입력을 받아야한다.

 

실제로 BufferedReader로 236ms가 걸렸던 문제가 112ms까지 줄어들었다.

그리고 해당 문제 Java 기준 가장 빠른 성능을 보여주기도 했다.

 

다만 클래스 정의가 굉장히 길어서 코테를 풀때는 BufferedReader를 계속 사용하면 될듯하고

순위 욕심이 생긴다면 한번 써볼만하다.

 

아 그리고 출력은 BufferedWriter 또는 StringBuilder를 사용하면 된다.

코드

static class FastReader {
        private static final int LINE_MAX_LENGTH=1<<10; // readLine 최대 길이
        private static final int BUFFER_SIZE=1<<16;
        private final DataInputStream din;
        private final byte[] buffer;
        private int bufferPointer, bytesRead;
        public FastReader() {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }
        public FastReader(String file_name) throws IOException {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }
        public String readLine() throws IOException {
            byte[] buf = new byte[LINE_MAX_LENGTH];
            int cnt = 0, c;
            while ((c = read()) != -1) {
                if (c == '\n') break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }
        public int nextInt() throws IOException {
            int ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) return -ret;
            return ret;
        }
        public long nextLong() throws IOException {
            long ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) return -ret;
            return ret;
        }
        public double nextDouble() throws IOException {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
            if (neg) return -ret;
            return ret;
        }
        private void fillBuffer() throws IOException {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1) buffer[0] = -1;
        }
        private byte read() throws IOException {
            if (bufferPointer == bytesRead) fillBuffer();
            return buffer[bufferPointer++];
        }
        public void close() throws IOException {
            din.close();
        }
    }

 

매크로

만약 인텔리제이를 사용한다면 라이브 템플릿에서 매크로로 저장할 수 있다.

(다른 에디터도 비슷하게 저장해서 쓰면 될거같다.)

참고

The most insightful stories about Competitive Programming - Medium

'Algorithm' 카테고리의 다른 글

[이분탐색] java lower bound, upper bound  (0) 2023.12.11