究极快读快写(fread、fwrite)

· · 个人记录

众所周知,我们可以通过getchar和putchar实现快读快写。

但是,这还不是最快的。我们可以通过fread和fwrite,一次性读写大量信息,达到比普通快读快写更快的速度。本程序参考了 P8353 中提供的快速输入模版。

#include<bits/stdc++.h>
using namespace std;

// 究极快读
namespace fastread {
    const unsigned int S=1<<16;
    char B[S+3],*H,*T;
    inline unsigned int gc() {
        if(H==T) T=(H=B)+fread(B,1,S,stdin);
        return (H==T)?EOF:*H++;
    }
    inline unsigned int read() {
        unsigned int x,ch;
        while((ch=gc())<48);
        x=ch^'0';
        while((ch=gc())>47) x=x*10+(ch^'0');
        return x;
    }
} using fastread::read;

// 究极快写
namespace fastwrite {
    const unsigned int S=1<<16;
    unsigned int cnt;
    char B[S+3];
    inline void write(unsigned int x) {
        if(x>9) write(x/10);
        B[cnt++]=(x%10)|48;
        if(cnt == S){
            fwrite(B,1,S,stdout);
            cnt=0;
        } 
    }
    inline void space() {
        B[cnt++]=32;
        if(cnt == S){
            fwrite(B,1,S,stdout);
            cnt=0;
        } 
    }
    inline void endl() {
        B[cnt++]=10;
        if(cnt == S){
            fwrite(B,1,S,stdout);
            cnt=0;
        } 
    }
    inline void show() {
        fwrite(B,1,cnt,stdout);
        cnt=0;
    }
}using fastwrite::write, fastwrite::space, fastwrite::show;
int main() {









    show();
    return 0;
}

使用 read 函数,可以读取一个 unsigned int

使用 write 函数,可以输出一个 unsigned int

使用 space 函数,可以输出一个空格

使用 endl 函数,可以输出一个换行

使用 show 函数,清空输出缓存区,必须在程序最后执行一次

注:如果测试数据大于 2^{16} ,并且内存充裕,可以将 S 变量调大(也就是可以一次性读写更多的数据)来提升一点速度。