常数,决定了复杂度一样的算法得到分数的高低。
一个 10 10 10倍常数?不得了!
常用的常数优化:
0:精致优化
通过精妙地控制循环的边界或者搜索剪枝。 最有效!
1:快读
基础版:
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-')f = -1; ch = getchar();}
while (ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0'; ch = getchar();}
return x * f;
}
2: r e g i s t e r register register优化
for (register int i = 1; i <= n; ++i)
3: i n l i n e inline inline优化
inline int calc() {
}
4:判断语句优化
- 三目运算符要比 i f . . e l s e if..else if..else更快。
- 尽量减少 i f if if等语句
5:赋值优化
- 多组询问的题如果是一个静态的东西,就没必要清空了。
- 如果赋值较满,用 m e m s e t memset memset比 f o r for for更加优越。
6:类型优化
- l o n g l o n g long\ long long long类型下的运算慢一些,不要闭着眼开 l o n g l o n g long\ long long long。
- i n t int int下的运算比 c h a r char char快一些
7:运算优化
- 使用位运算来代替与 2 2 2的次幂有关的操作。
8:写法优化
- 使用递推类型的 d p dp dp来代替记忆化搜索
- 使用二进制枚举法来枚举子集(比dfs快)
for (int i = 0; i < (1 << all); ++i) {//2^n枚举
for (int j = 0; j < all; ++j) {
if ( (i >> j) & 1) bas[j + 1] = 1;
}
}
for (int i = all; i; i = (i - 1) & all) //枚举子集