输入输出优化
快读与快输
快读
原理
- 当ch不是数字时,判断是否为负,然后继续读入。
- ch 是数字时,将新读入的数字"加"在
x
的后面。 - 返回 数字 * 正负号 = 实际数值。
- 介绍一个函数
isdigit()
,判断字符型是否是数字。
code
code1
inline int read() {
int k = 0, f = 1;
char ch = getchar();
for (; !isdigit(ch); ch = getchar())
if (ch == '-')
f = -1;
for (; isdigit(ch); ch = getchar()) k = k * 10 + ch - '0';
return k * f;
}
code2
inline int read() {
int f = 1, x = 0;
char c = getchar();
while (c < '0' || c > '9') f = (c == '-') ? -1 : 1, c = getchar();
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return f * x;
}
快输
原理
- 首先,判负,然后输出负号,然后变原数为正数,
- 然后,将除最后一位外的其他部分放到递归中输出,
- 最后输出末位。
- 同时可以用栈来实现代码。
code1
#include <bits/stdc++.h>
using namespace std;
void write(int x) {
if (x < 0) {
x = -x;
putchar('-');
}
if (x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
code2
inline void write(int x) {
static int sta[35];
int top = 0;
do {
sta[top++] = x % 10, x /= 10;
} while (x);
while (top) putchar(sta[--top] + 48); // 48 是 '0'
}
关闭同步/解除绑定
std::ios::sync_with_stdio(false)
这个函数是一个“是否兼容 stdio”的开关,C++ 为了兼容 C,保证程序在使用了 printf 和 std::cout 的时候不发生混乱,将输出流绑到了一起。
我们可以在进行 IO 操作之前将 stdio 解除绑定,但是在这样做之后要注意不能同时使用 std::cin/std::cout 和 scanf/printf 。
tie
tie 是将两个 stream 绑定的函数,空参数的话返回当前的输出流指针。
在默认的情况下 std::cin 绑定的是 std::cout ,每次执行 << 操作符的时候都要调用 flush() ,这样会增加 IO 负担。可以通过 std::cin.tie(0) (0 表示 NULL)来解除 std::cin 与 std::cout 的绑定,进一步加快执行效率。
code
std::ios::sync_with_stdio(false);
std::cin.tie(0);