简易快读
本文采用 LOJ #7 作为测试。由于 LOJ 上有奇怪的
普通快读:
void read(ll &x) {
x = 0;
char c = getchar();
while (!isdigit(c)) {
c = getchar();
}
while (isdigit(c)) {
x = 10 * x + c - '0';
c = getchar();
}
}
速度:
常见的 fread 快读:
char buf[1 << 22], *p, *q;
inline char getc() {
return p == q && (q = (p = buf) + fread(buf, 1, 1 << 21, stdin)), p == q ? EOF : *p++;
}
void read(ll &x) {
x = 0;
char c = getc();
while (!isdigit(c)) {
c = getc();
}
while (isdigit(c)) {
x = 10 * x + c - '0';
c = getc();
}
}
速度:
实际上只需要把普通快读的 getchar 换成 getchar_unlocked 就会快很多。
void read(ll &x) {
x = 0;
char c = getchar_unlocked();
while (!isdigit(c)) {
c = getchar_unlocked();
}
while (isdigit(c)) {
x = 10 * x + c - '0';
c = getchar_unlocked();
}
}
速度:
原理:getchar 为了保证线程安全,在每次使用前和使用后都进行了上锁和解锁的操作,而 getchar_unlocked 没有这些操作,同时它也线程不安全。然而 OI 中根本不用考虑什么线程安全对吧!
优点:好写,速度快。
缺点:Windows 用不了(意味着 CF 用不了)。当然 NOI Linux 能用就行!
注:在 Windows 中可用 _getchar_nolock 代替。