快读快写

· · 个人记录

使用这种快读快写读入一个数 x 时请使用语句 x=read();,输出时使用语句 write(x);。注意,换行时需使用语句 putc('\n');,程序执行结束时使用语句 flush();。

在使用此快读时请加上 #include<bits/stdc++.h>。

namespace IO{//by cyffff
    int len=0;
    char ibuf[(1<<20)+1],*iS,*iT,out[(1<<26)+1];
    #ifdef ONLINE_JUDGE
    #define gh() (iS==iT?iT=(iS=ibuf)+fread(ibuf,1,(1<<20)+1,stdin),(iS==iT?EOF:*iS++):*iS++)
    #endif
    #ifndef ONLINE_JUDGE
    #define gh() getchar()
    #endif
    #define reg register
    inline int read(){
        reg char ch=gh();
        reg int x=0;
        reg char t=0;
        while(ch<'0'||ch>'9')   t|=ch=='-',ch=gh();
        while(ch>='0'&&ch<='9') x=x*10+(ch^48),ch=gh();
        return t?-x:x;
    }
    inline void putc(char ch){
        out[len++]=ch;
    }
    template<class T>
    inline void write(T x){
        if(x<0)putc('-'),x=-x;
        if(x>9)write(x/10);
        out[len++]=x%10+48;
    }
    inline void flush(){
        fwrite(out,1,len,stdout);
        len=0;
    }
}
using IO::read;
using IO::write;
using IO::flush;
using IO::putc;

char-gpt 版本。

#include <iostream>
#include <cstdio>
#include <tuple>
char Inbuf[1000000],*ibuf=Inbuf,Outbuf[1000000],*obuf=Outbuf;
// 将一个整数写入缓冲区
template<typename T>
inline void writeInt(T x, char *&p) {
    static char buf[21];
    int i = 0;
    if (x < 0) {
        *p++ = '-';
        x = -x;
    }
    if (x == 0) *p++ = '0';
    while (x) {
        buf[i++] = x % 10 + '0';
        x /= 10;
    }
    while (i) *p++ = buf[--i];
}

// 辅助函数,用于终止递归调用
inline void writeInt(char *&p, char sep, char end) {}

// 递归展开以写入所有参数
template<typename T, typename... Args>
inline void writeInt(char *&p, char sep, char end, T x, Args&&... args) {
    writeInt(x, p);
    if constexpr(sizeof...(args) != 0) {
        *p++ = sep; // 输出 sep 字符
    } else {
        *p++ = end; // 输出 end 字符
    }
    writeInt(p, sep, end, std::forward<Args>(args)...);
}

// 从缓冲区读取一个整数
template<typename T>
inline void readInt(T &x, char *&p) {
    x = 0;
    bool neg = false;
    char c;
    while (*p && !isdigit(*p) && *p != '-') ++p;
    if (*p == '-') {
        neg = true;
        ++p;
    }
    while (*p && isdigit(*p)) {
        x = x * 10 + (*p - '0');
        ++p;
    }
    if (neg) x = -x;
}

// 递归展开以读取所有参数
template<typename... Args>
inline void readInt(char *&p, Args&... args) {
    (readInt(args, p), ...);
}


int main() {
    fread(ibuf,1,1000000,stdin);
    int x;
    readInt(ibuf,x);
    writeInt(obuf,' ','\n',x);
    fwrite(Outbuf,1,obuf-Outbuf,stdout);

}