快读快写模板 (缓冲区)

前言

在一些算法题中输入输出的数据可能达到 1 0 7 10^7 107的范围,此时用scanfprintf的时间将大大超过一秒,此时需要使用快速读入和快速输出的方法(下文简称快读快写)。即使输入输出数据量中等,使用快读和快写也可以延长程序的计算时间,如果写的是暴力算法就可能能过更多的点。

代码

namespace FastIO {
    char buf[1 << 21], buf2[1 << 21], a[20], *p1 = buf, *p2 = buf, hh = ' ';
    int p, p3 = -1;
    void read() {}
    void print() {}
    inline int getc() {
        return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++;
    }
    inline void flush() {
        fwrite(buf2, 1, p3 + 1, stdout), p3 = -1;
    }
    template <typename T, typename... T2>
    inline void read(T &x, T2 &...oth) {
        int f = 0;
        x = 0;
        char ch = getc();
        while (!isdigit(ch)) {
            if (ch == '-')
                f = 1;
            ch = getc();
        }
        while (isdigit(ch)) {
            x = x * 10 + ch - 48;
            ch = getc();
        }
        x = f ? -x : x;
        read(oth...);
    }
    template <typename T, typename... T2>
    inline void print(T x, T2... oth) {
        if (p3 > 1 << 20)
            flush();
        if (x < 0)
            buf2[++p3] = 45, x = -x;
        do {
            a[++p] = x % 10 + 48;
        } while (x /= 10);
        do {
            buf2[++p3] = a[p];
        } while (--p);
        buf2[++p3] = hh;
        print(oth...);
    }
}  // namespace FastIO
#define read FastIO::read
#define print FastIO::print
#define flush FastIO::flush

使用方法

该方法通过开辟内存缓冲区,一次性读入、写入大量数据,极大提升了读写速度。

读入数组示例:

for(int i = 0; i < n; ++ i){
    read(a[i]); // scanf("%d", &a[i])
}

输出数组示例:

for(int i = 0; i < n; ++ i){
    print(a[i]);
}
flush();

注意,在输出结果的最后一定要加一个flush。因为该print函数只是把内容送入缓冲区,缓冲区满了之后会自动写入,但是最后一次缓冲区中可能会留下部分数据,需要手动flush写入。另外,只适用于int类型读入。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值