前言
在做题的时候经常会遇到卡输入输出的题,连scanf和printf都会TLE的题,我们需要使用快读快写。
基本快读快写
当然,基本快读快写是指整数的快读快写
快读
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要快。
高级快读快写
来自某洛谷大佬cyffff (%%%orz)
namespace IO { // by cyffff
int len = 0;
char ibuf[(1 << 20) + 1], *iS, *iT, out[(1 << 25) + 1];
#define gh() \
(iS == iT ? iT = (iS = ibuf) + fread(ibuf, 1, (1 << 20) + 1, stdin), \
(iS == iT ? EOF : *iS++) : *iS++)
#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;
}
} // namespace IO
using IO::flush;
using IO::putc;
using IO::read;
using IO::write;
后记
如有不足,请大佬在评论区指出,本蒟蒻一定会关注回复。
注:可以在我的 cnblogs 里查看。