Fast reading skills

When practicing on the topic OJ, enter some data subject is very large, even with scanf () card will be constant, leading to TLE. So gather online solutions, common are the following two:

First, when the data is not particularly large amount of time, you can disable synchronization stdio so cin, cout and printf, as fast scanf.

核心代码:
ios::sync_with_stdio(false)
//此时注意在程序中不能再使用任何stdio的库函数,否则会造成混乱。

Second, when in the form of a large amount of data when using the characters read read, pay attention to neglected spaces, carriage returns, and other characters.

//写为内联函数  建议编译器不做函数调用,直接展开
/*毕竟数量大的时,需要一直调用read()读取,如果能成为内联
则可以减少函数调用的开销,提高程序的执行效率*/
inline int read() {
	int x = 0;
	int f = 1;//f表示的是整数x的正负  f==1表示x为正  f==-1表示x为负
	char ch = getchar();
	while (!isdigit(ch)) {
		//如果不是数字字符  只考虑其是否为符号,其他符号不考虑
		if (ch == '-') f = -1;
		ch = getchar();
	}
	while (isdigit(ch) {
		//说明ch是数字字符  但是有能不是一个只有个数数的数字
		x = x*10 + ch -'0';
		ch = getchar();
	}
	return x*f;
}


//函数功能同上,只是直接读取到了引用参数x中
template <typename T>
inline void read(T &x) {
	int f = 1;
	x = 0;
	char ch = getchar();
	while (!isdigit(ch)) {
		if (ch == '-') {
			f = -1;
			ch = getchar();
		}
	}
	while (isdigit(ch)) {
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	x = x*f;
}
Published 235 original articles · won praise 51 · views 120 000 +

Guess you like

Origin blog.csdn.net/ASJBFJSB/article/details/103162340