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