模板

· · 个人记录

1. 数据结构

1.1 邻接表存图

int n;
vector<vector<int>> g(M + 1);
vector<vector<pair<int, int>>> g(M + 1);
// 无权:g[x].push_back(y)
// 带权:g[x].push_back({y, w})

1.2 链式前向星

int head[N], cnt = 0; 
struct Edge {int to, next}edge[N];
void init() {
    for (int i=0; i < N << 1; i++) edge[i].next = -1, head[i] = -1;
    cnt = 0;
}
void addedge(int u, int v) {
    edge[cnt].to = v; edge[cnt].next = head[u]; head[u] = cnt++;
}

1.3 LCT

const int N = 3e5+5;
struct node {int fa, ch[2], sum, val, lazy;}t[N];
#define lc t[x].ch[0]
#define rc t[x].ch[1]
bool isroot(int x) {
    int g = t[x].fa;
    return t[g].ch[0] != x && t[g].ch[1] != x;
}
void pushup(int x) {t[x].sum = t[x].val ^ t[lc].sum ^ t[rc].sum;} // 按要求改
void reverse(int x) {
    if (!x) return;
    swap(lc,rc);
    t[x].lazy^=1;
}
void pushdown(int x) {
    if (t[x].lazy) {
        reverse(lc);
        reverse(rc);
        t[x].lazy=0;
    }
}
void push(int x) {
    if (!isroot(x)) push(t[x].fa);
    pushdown(x);
}
void rotate(int x) {
    int y = t[x].fa;
    int z = t[y].fa;
    int k = t[y].ch[1] == x;
    if (!isroot(y)) t[z].ch[t[z].ch[1] == y] = x;
    t[x].fa = z;
    t[y].ch[k] = t[x].ch[k^1];
    if (t[x].ch[k^1]) t[t[x].ch[k^1]].fa = y;
    t[y].fa = x;
    t[x].ch[k^1] = y;
    pushup(y);
}
void splay(int x) {
    int y, z;
    push(x);
    while (!isroot(x)) {
        y = t[x].fa, z = t[y].fa;
        if (!isroot(y)) (t[z].ch[0] == y) ^ (t[y].ch[0] == x) ? rotate(x) : rotate(y);
        rotate(x);
    }
    pushup(x);
}
void access(int x) {
    for (int child = 0; x; child = x, x = t[x].fa) {
        splay(x);
        rc = child;
        pushup(x);
    }
}
void makeroot(int x) {access(x); splay(x); reverse(x);}
void split(int x, int y) {makeroot(x); access(y); splay(y);}
void link(int x, int y) {makeroot(x); t[x].fa = y;}
void cut(int x, int y) {
    split(x, y);
    if (t[y].ch[0] != x || rc) return;
    t[x].fa = t[y].ch[0] = 0;
    pushup(y);
}
int findroot(int x) {
    access(x); splay(x);
    while (lc) pushdown(x), x = lc;
    return x;
}
#undef lc
#undef rc

2. 图论算法

2.1 拓扑排序

vector<int> id(M + 1, 0);
void topo() {
    queue<int> q;
    for (int i = 1; i <= n; i++) {
        if (id[i] == 0) q.push(i);
    }
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v : g[u]) {
            id[v]--;
            if (id[v] == 0) q.push(v);
        }
    }
}

2.2 堆优化 Dijkstra

const int INF = 0x3f3f3f3f;
int dist[MAXN];
bool vis[MAXN]; 
void dijkstra(int s, int n) { 
    memset(dist, 0x3f, sizeof(int) * (n + 1));
    memset(vis, 0, sizeof(bool) * (n + 1));
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    dist[s] = 0;
    pq.push({0, s});
    while (!pq.empty()) {
        auto [d, u] = pq.top(); pq.pop();
        if (vis[u]) continue; 
        vis[u] = true; 
        for (auto [v, w] : g[u]) {
            if (!vis[v] && dist[v] > dist[u] + w) {
                dist[v] = dist[u] + w;
                pq.push({dist[v], v});
            }
        }
    }
}

2.3 并查集 DSU

int fa[MAXN], rk[MAXN];
void init(int n) {
    for (int i = 1; i <= n; i++) {
        fa[i] = i;
        rk[i] = 0;
    }
}
int find(int x) {
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}
bool unite(int x, int y) {
    int rx = find(x), ry = find(y);
    if (rx == ry) return false;
    if (rk[rx] < rk[ry]) swap(rx, ry);
    fa[ry] = rx;
    if (rk[rx] == rk[ry]) rk[rx]++;
    return true;
}

2.4 Kruskal 最小生成树

struct Edge {
    int u, v, w;
    bool operator<(const Edge& other) const {
        return w < other.w; 
    }
};
vector<Edge> edges;
long long kruskal(int n) {
    sort(edges.begin(), edges.end()); 
    init(n); 
    long long mst = 0;
    int cnt = 0;
    for (const Edge& e : edges) {
        if (unite(e.u, e.v)) { 
            mst += e.w;
            cnt++;
            if (cnt == n - 1) return mst; 
        }
    }
    return -1; 
}

2.5 SPFA 判负环

bool inq[N];
int dis[N], cnt[N];
bool spfa(int s) {
    fill(dis, dis + n + 1, INF);
    fill(inq, inq + n + 1, false);
    fill(cnt, cnt + n + 1, 0);
    queue<int> q;
    dis[s] = 0;
    q.push(s);
    inq[s] = true;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        inq[u] = false;
        for (auto [v, w] : g[u]) {
            if (dis[v] > dis[u] + w) {
                dis[v] = dis[u] + w;
                cnt[v] = cnt[u] + 1;
                if (cnt[v] >= n) return false;
                if (!inq[v]) {
                    q.push(v);
                    inq[v] = true;
                }
            }
        }
    }
    return true;
}

2.6 Floyd 全源最短路

const int N = 505;
int d[N][N];
void init_floyd(int n) {
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            d[i][j] = (i == j) ? 0 : I;
}
void floyd(int n) {
    for (int k = 1; k <= n; k++)
        for (int i = 1; i <= n; i++) {
            if (d[i][k] == I) continue;
            for (int j = 1; j <= n; j++) {
                if (d[k][j] == I) continue;
                d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
            }
        }
}

2.7 Johnson 全源最短路

vector<vector<int>> johnson() {
    vector<int> h(n + 1, 0), cnt(n + 1, 0);
    vector<bool> inq(n + 1, false);
    queue<int> q;
    for (int i = 1; i <= n; i++) {
        q.push(i);
        inq[i] = true;
    }
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        inq[u] = false;
        for (auto [v, w] : g[u]) {
            if (h[v] > h[u] + w) {      
                h[v] = h[u] + w;
                cnt[v] = cnt[u] + 1;
                if (cnt[v] >= n) return {}; 
                if (!inq[v]) {
                    q.push(v);
                    inq[v] = true;
                }
            }
        }
    }
    vector<vector<pair<int, int>>> ng(n + 1);
    for (int u = 1; u <= n; u++) for (auto [v, w] : g[u]) ng[u].push_back({v, w + h[u] - h[v]});
    vector<vector<int>> rs(n + 1, vector<int>(n + 1, INF));
    swap(g, ng);
    for (int s = 1; s <= n; s++) {
        dijkstra(s, n);                  
        for (int i = 1; i <= n; i++) if (dist[i] < INF) rs[s][i] = dist[i] - h[s] + h[i];
    }
    swap(g, ng);
    return rs;
}

2.8 网络最大流

const int N = 250;
ll graph[N][N], pre[N], flow[N];
ll bfs_flow(int s, int t) {
    memset(pre, -1, sizeof(pre));
    flow[s] = F;
    pre[s] = 0;
    queue<int> q;
    q.push(s);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        if (u == t) break;
        for (int v = 1; v <= n; v++) {
            if (v != s && graph[u][v] > 0 && pre[v] == -1) {
                pre[v] = u;
                q.push(v);
                flow[v] = min(flow[u], graph[u][v]);
            }
        }
    }
    if (pre[t] == -1) return -1;
    return flow[t];
}
ll maxflow(int s, int t) {
    ll mf = 0;
    while (1) {
        ll f = bfs_flow(s, t);
        if (f == -1) break;
        int cur = t;
        while (cur != s) {
            int fa = pre[cur];
            graph[fa][cur] -= f;
            graph[cur][fa] += f;
            cur = fa;
        }
        mf += f;
    }
    return mf;
}

2.9 割点

const int N = 2e4+5;
int low[N], num[N], dfn;
bool iscut[N];
vector<int> G[N];
void dfs(int u, int fa) {
    low[u] = num[u] = ++dfn;
    int child = 0;
    for (int i = 0; i < G[u].size(); i++) {
        int v = G[u][i];
        if (!num[v]) {
            child++;
            dfs(v, u);
            low[u] = min(low[u], low[v]);
            if (low[v] >= num[u] && fa != 0) iscut[u] = 1;
        }
        else if (num[v] < num[u] && v != fa) low[u] = min(low[u], num[v]);
    }
    if (fa == 0 && child >= 2) iscut[u] = 1;
}

3. 树

3.1 倍增法 LCA

vector<int> g[N];
int dep[N];
int up[N][20];
int lca(int a, int b) {
    if (dep[a] < dep[b]) swap(a, b);
    int df = dep[a] - dep[b];
    for (int j = 0; j < G; ++j)
        if (df & (1 << j)) a = up[a][j];
    if (a == b) return a;
    for (int j = G - 1; j >= 0; --j)
        if (up[a][j] != up[b][j]) {
            a = up[a][j];
            b = up[b][j];
        }
    return up[a][0];
}
void init_lca(int S) {
    queue<int> q;
    q.push(S);
    dep[S] = 0;
    for (int j = 0; j < G; ++j) up[S][j] = S;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v : aj[u]) {
            if (v == up[u][0]) continue;
            dep[v] = dep[u] + 1;
            up[v][0] = u;
            for (int j = 1; j < G; ++j)
                up[v][j] = up[up[v][j - 1]][j - 1];
            q.push(v);
        }
    }
}

3.2 树链剖分

struct Edge {int to, next;}edge[N << 1];
int head[N << 1], cnt, w[N], w_new[N], tree[N << 2], tag[N << 2], n, m, r, mod, son[N], id[N], fa[N], deep[N], siz[N], top[N], num;
void init() {
    for (int i=0; i < N << 1; i++) edge[i].next = -1, head[i] = -1;
    cnt = 0;
}
void addedge(int u, int v) {
    edge[cnt].to = v; edge[cnt].next = head[u]; head[u] = cnt++;
}
int ls(int x) {return x << 1;}
int rs(int x) {return x << 1 | 1;}
void addtag(int p, int pl, int pr ,int d) {
    tag[p] += d; tree[p] += (d * (pr - pl + 1)) % mod;
}
void pushup(int p) {
    tree[p] = 1LL * tree[ls(p)] + tree[rs(p)] % mod;
}
void pushdown(int p, int pl, int pr) {
    if (tag[p]) {
        int mid = (pl + pr) >> 1;
        addtag(ls(p), pl, mid, tag[p]);
        addtag(rs(p), mid+1, pr, tag[p]);
        tag[p] = 0;
    }
}
void build(int p, int pl, int pr) {
    tag[p] = 0;
    if (pl == pr) {tree[p] = w_new[pl] % mod; return;}
    int mid = (pl + pr) >> 1;
    build(ls(p), pl, mid);
    build(rs(p), mid+1, pr);
    pushup(p);
}
void update(int L, int R, int p, int pl, int pr, int d) {
    if (L <= pl && pr <= R) {addtag(p, pl, pr, d); return;}
    pushdown(p, pl, pr);
    int mid = (pl + pr) >> 1;
    if (L <= mid) update(L, R, ls(p), pl, mid, d);
    if (R > mid) update(L, R, rs(p), mid+1, pr, d);
    pushup(p);
}
int query(int L, int R, int p, int pl, int pr) {
    if (pl >= L && R >= pr) return tree[p] % mod;
    pushdown(p, pl, pr);
    int res = 0, mid = (pl + pr) >> 1;
    if (L <= mid) res += query(L, R, ls(p), pl, mid) % mod;
    if (R > mid) res += query(L, R, rs(p), mid+1, pr) % mod;
    return res % mod;
}
void dfs1(int x, int fa) {
    deep[x] = deep[fa] + 1;
    ::fa[x] = fa;
    siz[x] = 1;
    for (int i = head[x]; ~i; i = edge[i].next) {
        int y = edge[i].to;
        if (y != fa) {
            ::fa[y] = x;
            dfs1(y, x);
            siz[x] += siz[y];
            if (!son[x] || siz[son[x]] < siz[y]) son[x] = y;
        }
    }
}
void dfs2(int x, int topx) {
    id[x] = ++num;
    w_new[num] = w[x];
    top[x] = topx;
    if (!son[x]) return;
    dfs2(son[x], topx);
    for (int i = head[x]; ~i; i = edge[i].next) {
        int y = edge[i].to;
        if (y != fa[x] && y != son[x]) dfs2(y, y);
    }
}
void update_range(int x, int y, int z) {
    while (top[x] != top[y]) {
        if (deep[top[x]] < deep[top[y]]) swap(x, y);
        update(id[top[x]], id[x], 1, 1, n, z);
        x = fa[top[x]];
    }
    if (deep[x] > deep[y]) swap(x, y);
    update(id[x], id[y], 1, 1, n, z);
}
int query_range(int x, int y) {
    int ans = 0;
    while (top[x] != top[y]) {
        if (deep[top[x]] < deep[top[y]]) swap(x, y);
        ans += query(id[top[x]], id[x], 1, 1, n);
        ans %= mod;
        x = fa[top[x]];
    }
    if (deep[x] > deep[y]) swap(x, y);
    ans += query(id[x], id[y], 1, 1, n);
    return ans % mod;
}
void update_tree(int x, int k) {update(id[x], id[x] + siz[x] - 1, 1, 1, n, k);}
int query_tree(int x) {return query(id[x], id[x] + siz[x] - 1, 1, 1, n);}

3.3 文艺平衡树

const int N = 1e5+5;
int cnt, root;
struct Node {int ls, rs, num, pri, siz, lzy;}t[N];
void newnode(int x) {t[++cnt].siz = 1, t[cnt].ls = t[cnt].rs = 0, t[cnt].pri = rand(), t[cnt].num = x;}
void update(int u) {t[u].siz = t[t[u].ls].siz + t[t[u].rs].siz + 1;}
void pushdown(int u) {
    if (t[u].lzy) {
        swap(t[u].ls, t[u].rs);
        t[t[u].ls].lzy ^= 1, t[t[u].rs].lzy ^= 1;
        t[u].lzy = 0;
    }
}
void Split(int u, int x, int& L, int& R) {
    if (u == 0) {L = R = 0; return;}
    pushdown(u);
    if (t[t[u].ls].siz + 1 <= x) {
        L = u; Split(t[u].rs, x-t[t[u].ls].siz-1, t[u].rs, R);
    } else {
        R = u; Split(t[u].ls, x, L, t[u].ls);
    }
    update(u);
}
int Merge(int L, int R) {
    if (L == 0 || R == 0) return L+R;
    if (t[L].pri > t[R].pri) {
        pushdown(L);
        t[L].rs = Merge(t[L].rs, R); update(L); return L;
    } else {
        pushdown(R); 
        t[R].ls = Merge(L, t[R].ls); update(R); return R;
    }
}
void show(int u) {
    if (!u) return;
    pushdown(u);
    show(t[u].ls); printf("%d ", t[u].num); show(t[u].rs);
}
/*
int x, y; scanf("%d%d", &x, &y);
int L, R, p;
Split(root, y, L, R);
Split(L, x-1, L, p);
t[p].lzy ^= 1;
root = Merge(Merge(L, p), R);
*/

4. 区间查询

4.1 ST 表 RMQ

int st[N][20];
int lg[N];
int a[N];
void init_st(int n) {
    lg[1] = 0;
    for (int i = 2; i <= n; i++) lg[i] = lg[i / 2] + 1;
    for (int i = 1; i <= n; i++) st[i][0] = a[i];
    for (int k = 1; k < 20; k++)
        for (int i = 1; i + (1 << k) - 1 <= n; i++)
            st[i][k] = max(st[i][k - 1], st[i + (1 << (k - 1))][k - 1]);
            // 查 min 把 max 改成 min
}
int query_rmq(int L, int R) {
    int k = lg[R - L + 1];
    return max(st[L][k], st[R - (1 << k) + 1][k]);
}

4.2 线段树

int a[M];
int tr[4 * M];
int lz[4 * M];
void build(int nd, int l, int r) {
    if (l == r) {
        tr[nd] = a[l];
        return;
    }
    int m = (l + r) >> 1;
    build(nd << 1, l, m);
    build(nd << 1 | 1, m + 1, r);
    tr[nd] = tr[nd << 1] + tr[nd << 1 | 1];
}
void push_down(int nd, int l, int r) {
    if (lz[nd] == 0) return;
    int m = (l + r) >> 1;
    int lc = nd << 1, rc = nd << 1 | 1;
    lz[lc] += lz[nd];
    tr[lc] += lz[nd] * (m - l + 1);
    lz[rc] += lz[nd];
    tr[rc] += lz[nd] * (r - m);
    lz[nd] = 0;
}
void range_add(int nd, int l, int r, int L, int R, int v) {
    if (L <= l && r <= R) {
        tr[nd] += v * (r - l + 1);
        lz[nd] += v;
        return;
    }
    push_down(nd, l, r);
    int m = (l + r) >> 1;
    if (L <= m) range_add(nd << 1, l, m, L, R, v);
    if (R > m) range_add(nd << 1 | 1, m + 1, r, L, R, v);
    tr[nd] = tr[nd << 1] + tr[nd << 1 | 1];
}
int query_sum(int nd, int l, int r, int L, int R) {
    if (L <= l && r <= R) return tr[nd];
    push_down(nd, l, r);
    int m = (l + r) >> 1;
    int ans = 0;
    if (L <= m) ans += query_sum(nd << 1, l, m, L, R);
    if (R > m) ans += query_sum(nd << 1 | 1, m + 1, r, L, R);
    return ans;
}

4.3 单调队列 / 滑动窗口

int a[M], q[M];
int main() {
    int n, k;
    scanf("%d%d", &n, &k);
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
    int hd = 1, tl = 0;
    for (int i = 1; i <= n; i++) {
        while (hd <= tl && q[hd] < i - k + 1) hd++;
        while (hd <= tl && a[q[tl]] >= a[i]) tl--;
        q[++tl] = i;
        if (i >= k) printf("%d ", a[q[hd]]);
    }
    printf("\n");
    hd = 1;
    tl = 0;
    for (int i = 1; i <= n; i++) {
        while (hd <= tl && q[hd] < i - k + 1) hd++;
        while (hd <= tl && a[q[tl]] <= a[i]) tl--;
        q[++tl] = i;
        if (i >= k) printf("%d ", a[q[hd]]);
    }
}

4.4 单调栈

int a[M];
int as[M];
int sk[M], tp;
// 记得memset(as, 0, sizeof(as));
void ngr(int n) { // 右边第一个比他大的
    tp = 0;
    for (int i = n; i >= 1; i--) {
        while (tp > 0 && a[sk[tp]] <= a[i]) tp--;
        as[i] = (tp > 0) ? sk[tp] : 0;
        sk[++tp] = i;
    }
}
void nsr(int n) { // 右边第一个比他小的
    tp = 0;
    for (int i = n; i >= 1; i--) {
        while (tp > 0 && a[sk[tp]] >= a[i]) tp--;
        as[i] = (tp > 0) ? sk[tp] : 0;
        sk[++tp] = i;
    }
}
void ngl(int n) { // 左边第一个比他大的
    tp = 0;
    for (int i = 1; i <= n; i++) {
        while (tp > 0 && a[sk[tp]] <= a[i]) tp--;
        as[i] = (tp > 0) ? sk[tp] : 0;
        sk[++tp] = i;
    }
}
void nsl(int n) { // 左边第一个比他小的
    tp = 0;
    for (int i = 1; i <= n; i++) {
        while (tp > 0 && a[sk[tp]] >= a[i]) tp--;
        as[i] = (tp > 0) ? sk[tp] : 0;
        sk[++tp] = i;
    }
}

4.5 主席树

const int N = 2e5 + 5;
int cnt = 0;
int a[N], b[N], root[N];
struct {int L, R, sum;}tree[N << 5];
int build(int pl, int pr) {
    int rt = ++cnt;
    tree[rt].sum = 0;
    int mid = (pl + pr) >> 1;
    if (pl < pr) tree[rt].L = build(pl, mid), tree[rt].R = build(mid + 1, pr);
    return rt;
}
int update(int pre, int pl, int pr, int x) {
    int rt = ++cnt;
    tree[rt].L = tree[pre].L;
    tree[rt].R = tree[pre].R;
    tree[rt].sum = tree[pre].sum + 1;
    int mid = (pl + pr) >> 1;
    if (pl < pr) {
        if (x <= mid) tree[rt].L = update(tree[pre].L, pl, mid, x);
        else tree[rt].R = update(tree[pre].R, mid+1, pr, x);
    }
    return rt;
}
int query(int u, int v, int pl, int pr, int k) {
    if (pl == pr) return pl;
    int x = tree[tree[v].L].sum - tree[tree[u].L].sum;
    int mid = (pl + pr) >> 1;
    if (k <= x) return query(tree[u].L, tree[v].L, pl, mid, k);
    else return query(tree[u].R, tree[v].R, mid+1, pr, k - x);
}

// how to use: query(root[x - 1], root[y], 1, size, k);
// print(b[t])

5. 序列和排序

5.1 归并排序求逆序对

const int N = 300005;
int a[N], tmp[N];
ll mergesort(int l, int r) {
    if (l >= r) return 0;
    int m = l + (r - l) / 2;
    ll c = mergesort(l, m) + mergesort(m + 1, r);
    int i = l, j = m + 1, k = l;
    while (i <= m && j <= r) {
        if (a[i] <= a[j]) tmp[k++] = a[i++];
        else { c += m - i + 1; tmp[k++] = a[j++]; }
    }
    while (i <= m) tmp[k++] = a[i++];
    while (j <= r) tmp[k++] = a[j++];
    for (int p = l; p <= r; p++) a[p] = tmp[p];
    return c;
}

5.2 贪心版 LIS

vector<int> tl;
for (int x : a) {
    auto it = lower_bound(tl.begin(), tl.end(), x);
    if (it == tl.end()) tl.push_back(x);
    else *it = x;
}
cout << tl.size() << '\n';

5.3 离散化

int n; scanf("%d", &n);
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
vector<int> b = a;
sort(b.begin(), b.end());
b.erase(unique(b.begin(), b.end()), b.end());
for (int i = 0; i < n; i++) {
    int r = lower_bound(b.begin(), b.end(), a[i]) - b.begin() + 1;
    cout << r << (i == n - 1 ? '\n' : ' ');
}

6. 卡常时的救赎

6.1 int 快读

inline int read() {
    int x = 0, f = 1;
    char c = getchar();
    while (c < '0' || c > '9') {
        if (c == '-') f = -1;
        if (c == EOF) return 0;
        c = getchar();
    }
    while (c >= '0' && c <= '9') {
        x = x * 10 + (c - '0');
        c = getchar();
    }
    return x * f;
}

6.2 int 快写

inline void write(int x) {
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

7. 数论

7.1 快速幂

ull fastpow(ull a, ull b, ull p) {
    ull rs = 1;
    a %= p;
    while (b) {
        if (b & 1) rs = __int128(rs * a) % p;
        a = __int128(a * a) % p;
        b >>= 1;
    }
    return rs;
}

7.2 GCD & LCM

int gcd(int a, int b) {
    return b ? gcd(b, a % b) : a;
}
int lcm(int a, int b) {
    return a / gcd(a, b) * b;
}

7.3 CRT

void extend_gcd(ll a, int b, int& x, int& y) {
    if (b == 0) { x = 1, y = 0; return; }
    extend_gcd(b, a % b, x, y);
    int tmp = x;
    x = y;
    y = tmp - (a / b) * y;
}
int CRT(int a[], int b[], int n) {
    int md = 1;
    for (int i = 1; i <= n; i++) md *= a[i];
    ll ans = 0;
    for (int i = 1; i <= n; i++) {
        ll Mi = md / a[i];
        int x, y;
        extend_gcd(Mi, a[i], x, y);
        int inv = (x % a[i] + a[i]) % a[i];
        ans = (ans + (__int128)b[i] * Mi * inv) % md;
    }
    return ans;
}

7.4 Lucas & C(n,m)

vector<ll> fact, invfact;

void init_lucas(int p) {
    fact.resize(p);
    invfact.resize(p);
    fact[0] = 1;
    for (int i = 1; i < p; ++i) {
        fact[i] = fact[i - 1] * i % p;
    }
    invfact[p - 1] = fastpow(fact[p - 1], p - 2, p);
    for (int i = p - 1; i >= 1; --i) {
        invfact[i - 1] = invfact[i] * i % p;
    }
}
ll C(int n, int m, int p) {
    if (m < 0 || m > n) return 0;
    return fact[n] * invfact[m] % p * invfact[n - m] % p;
}
ll Lucas(ll n, ll m, int p) {
    ll res = 1;
    while (m > 0) {
        int ni = n % p;
        int mi = m % p;
        if (mi > ni) return 0;
        res = res * C(ni, mi, p) % p;
        n /= p;
        m /= p;
    }
    return res;
}

7.5 线性基

const int MB = 63;
ll p[MB];
bool zero;
void Insert(ll x) {
    for (int i = MB; i >= 0; i--) if (x >> i == 1) if (p[i] == 0) {p[i] = x; return;} else x ^= p[i];
    zero = 1;
}
bool check(ll x) {
    for (int i = MB; i >= 0; i--) {
        if (!((x >> i) & 1)) continue;
        if (!p[i]) return false;
        x ^= p[i];
    }
    return true;
}
ll qmax() {
    ll ans = 0;
    for (int i = MB; i >= 0; i--) ans = max(ans, ans ^ p[i]);
    return ans;
}
ll qmin() {
    if (zero) return 0;
    for (int i = 0; i <= MB; i++)
        if (p[i]) return p[i];
    return 0;
}
ll b[MB + 1];
int tot = 0;
void init_kth() {
    for (int i = MB; i >= 0; i--)
        for (int j = i - 1; j >= 0; j--)
            if (p[i] && ((p[i] >> j) & 1))
                p[i] ^= p[j];
    tot = 0;
    for (int i = 0; i <= MB; i++)
        if (p[i]) b[tot++] = p[i];
}
ll kth(ll k) {
    if (zero) {
        if (k == 1) return 0;
        k--;
    }
    if (k >= (1LL << tot)) return -1;
    ll res = 0;
    for (int i = 0; i < tot; i++)
        if ((k >> i) & 1) res ^= b[i];
    return res;
}

7.6 杜教筛

const int SN = 5e6+5;
int prime[N], mu[N];
bool vis[N];
ll phi[N];
unordered_map<int, int> summu;
unordered_map<int, ll> sumphi;
void init() {
    int cnt = 0;
    vis[0] = vis[1] = 1;
    phi[1] = mu[1] = 1;
    for (int i = 2; i < N; i++) {
        if (!vis[i]) {
            prime[cnt++] = i;
            mu[i] = -1;
            phi[i] = i - 1;
        }
        for (int j = 0; j < cnt && i * prime[j] < N; j++) {
            vis[i * prime[j]] = 1;
            if (i % prime[j]) mu[i * prime[j]] = -mu[i], phi[i * prime[j]]= phi[i] *phi[prime[j]];
            else {
                mu[i * prime[j]] = 0, phi[i * prime[j]] = phi[i] * prime[j];
                break;
            }
        }
    }
    for (int i = 1; i < N; i++) mu[i] += mu[i-1], phi[i] += phi[i-1];
}
ll getsmu(int x) {
    if (x < N) return mu[x];
    if (summu[x]) return summu[x];
    ll ans = 1;
    for (ll l = 2, r; l <= x; l = r + 1) {
        r = x / (x / l);
        ans -= (r - (l - 1)) * getsmu(x / l);
    }
    return summu[x] = ans;
}
ll getsphi(int x) {
    if (x < N) return phi[x];
    if (sumphi[x]) return sumphi[x];
    ll ans = x * ((ll) x + 1) / 2;
    for (ll l = 2, r; l <= x; l = r + 1) {
        r = x / (x / l);
        ans -= (r - (l - 1)) * getsphi(x / l);
    }
    return sumphi[x] = ans;
}

7.7 Pollard-Rho

mt19937 gen(random_device{}());
ll max_fac;
ll mul(ll a, ll b, ll p) {return (__int128)a * b % p;}
bool witness(ll a, ll n) {
    ll u = n - 1;
    int t = 0;
    while ((u & 1) == 0) u >>= 1, t++;
    ll x1 = fastpow(a, u, n);
    if (x1 == 1 || x1 == n - 1) return 0;
    for (int i = 1; i < t; i++) {
        ll x2 = mul(x1, x1, n);
        if (x2 == n - 1) return 0;
        if (x2 == 1) return 1;
        x1 = x2;
    }
    return 1;
}
bool miller_rabin(ll n) {
    if (n < 2) return 0;
    if (n == 2 || n == 3) return 1;
    if (n % 2 == 0) return 0;
    for (ll a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
        if (a >= n) break;
        if (witness(a, n)) return 0;
    }
    return 1;
}
ll pollard_rho(ll n) {
    if (n % 2 == 0) return 2;
    uniform_int_distribution<ll> dist(1, n - 1);
    ll c = dist(gen);
    ll x = dist(gen) + 1, y = x, d;
    ll i = 1, k = 2;
    while (true) {
        i++;
        x = (mul(x, x, n) + c) % n;
        d = gcd(y > x ? y - x : x - y, n);
        if (d != 1 && d != n) return d;
        if (y == x) return n;
        if (i == k) y = x, k <<= 1;
    }
}
void findfac(ll n) {
    if (n == 1) return;
    if (miller_rabin(n)) {
        max_fac = max(max_fac, n);
        return;
    }
    ll d = n;
    while (d >= n) d = pollard_rho(n);
    findfac(d);
    findfac(n / d);
}

7.8 Miller-Rabin

bool miller_rabin(ll n) {
    if (n < 2) return false;
    if (n == 2 || n == 3) return true;
    if (n % 2 == 0) return false;
    for (ll a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
        if (a >= n) break;
        if (witness(a, n)) return false;
    }
    return true;
}

7.9 exCRT

int n;
ll ai[N], mi[N];
ll mul(ll a, ll b, ll m) {
    ll res = 0;
    a %= m; b %= m;
    while (b > 0) {
        if (b&1) res = (res + a) % m;
        a = (a + a) % m;
        b >>= 1;
    }
    return res;
}
ll exgcd(ll a, ll b, ll& x, ll& y) {
    if (b == 0) {x = 1, y = 0; return a;}
    ll d = exgcd(b, a%b, y, x);
    y -= a / b * x;
    return d;
}
ll excrt() {
    ll x, y;
    ll m1 = mi[1], a1 = ai[1];
    ll ans = (a1 % m1 + m1) % m1;
    for (int i = 2; i <= n; i++) {
        ll a2 = ai[i], m2 = mi[i];
        ll a = m1, b = m2, c = (a2 - a1 % m2 + m2) % m2;
        ll d = exgcd(a, b, x, y);
        if (c % d != 0) return -1;
        x = mul(x, c / d, b/d);
        ans=a1+x*m1;
        m1=m2/d*m1;
        ans=(ans%m1+m1)%m1;
        a1=ans;
    }
    return ans;
}

7.10 矩阵快速幂

const int N = 100, mod = 1e9 + 7;
struct Matrix {
    int a[N + 5][N + 5];
    Matrix(){memset(a, 0, sizeof(a));}
    Matrix operator * (const Matrix &b) {
        Matrix c; 
        for(int i = 1; i <= N; i++) {
            for(int k = 1; k <= N; k++) {
                if (a[i][k] == 0) continue;
                for(int j = 1; j <= N; j++) {
                    c.a[i][j] = (c.a[i][j] + 1LL * a[i][k] * b.a[k][j]) % mod;
                }
            }
        }
        return c;
    }
}; 
Matrix qpow(Matrix a, long long exp, int n) {
    Matrix res;
    for (int i = 1; i <= n; i++)
        res.a[i][i] = 1;
    while (exp > 0) {
        if (exp & 1) {
            res = res * a;
        }
        a = a * a;
        exp >>= 1;
    }
    return res;
}

8. 计算几何

8.1 三维凸包

const int MAXN = 2010;
const double eps = 1e-8;
struct Point3 {
    double x, y, z;
    Point3(double x_ = 0, double y_ = 0, double z_ = 0) : x(x_), y(y_), z(z_) {}
    Point3 operator + (Point3 B) {return Point3(x + B.x, y + B.y, z + B.z);}
    Point3 operator - (Point3 B) {return Point3(x - B.x, y - B.y, z - B.z);}
    Point3 operator * (double k) {return Point3(x * k, y * k, z * k);}
    Point3 operator / (double k) {return Point3(x / k, y / k, z / k);}
};
typedef Point3 Vector3;
double Dot(Vector3 A, Vector3 B) {return A.x * B.x + A.y * B.y + A.z * B.z;}
Point3 Cross(Vector3 A, Vector3 B) {
    return Point3(A.y * B.z - A.z * B.y, A.z * B.x - A.x * B.z, A.x * B.y - A.y * B.x);
}
double Len(Vector3 A) {return sqrt(Dot(A, A));}
double Area2(Point3 A, Point3 B, Point3 C) {return Len(Cross(B - A, C - A));}
double volume4(Point3 A, Point3 B, Point3 C, Point3 D) {
    return Dot(Cross(B - A, C - A), D - A);
}
struct CH3D {
    struct face {
        int a,b,c;
        bool ok;
    };
    int n; 
    Point3 P[MAXN];
    int num;
    face F[8 * MAXN];
    int g[MAXN][MAXN];
    double dblcmp(Point3& p, face& f) {
        Point3 m = P[f.b]- P[f.a];
        Point3 n = P[f.c] - P[f.a];
        Point3 t = p - P[f.a];
        return Dot(Cross(m, n), t);
    }
    void deal(int p, int a, int b) {
        int f = g[a][b];
        face add;
        if (F[f].ok) {
            if (dblcmp(P[p], F[f]) > eps)
                dfs(p, f);
            else {
                add.a = b;
                add.b = a;
                add.c = p;
                add.ok = true;
                g[p][b] = g[a][p] = g[b][a] = num;
                F[num++] = add;
            }
        }
    }
    void dfs(int p, int now) {
        F[now].ok = 0;
        deal(p, F[now].b, F[now].a);
        deal(p, F[now].c, F[now].b);
        deal(p, F[now].a, F[now].c);
    }
    bool same(int s, int t) {
        Point3& a = P[F[s].a];
        Point3& b = P[F[s].b];
        Point3& c = P[F[s].c];
        return fabs(volume4(a, b, c, P[F[t].a])) < eps &&
               fabs(volume4(a, b, c, P[F[t].b])) < eps &&
               fabs(volume4(a, b, c, P[F[t].c])) < eps;
    }
    void create() {
        memset(g, 0, sizeof(g));
        int i, j, tmp;
        face add;
        num = 0;
        if (n < 4) return;
        bool flag = 1;
        for (i = 1; i < n; i++) {
            if (Len(P[0] - P[i]) > eps) {
                swap(P[1], P[i]);
                flag = 0;
                break;
            }
        }
        if (flag) return;
        flag = 1;
        for (i = 2; i < n; i++) {
            if (Len(Cross(P[0] - P[1], P[1] - P[i])) > eps) {
                swap(P[2], P[i]);
                flag = 0;
                break;
            }
        }
        if (flag) return;
        flag = 0;
        for (i = 3; i < n; i++) {
            if (fabs(Dot(Cross(P[0] - P[1], P[1] - P[2]), P[0] - P[i])) > eps) {
                swap(P[3], P[i]);
                flag = 0;
                break;
            }
        }
        if (flag) return;
        for (i = 0; i < 4; i++) {
            add.a = (i + 1) % 4;
            add.b = (i + 2) % 4;
            add.c = (i + 3) % 4;
            add.ok = 1;
            if (dblcmp(P[i], add) > 0) swap(add.b, add.c);
            g[add.a][add.b] = g[add.b][add.c] = g[add.c][add.a] = num;
            F[num++] = add;
        }
        for (i = 4; i < n; i++) {
            for (j = 0; j < num; j ++) {
                if (F[j].ok && dblcmp(P[i], F[j]) > eps) {
                    dfs(i, j);
                    break;
                }
            }
        }
        tmp = num;
        for (i = num = 0; i < tmp; i++) 
            if (F[i].ok) 
                F[num++] = F[i];
    }
    double area() {
        double res = 0;
        for (int i = 0; i < num; i++)
            res += Area2(P[F[i].a], P[F[i].b], P[F[i].c]);
        return res / 2.0;
    }
    double volume() {
        double res = 0;
        for (int i = 0; i < num; i++)
            res += volume4(Point3(0, 0, 0), P[F[i].a], P[F[i].b], P[F[i].c]);
        return fabs(res) / 6.0;
    }
};

7.2 最小球覆盖

struct Point {
    double x, y, z;
    Point() {}
    Point(double x_, double y_, double z_) : x(x_), y(y_), z(z_) {}
} p[MAXN];
double dist2(Point a, Point b) {return ((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z));}
double solve() {
    double ans = INF;
    Point cur = {0, 0, 0};
    double T = start;
    while (T > eps) {
        int f = 1; 
        rep(1, n, 1) if (dist2(p[i], cur) > dist2(p[f], cur)) f = i;
        ans = min(ans, sqrt(dist2(cur, p[f])));
        cur.x += (p[f].x - cur.x) * (T / start);
        cur.y += (p[f].y - cur.y) * (T / start);
        cur.z += (p[f].z - cur.z) * (T / start);
        T *= rate;
    }
    return ans;
}

7.3 最小圆覆盖

const double eps = 1e-12;
const int N = 1e5+5;
#define double long double
int sgn(double x) {
    if (fabsl(x) < eps) return 0;
    else return x < 0 ? -1 : 1;
}
struct Point {double x, y;}p[N];
double Distance(Point A, Point B) {return hypotl(A.x-B.x, A.y-B.y);}
Point circle_center(const Point a, const Point b, const Point c) {
    Point center;
    double a1 = b.x - a.x, b1 = b.y - a.y, c1 = (a1 * a1 + b1 * b1) / 2;
    double a2 = c.x - a.x, b2 = c.y - a.y, c2 = (a2 * a2 + b2 * b2) / 2;
    double d = a1 * b2 - a2 * b1;
    center.x = a.x + (c1 * b2 - c2 * b1) / d;
    center.y = a.y + (a1 * c2 - a2 * c1) / d;
    return center;
}
void min_cover_circle(Point* p, int n, Point& c, double& r) {
    random_shuffle(p, p+n);
    c = p[0], r = 0;
    for (int i = 0; i < n; i++) if (sgn(Distance(p[i], c) - r) > 0) {
        c = p[i], r = 0;
        for (int j = 0; j < i; j++) if (sgn(Distance(p[j], c) - r) > 0) {
            c.x = (p[i].x + p[j].x) / 2;
            c.y = (p[i].y + p[j].y) / 2;
            r = Distance(p[j], c);
            for (int k = 0; k < j; k++) if (sgn(Distance(p[k], c) - r) > 0) {
                c = circle_center(p[i], p[j], p[k]);
                r = max({Distance(p[i], c), Distance(p[j], c), Distance(p[k], c)});
            }
        }
    }
}

8. 字符串

8.1 Trie

struct Trie {
    static const int N = 1e5 + 5, A = 26;
    int son[N][A], pc[N], ec[N], tot = 0;
    Trie() { init(); }
    void init() {
        memset(son, 0, sizeof son);
        memset(pc, 0, sizeof pc);
        memset(ec, 0, sizeof ec);
        tot = 0;
    }
    static int id(char ch) { return ch - 'a'; }
    void insert(const string& s) {
        int u = 0; pc[u]++;
        for (char ch : s) {
            int c = id(ch);
            if (!son[u][c]) son[u][c] = ++tot;
            u = son[u][c]; pc[u]++;
        }
        ec[u]++;
    }
    int count(const string& s) const {
        int u = 0;
        for (char ch : s) {
            int c = id(ch);
            if (!son[u][c]) return 0;
            u = son[u][c];
        }
        return ec[u];
    }
    int prefix(const string& s) const {
        int u = 0;
        for (char ch : s) {
            int c = id(ch);
            if (!son[u][c]) return 0;
            u = son[u][c];
        }
        return pc[u];
    }
    void erase(const string& s) {
        int u = 0; pc[u]--;
        for (char ch : s) { u = son[u][id(ch)]; pc[u]--; }
        ec[u]--;
    }
    int size() const { return tot + 1; }
};

8.2 AC自动机(简单版)

const int N = 1e6+5;
struct node {
    int son[26], end, fail;
}t[N];
int cnt;
void Insert(char* s) {
    int now = 0;
    for (int i = 0; s[i]; i++) {
        int ch = s[i] - 'a';
        if (t[now].son[ch] == 0) t[now].son[ch] = ++cnt;
        now = t[now].son[ch];
    }
    t[now].end++;
} 
void getFail () {
    queue<int> q;
    for (int i = 0; i < 26; i++) if (t[0].son[i]) q.push(t[0].son[i]);
    while (!q.empty()) {
        int now = q.front(); q.pop();
        for (int i = 0; i < 26; i++) {
            if (t[now].son[i]) {t[t[now].son[i]].fail = t[t[now].fail].son[i]; q.push(t[now].son[i]);}
            else t[now].son[i] = t[t[now].fail].son[i];
        }
    }
}
int query(char* s) { // 不是模式串
    int ans = 0, now = 0;
    for (int i = 0; s[i]; i++) {
        int ch = s[i] - 'a';
        now = t[now].son[ch];
        int tmp = now;
        while (tmp && t[tmp].end != -1) {
            ans += t[tmp].end;
            t[tmp].end = -1;
            tmp = t[tmp].fail;
        }
    }
    return ans;
}