본문 바로가기

C++/함수 및 클래스 창고

[백준] fread 사용법

입력을 받기 위한 cin의 호출 횟수가 100만개를 넘어가기 시작하면 입력을 받는 행위 자체만으로도 상당한 시간이 걸리게 된다. 이럴 땐 fread를 통하여 입력버퍼 접근 횟수를 줄여서 속도를 개선시킬 수 있다.

 

다음과 같은 FastInput 클래스를 만들어 두었다.

사용하고 싶은 곳에 선언한 후 기존의 cin을 사용하듯 fin을 사용하면 된다.

 

필요 헤더
#include <cstdio>
#include <ciso646>

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
42
43
44
45
46
47
48
49
50
51
class FastInput {
    int size;
    char* buf;
    int idx;
 
public:
    FastInput() {
        size = 1000000;
        buf = new char[size];
        fread(buf, 1size, stdin);
        idx = 0;
    }
    ~FastInput() {
        delete[] buf;
    }
 
private:
    char Read() {
        if (idx == size) {
            fread(buf, 1size, stdin);
            idx = 0;
        }
        return buf[idx++];
    }
 
public:
    FastInput& operator>>(int& value) {
        value = 0;
        bool negative = false;
 
        char ch;
        do {
            ch = Read();
            if (ch == '-') {
                negative = true;
                ch = Read();
                break;
            }
        } while (not ('0' <= ch and ch <= '9'));
        do {
            value = (value * 10+ (ch - '0');
            ch = Read();
        } while ('0' <= ch and ch <= '9');
 
        if (negative) {
            value *= -1;
        }
        return *this;
    }
};
 
cs

 

다음과 같이 호출할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void Input() {
    FastInput fin;
 
    fin >> n >> r;
    maxLevel = n;
    n = int(pow(2, maxLevel));
 
    for (int y = 0; y < n; y++) {
        for (int x = 0; x < n; x++) {
            fin >> matrix[src][y][x];
        }
    }
 
    for (int i = 0; i < r; i++) {
        fin >> ops[i].first >> ops[i].second;
    }
}
 
cs

'C++ > 함수 및 클래스 창고' 카테고리의 다른 글

Split  (0) 2020.10.10