본문 바로가기

C 및 C++

FastIO 템플릿

#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
template<typename T>
struct FASTIO {
    char *p,O[2000000],*d;
    void set() {
        struct stat st;fstat(0,&st);d=O;
        p=(char*)mmap(0,st.st_size,1,1,0,0);
    }
    ~FASTIO() {
        write(1,O,d-O);
    }
    inline T get() {
        T x=0;bool e;p+=e=*p=='-';
        for(;*p==10 or *p==32;p++);
        for(char c=*p++;c&16;x=10*x+(c&15),c=*p++);
        return e?-x:x;
    }
    inline void put(T x) {
        if(d-O+100>2000000) write(1,O,d-O), d=O;
        if(x<0) *d++='-', x=-x;
        char t[16],*q=t;
        do *q++=x%10|48; while(x/=10);
        do *d++=*--q; while(q!=t);
        *d++=10;
    }
};

FASTIO<int> IO;

 

#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#define rf(x) (x)=0;while(*_p<48)_p++;while(47<*_p)(x)=((x)<<3)+((x)<<1)+(*_p++&15);
char *_p;
char O[2000000],*d=O;
void put(int x) {
    if(d-O+100>2000000) write(1,O,d-O);
    char t[16],*q=t;
    do *q++=x%10|48; while(x/=10);
    do *d++=*--q; while(q!=t);
    *d++=10;
}

int main(){
    struct stat st; fstat(0, &st);
    _p = (char*)mmap(0, st.st_size, PROT_READ, MAP_SHARED, 0, 0);    
    write(1,O,d-O);
}

참고 자료

cgiosy : https://cgiosy.github.io/posts/fast-io

jinhan814 : https://blog.naver.com/jinhan814/222440944366