我们知道cin、cout是比较慢的,不过它们可以加速。
在代码中加入这两句即可
std::ios::sync_with_stdio(false);
std::cin.tie(0);
加速过后cin的速度与scanf的速度近似
当然,加速过后就不要混用print和cout,scanf和cin了。(因为不同步,后果会很严重)
cin慢是有原因的,其实默认的时候,cin与stdin总是保持同步的,也就是说这两种方法可以混用,而不必担心文件指针混乱,同时cout和stdout也一样,两者混用不会输出顺序错乱。正因为这个兼容性的特性,导致cin有许多额外的开销,如何禁用这个特性呢?只需一个语句std::ios::sync_with_stdio(false);,这样就可以取消cin于stdin的同步了。
输入输出外挂能够减少程序输入输出的时间。
常用的printf,scanf都要比cin,cout快,但是,有时候用printf、scanf也会TLE( 有的题目出题人会卡你读取数据,输出数据。让你因为读取数据,输出数据而TLE ),这时候我们就要用到外挂的输入输出方式了。
外挂输入输出对于大数据量能够明显减少时间,其实它的快主要是因为 scanf和printf都是对缓冲区的读写操作,当程序执行的时候不会直接把要输出的内容输出到键盘上,或者说是从键盘读入的数据不会直接读到程序里,而是先读到一个叫做缓冲区的东西里面,这就大大降低了速度了。
而putchar和getchar因为一次只能输出一个字符,所以它可以直接输出,所以它输出的很快。外挂输入输出的程序其实就是将本来要读取的内容拆成一个一个的字符进行读取或者输出。
这里贴一份kuangbin输入输出外挂的模板
代码
//适用于正负整数
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template <class T>
inline bool scan_d(T &ret){
char c;
int sgn;
if(c = getchar(), c == EOF)
return 0;
while(c != '-' && (c < '0' || c > '9'))
c = getchar();
sgn = (c == '-') ? -1 : 1;
ret = (c == '-') ? 0 : (c - '0');
while(c = getchar(), c >= '0' && c <= '9')
ret = ret * 10 + (c - '0');
ret += sgn;
return 1;
}
inline void out(int x){
if(x > 9)
out(x / 10);
putchar(x % 10 + '0');
}
int main(){
return 0;
}
不会用这份kuangbin的模板。。。
贴一份会用的模板,不过只能用来处理整数。
#include <stdio.h>
//注: 此外挂只适合数字的输入输出
int scan_int(){//输入外挂
char ch;
int res = 0, flag = 0;
if((ch = getchar()) == '-')
flag = 1;
else if(ch >= '0' && ch <= '9')
res = ch -'0';
while ((ch = getchar()) && ch >= '0' && ch <= '9')
res = res * 10 + ch - '0';
return flag ? -res : res;
}
void out(int n){//输出外挂
if(n > 9)
out(n / 10);
putchar(n % 10 + '0');
}
int main(){
int n = scan_int();
if(n < 0){
printf("-");
out(-n);
}
out(n);
return 0;
}
参考来源
博客
http://www.ishenping.com/ArtInfo/1647484.html
博客
https://www.cnblogs.com/Howe-Young/p/4057975.html
博客
http://blog.csdn.net/u013445530/article/details/43381833