卡常,通常是指使用一些手段以降低代码的运行时间。在某些毒瘤题目中,出题人会卡你常数。日常练习的时候,进行一些非刻意卡常也是好的习惯。
本文记录笔者见过的一些卡常技巧。
1. I/O 优化
经典 I/O 优化。在输入规模达到 及以上时,应用 I/O 优化效果比较显著。模板如下:
namespace FastIO {
const int SZ = 1 << 18; char *p1, *p2, buf[SZ];
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, SZ, stdin), p1 == p2) ? EOF : *p1++)
inline void skip() {for (char ch = getchar(); ch == ' ' || ch == '\n' || ch == '\t'; ch = getchar());}
int t; char ch;
template <class T> inline void read(T& x) {x = 0, t = 1, ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) if (ch == '-') t = -1; for (; '0' <= ch && ch <= '9'; ch = getchar()) x = (x << 1) + (x << 3) + (ch ^ 48); x *= t;}
inline void read(char& x) {skip(), x = getchar();}
template <class T, class... Args> inline void read(T& t, Args&... args) {read(t), read(args...);}
template <class It> inline void read(const It& begin, const It& end) {for (It it = begin; it != end; it++) read(*it);}
template <class T1, class T2> inline void read(pair<T1, T2>& p) {read(p.first), read(p.second);}
#ifndef DISABLE_FAST_WRITE
char obuf[SZ], *p3 = obuf;
#define putchar(a) ((p3 - obuf < SZ) ? (*p3++ = a) : (fwrite(obuf, p3 - obuf, 1, stdout), p3 = obuf, *p3++ = a))
inline void flush() {fwrite(obuf, p3 - obuf, 1, stdout);}
#endif //DISABLE_FAST_WRITE
template <class T> inline void write(T x) {if (x < 0) putchar('-'), x = -x; static int st[40]; int top = 0; do {st[top++] = x % 10, x /= 10;} while (x); while (top) putchar(st[--top] ^ 48);}
inline void write(const char c) {putchar(c);}
inline void write(const std::string& s) {for (char c : s) putchar(c);}
template <class T> inline void write(const char c, const T x) {write(x), putchar(c);}
template <class T, class... Args> inline void write(T t, const char c, Args... args) {write(c, t), write(c, args...);}
template <class T> inline void writeln(const T x) {write(x), putchar('\n');}
template <class T> inline void writesp(const T x) {write(x), putchar(' ');}
template <class It> inline void write(const char c, const It& begin, const It& end) {for (It it = begin; it != end; it++) write(*it), putchar(c);}
template <class T1, class T2> inline void write(const char c, const pair<T1, T2>& p) {write(p.first), putchar(c), write(p.second);}
} using namespace FastIO;如果想要进一步卡常,可以使用 mmap:
#include <sys/mman.h>
namespace FastIO {
const int SZ = 1 << 18;
#define _Input (char*) mmap(0, 1LL << 29, PROT_READ, MAP_SHARED, 0, 0)
char obuf[SZ];
char *input = _Input, *p = obuf;
#define getchar() (*input++)
#define putchar(x) ((p == obuf + SZ) && (fwrite(obuf, p - obuf, 1, stdout), p = obuf), *p++ = x)
inline void skip() {for (char ch = getchar(); ch == ' ' || ch == '\n' || ch == '\t'; ch = getchar());}
int t; char ch;
template <typename T> inline void read(T& x) {x = 0, t = 1, ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) if (ch == '-') t = -1; for (; '0' <= ch && ch <= '9'; ch = getchar()) x = (x << 1) + (x << 3) + (ch ^ 48); x *= t;}
inline void read(char& x) {skip(), x = getchar();}
template <typename T, typename... Args> inline void read(T& t, Args&... args) {read(t); read(args...);}
template <typename It> inline void read(const It& begin, const It& end) {for (It it = begin; it != end; it++) read(*it);}
inline void flush() {fwrite(obuf, p - obuf, 1, stdout);}
template <typename T> inline void write(T x) {if (x < 0) putchar('-'), x = -x; static int st[40]; int top = 0; do {st[top++] = x % 10, x /= 10;} while (x); while (top) putchar(st[--top] ^ 48);}
inline void write(const char c) {putchar(c);}
inline void write(const std::string& s) {for (char c : s) putchar(c);}
template <typename T> inline void write(const char c, const T x) {write(x), putchar(c);}
template <typename T, typename... Args> inline void write(T t, const char c, Args... args) {write(c, t); write(c, args...);}
template <typename T> inline void writeln(const T x) {write(x), putchar('\n');}
template <typename T> inline void writesp(const T x) {write(x), putchar(' ');}
template <typename It> inline void write(const char c, const It& begin, const It& end) {for (It it = begin; it != end; it++) write(*it), putchar(c);}
} using namespace FastIO;一般有 20 ~ 200ms 的优化效果。
2. 范围优化
好像比较抽象。其实就是这几个例子:
- 查询区间从 改写成 。
- 二分端点从
l=0, r=1e18改成具体范围。
某些时候会有 100ms 左右的效果。
3. 合理剪枝
这个就就题论题吧。举个例子:P5356 [Ynoi2017] 由乃打扑克 中,只需要将二分中加上一句剪枝就可以以 卡过。
if (d[r[i]] + lazy[i] <= k) {
res += r[i] - l[i] + 1;
continue;
}4. 内置函数 / STL
4.1 mem 函数
<cstring> 中以 mem 开头的函数一般快于手写。以下是用法:
memset(a + l + 1, /*值*/, sizeof(/*类型*/) * (r - l + 1))
memcpy(a + l + 1, b + l + 1, sizeof(/*类型*/) * (r - l + 1))
memmove(a + to + 1, a + l + 1, sizeof(/*类型*/) * (r - l + 1))4.2 __builtin 家族
这个玩意所实现的函数是非常快的,通常可以看作 。用法:
| 用法 | 含义 |
|---|---|
__builtin_popcount(x) | 计算 二进制中 的个数 |
__builtin_sqrt(x) | 计算 |
__builtin_ctz(x) | 计算 从最低位开始的连续的 0 的个数 |
__builtin_clz(x) | 计算 从最高位开始的连续的 0 的个数 |
__builtin_parity(x) | 计算 二进制中 的个数的奇偶性 |
一般地,__builtin_parity(x) 快于 __builtin_popcount(x) & 1。
计算 long long 类型时,函数名后应该加 ll。
使用 __builtin_ctz 实现的 Binary GCD,非常优秀:
constexpr int gcd(int a, int b) {
int az = __builtin_ctz(a), bz = __builtin_ctz(b), z = min(az, bz);
b >>= bz;
while (a) {
a >>= az;
int d = a - b;
az = __builtin_ctz(d);
b = min(a, b), a = abs(d);
}
return b << z;
}4.3 STL 的神奇函数
通常是指下面两个:
| 函数 | 用法 |
|---|---|
std::__lg(x) | 计算 |
std::__gcd(a, b) | 计算 |
其中,std::__lg 快于手写、预处理和 (int) log2(x) 三种做法。std::__gcd 快于普通手写,慢于 Binary GCD。
4.4 pb_ds
众所周知,std::unordered_map 非常慢。这个时候,可以使用 __gnu_pbds::cc_hash_table,通常有 300ms 的效果。
一般地,使用 __gnu_pbds::priority_queue 实现的配对堆比 std::priority_queue 快 100ms 左右。
#include <bits/extc++.h>
using namespace __gnu_pbds;
cc_hash_table<int, int> mp;
__gnu_pbds::priority_queue<int> q;4.5 多用 STL
开 O2 情况下。举例:
std::vector写的有序数组代替平衡树,可以卡过数据不强的平衡树题。- 用
std::iota(fa, fa + n + 1, 0)替换普通的并查集初始化。 - 用
std::fill、std::copy、std::reverse等代替手写。
4.6 少用 STL
std::vector、std::complex 等等即使开 O2 也慢于手写。
注:感谢 konyakest 指出,
std::array在开 O2 情况下与原生数组完全相同。
5. 数据结构
5.1 线段树 / 树状数组
除非你的线段树特别优秀,否则普通树状数组一定快于线段树。
笔者实测,在模板题即使 ZKW 线段树也跑不过双差分树状数组。
所以,面对区间加、区间求和问题,使用双差分树状数组一般快于线段树。
5.2 分块
其实把……Ynoi 全都是这些东西。这里碍于笔者水平,只能说一些基础的技巧:
- 将块长设为定值,适当微调。
- 散块使用比暴力更优的处理方式。
5.3 莫队
奇偶化排序,优化作用有 。也可以固定块长。
sort(q.begin(), q.end(), [&](const node& x, const node& y) -> bool {
if (x.l / unit != y.l / unit) return x.l < y.l;
if ((x.l / unit) & 1) return x.r < y.r;
return x.r > y.r;
});5.4 平衡树
OI 常用平衡树中,手写红黑树最快。
不过红黑树非常难写,那么使用 AVL 代替也能达到相近的优化效果。非文艺平衡树尽量避免 Splay / FHQ-Treap。WBLT / 01-Trie 也比较优秀。
5.5 BitSet
见笔者的 BitSet 总结笔记。
手写 BitSet 也是不错的卡常方法。
6. 排序
先说结论:你自己手写 的排序,很难比 std::sort 快。这是因为 std::sort 使用的 IntroSort 已经作了大量优化。
注:
std::sort可以在 100ms 完成 级别的排序。
若值域较小,使用计数排序是很优秀的。值域大时,使用二进制基数排序,一般也是线性的。
特别地,若数组中元素大部分有序,使用 std::stable_sort 可以做到线性。
7. 取模
前置知识:模数要加 const 不用多说了吧……
7.1 加减法
对于加减,我们通常是这样的:
int add = (x + y) % mod;
int sub = (x - y + mod) % mod;这样写的常数是很大的。有比较快速的方法:
int add = x + y >= mod ? x + y - mod : x + y;
int sub = x - y < 0 ? x - y + mod : x - y;7.2 乘法
对于两个可能爆 long long 的数,龟速乘确实是“龟速”,可以使用 __int128:
long long mul = (__int128) x * y % mod;7.3 modint
如果这样写过于麻烦,可以自己写一个板子。
template <const int mod>
struct mod32 {
static_assert((static_cast<long long>(mod)<<1)<=INT_MAX);
int val;
explicit operator int() const {return val;}
static constexpr int norm(int x) {return x<0?x+mod:x;}
static constexpr int get_mod() {return mod;}
mod32():val(0){}
mod32(int m):val(norm(m)){}
mod32(long long m):val(norm(m%mod)){}
mod32<mod> operator- () const {return -val;}
bool operator== (const mod32<mod>& x) const {return val==x.val;}
bool operator!= (const mod32<mod>& x) const {return val!=x.val;}
bool operator< (const mod32<mod>& x) const {return val<x.val;}
bool operator<= (const mod32<mod>& x) const {return val<=x.val;}
bool operator> (const mod32<mod>& x) const {return val>x.val;}
bool operator>= (const mod32<mod>& x) const {return val>=x.val;}
mod32<mod>& operator+= (const mod32<mod>& x)
{return val=(val+x.val>=mod?val+x.val-mod:val+x.val),*this;}
mod32<mod>& operator-= (const mod32<mod>& x)
{return val=(val-x.val<0?val-x.val+mod:val-x.val),*this;}
mod32<mod>& operator*= (const mod32<mod>& x)
{return val=(static_cast<long long>(val)*x.val%mod),*this;}
mod32<mod> pow(long long b) const
{mod32<mod> a(*this),res(1);for(;b;a*=a,b>>=1)if(b&1)res*=a;return res;}
mod32<mod> operator~ () const {return pow(mod-2);}
mod32<mod>& operator/= (const mod32<mod>& x) {return *this*=x.pow(mod-2);}
mod32<mod> operator+ (const mod32<mod>& x) const
{return mod32<mod>(*this)+=x;}
mod32<mod> operator- (const mod32<mod>& x) const
{return mod32<mod>(*this)-=x;}
mod32<mod> operator* (const mod32<mod>& x) const
{return mod32<mod>(*this)*=x;}
mod32<mod> operator/ (const mod32<mod>& x) const
{return mod32<mod>(*this)/=x;}
friend std::istream& operator>> (std::istream& in, mod32<mod>& x)
{long long v;return in>>v,x.val=norm(v%mod),in;}
friend std::ostream& operator<< (std::ostream& out, const mod32<mod>& x)
{return out<<x.val;}
};
using mod998244353 = mod32<998244353>;
using mod1000000007 = mod32<1000000007>;