快速读写模板

· · 算法·理论

fread快读

template<typename T>inline void read(T &n);
template<typename T>inline void write(T n);

const int SIZE=1<<14;
inline char getc(){
    static char buf[SIZE],*begin=buf,*end=buf;
    if (begin==end){
        begin=buf;
        end=buf+fread(buf,1,SIZE,stdin);
        if (begin==end) return EOF;
    }
    return *begin++;
}
template<typename T>inline void read(T &n){
    n=0;T f=1;
    char c;
    do{
        c=getc();
        if (c=='-') f=-1;
    }while (c<'0'||c>'9');
    while (c>='0'&&c<='9'){
        n=(n<<1)+(n<<3)+(c^48);
        c=getc();
    }
    n*=f;
}
template<typename T>inline void write(T n){
    if (n<0) putchar('-'),n=-n;
    if (n>9) write(n/10);
    putchar(n%10+'0');return;
}

用于输入输出unsigned long long范围以内的整数(可为负数),fread是对getchar()的优化

关闭同步流

ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);

用于对cin和cout的优化,启用后不能再使用scanf和printf,如果关闭同步流后cout和快写/putchar()/puts()混用,cout会忽略代码执行顺序,总是在其他输出结束后再输出,因此调试代码时建议注释掉

注意事项

字符串或单个字符读入不能和上述整数快读混用,如果出现了字符串,建议为字符串单独处理快读读入或直接改为scanf或cin