0. 在有些输入数据很多的变态题中,scanf会大大拖慢程序的时间,cin就更慢了,所以就出现了读入优化。其原理就是一个一个字符的读入,输出优化同理,主要使用getchar,putchar函数。
1. int型读入优化(long long的只要把x改成long long型即可):
1 #include<cctype>
2 inline int read()
3 {
4 int x=0,f=0; char ch=0;
5 while(!isdigit(ch)) {f|=ch=='-';ch=getchar();}
6 while(isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
7 return f?-x:x;
8 }
2.double型读入优化:
1 inline double dbread()
2 {
3 double x=0,y=1.0; int f=0; char ch=0;
4 while(!isdigit(ch)) {f|=ch=='-';ch=getchar();}
5 while(isdigit(ch)) x=x*10+(ch^48),ch=getchar();
6 ch=getchar();
7 while(isdigit(ch)) x+=(y/=10)*(ch^48),ch=getchar();
8 return f?-x:x;
9 }
3. int型输出优化(在一些输出数据量很大的题可能会用,同理long long型的改一下x的类型即可):
1 inline void write(int x)
2 {
3 if(x<0) putchar('-'),x=-x;
4 if(x>9) write(x/10);
5 putchar(x%10+'0');
6 }
在一些题中使用优化可能从TLE逆转AC,代码也比较短,平时多敲敲。
cin关同步:cin慢的原因主要在于默认cin与stdin总是保持同步, 这一步是消耗时间大户.
只需要加上ios::sync_with_stdio(false)来关闭同步就好了, 速度甚至要优于scanf.
但是要注意关同步后不要同时用cin和scanf,会出错。
std::ios::sync_with_stdio(false);
std::cin.tie(0);
来源:https://www.cnblogs.com/FrankChen831X/p/10661348.html