Skip to main content

读写优化

Summary

读写优化用于加速竞赛程序的数据读写。基础手段是关闭 C++ 流与 C 标准 IO 的同步,并解除 cin 与 cout 的关联,代价是关闭后 cin 与 cout 不能再和 scanf、printf 混用,否则可能触发未定义行为。更进一步是手写快读快写,直接按字符读入整数、按位输出,绕开流的额外开销,这里给出基于 getchar、getchar_unlocked 以及带缓冲区的 namespace IO 三种实现。

参考资料​

关闭同步 & 解除关联​

46 Bcpp
ios::sync_with_stdio(false);
cin.tie(nullptr);
warning

关闭同步后,cin/cout 和 scanf/printf 不能混用,否则可能会导致未定义行为(UB),从而引发读写顺序错误。

快读快写​

244 Bcpp
int read()
{
int x=0,f=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9')x=x*10+c-48,c=getchar();
return x*f;
}
void write(int x)
{
if(x<0)putchar('-'),x=-x;
if(x>9)write(x/10);
putchar(x%10+48);
}

例题​

输入 nn 个整数 aia_i,输出它们的和。(∣ai∣≤n≤108|a_i|\le n\le 10^8)