Fast Input & Output - 快速读写
前言
在做题的时候经常会遇到卡输入输出的题,连scanf和printf都会TLE的题,我们需要使用快读快写。
以下内容均来自与洛谷的巨佬们,非本人原创,我只做整理。
扩展
这比较简易,给习惯 cin、cout 的 OIer 用,可以使得 cin、cout 达到 scanf、printf 的速度(关闭输入输出同步)。
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
基本快读快写
当然,基本快读快写是指整数的快读快写
快读
inline int read()
{
int X = 0, w = 0; char ch = 0;
while (!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while (isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
这里的inline可以加速,还有x = (x << 1) + (x << 3) + (c ^ 48);
使用位运算加快速度。
f
变量可以判负数。如果没有用bits/stdc++.h
的头文件,isdigit
函数要用cctype
头文件,当然也有人把isdigit
替换为手写ASCII码判断,但isdigit
可能会更快。
快写
inline void write(int x)
{
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
快写代码要短一些,这里采用递归写法, 可以用inline优化,putchar比cout和printf要快。
\(\rm Fast\ IO\) - 进阶卡常版本
注意最后要用flushout()输出哦!
原理: 把输出内容存到缓冲区,最后合并输出,从而在快读快写的基础上优化。
#include <bits/stdc++.h>
#define _for(i, a, b) for(int i = (a); i <= (b); i++)
using namespace std;
namespace FAST_IO{
#define ll long long
#define ull unsigned long long
#define db double
#define _8 __int128_t
const int LEN=1<<20;
char BUF[LEN],PUF[LEN];
int Pin=LEN,Pout;
inline void flushin(){memcpy(BUF,BUF+Pin,LEN-Pin),fread(BUF+LEN-Pin,1,Pin,stdin),Pin=0;return;}
inline void flushout(){fwrite(PUF,1,Pout,stdout),Pout=0;return;}
inline char Getc(){return (Pin==LEN?(fread(BUF,1,LEN,stdin),Pin=0):0),BUF[Pin++];}
inline char Get(){return BUF[Pin++];}
inline void Putc(char x){if(Pout==LEN)flushout(),Pout=0;PUF[Pout++]=x;}
inline void Put(char x){PUF[Pout++]=x;}
template<typename tp=int>inline tp read(){(Pin+32>=LEN)?flushin():void();tp res=0;char f=1,ch=' ';for(;ch<'0'||ch>'9';ch=Get())if(ch=='-')f=-1;for(;ch>='0'&&ch<='9';ch=Get())res=(res<<3)+(res<<1)+ch-48;return res*f;}
template<typename tp>inline void wt(tp a){if(a>9)wt(a/10);Put(a%10+'0');return;}
template<typename tp>inline void write(tp a,char b='\n')
{
static int stk[20],top;
(Pout+32>=LEN)?flushout():void();
if(a<0)Put('-'),a=-a;
else if(a==0)Put('0');
for(top=0;a;a/=10)stk[++top]=a%10;
for(;top;--top)Put(stk[top]^48);
Put(b);
return;
}
inline void wt_str(string s){for(char i:s)Putc(i);return;}
}
using namespace FAST_IO;
int main() {
flushout();
return 0;
}
后记
如有不足,请大佬在评论区指出,本蒟蒻一定会关注回复。