[笔记] 快读快写
复制版
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
inline int read(){
int x = 0, f = 1;
char c = getchar();
while(!isdigit(c)){
if(c == '-') f = -1;
c = getchar();
}
while(isdigit(c)){
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
return x * f;
}
1,为什么要有快读快写
在某些 无良卡时间的 题里面,我们总是会被烦人的0.01s卡住,并且你用的是最优解,能优化的全优化了,就很烦!
1,cin和cout
cin和cout是C++中很常用的读写方式,但很慢。
在精致小题里面不错,但数据很大时就会出现TLE的情况
2,scanf和printf
scanf和printf会比上面快,但是:
我们的 无良 样例组同样会送给你TLE!!!
3,getchar和putchar
众所周知(为什么我之前不知道),getchar和putchar会比前两种快
为什么,因为读字符更快
那为什么读字符更快?(我也不知道,请自行查阅资料)
2,优化
1,cin和cout
因为 C++ 为了和 C 保持同步、在混用 printf&scanf 和 cin&cout 的时候不发生混乱,将它的 输入&输出流 绑到了一起。
解决方法:
在using namespace std;的下面写上:
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
它取消了它们的绑定,也取消了cin与cout的绑定
另外,endl也是拖时间的 功臣 ,相比之下,使用\n会比前者更快。
2,getchar和putchar
直接放代码,看代码解析
inline int read(){
int x = 0, f = 1; //x是数字,f是符号
char c = getchar();
while(!isdigit(c)){ //符号特判,isdigit判断c是否是一个数字
if(c == '-') f = -1;
c = getchar();
}
while(isdigit(c)){
x = (x << 3) + (x << 1) + (c ^ 48); //位运算更快,你用这个也行:x = x * 10 + (c - '0');
c = getchar();
}
return x * f; //返回符号 * 数字
}
inline void write(int x){
if(x < 0){
putchar('-');
x = (~x) + 1; //位运算更快
}
if(x >= 10){
write(x / 10);
}
write(x % 10 ^ 48); //位运算更快
}
但是,如果题目里的输入有很多非数字,像这个:
—”: 7328 625eywi32--9372 521
211 76 *《" >} 42=-51
## % 2* -13 123 32 1[21] 132
那么就好自为之,别用快读了!