读入输出优化
读入输出优化
这里介绍了快读快写、O2 优化、关闭同步流。
时间比较:快读快些 \(\le\) \(c\) 语言输入输出 \(\le\) 关闭同步流 \(\le\) \(c++\) 语言输入输出。
大家可以根据注释理解一下代码。
// 快读
inline int read() {
int x = 0, f = 1;
char ch = getchar();
for (; ch < '0' || ch > '9'; (ch == '-') && (f = -1), ch = getchar) { // 如果 ch 为负号,就设定 f=-1
}
for (; ch >= '0' && ch <= '9'; x = x * 10 + ch - '0', ch = getchar) { // 计算 x 并读入
}
return x * f; // 输出 x*f
}
// 优化快读
char *p1, *p2, buf[100000];
#define nc() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++)
inline int read() { // 代码意思同上
int x = 0, f = 1;
char ch = nc();
for (; ch < '0' || ch > '9'; (ch == '-') && (f = -1), ch = nc()) {
}
for (; ch >= '0' && ch <= '9'; x = x * 10 + ch - '0', ch = nc()) {
}
return x * f;
}
// 快写
void write(int x) {
(x < 0) && (putchar('-'), x = -x); // 如果 x 为负数,就先输出符号,再输出它的相反数
(x > 9) && (write(x / 10), 0); // 如果 x 不为一位数就先输出前面的(递归),再输出个位
putchar(x % 10 + '0'); // 输出个位
}
// O2 优化
#pragma GCC optimize(2)
// 关闭同步流
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
其他
// 火车头
#pragma GCC optimize(3)
#pragma GCC target("avx")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-ffast-math")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-fwhole-program")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("inline-functions")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-fstrict-overflow")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-fcse-skip-blocks")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("inline-small-functions")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("-funsafe-loop-optimizations")
#pragma GCC optimize("inline-functions-called-once")
#pragma GCC optimize("-fdelete-null-pointer-checks")
#pragma GCC optimize(2)