跳到正文

个人记录

【模板】模板整理贴

Kendieer约 146 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月15日
篇幅
约 146 分钟

版本

  1. v2当前
  2. v1

Last updated: 2025/10/02


1.数学

1.1 数论

1.1.1 线性筛

C++
namespace Prime{
    std::vector<int> primes;
    std::vector<bool> np;
    constexpr int N = 1e7+7;
    void Eratosthenes(){ // 埃式筛
        const int ed = std::sqrt(N);
        for (int i = 2;i <= ed;i ++){
            if (np[i]) continue;
            for (int j = i<<1;j < N;j += i) np[j] = 1;
        }
        for (int i = 2;i < N;i ++)
            if (!np[i]) primes.push_back(i); // 仅统计用
    }
    void Euler() { // 欧式筛
        for (int i = 2; i < N; ++i) {
            if (!np[i]) primes.push_back(i);
            for (auto &x: primes) {
                if (i * x >= N) break;
                np[i * x] = 1;
                if (i % x == 0) break;
            }
        }
    }
    void init(){
        np.resize(N);
        np[0] = np[1] = 1;
        Eratosthenes();
    }
}

1.1.2 拓展欧几里得算法(exgcd)

C++
using i64 = long long;
i64 exgcd(i64 a, i64 b, i64 &x, i64 &y) {
    if (!b) return x = 1, y = 0, a;
    i64 g = exgcd(b, a % b, x, y), t = x;
    x = y, y = t - (a / b) * x;
    return g;
}

1.1.3 中国剩余定理及其拓展(CRT & exCRT)

C++
namespace NumberTheory {
    using ll = long long;
    ll exgcd(ll a, ll b, ll &x, ll &y) {
        if (!b) return x = 1, y = 0, a;
        ll g = exgcd(b, a % b, x, y), t = x;
        x = y, y = t - (a / b) * x;
        return g;
    }
    ll multi(ll a, ll b, ll p) { // 龟速乘
        ll ans = 0;
        for (; b; b >>= 1, a += a, a %= p) if (b & 1) ans += a, ans %= p;
        return ans;
    }
    ll crt(int n, std::vector <ll> &m, std::vector <ll> &p) { // x%m=p
        ll LCM = 1, ans = 0;
        for (int i = 0; i < n; i++) LCM *= m[i];
        assert(LCM);
        for (int i = 0; i < n; i++) {
            ll cm = LCM / m[i], x, y;
            exgcd(cm % m[i], m[i], x, y), x = (x % m[i] + m[i]) % m[i];
            ans += multi(multi(p[i], cm, LCM), x, LCM);
            ans %= LCM;
        }
        return ans;
    }
    ll excrt(int n, std::vector <ll> &m, std::vector <ll> &p) {
        ll LCM = 1, ans = 0;
        for (int i = 0; i < n; i++) {
            ll x, y, g = exgcd(LCM, m[i], x, y), c = ((p[i] - ans) % m[i] + m[i]) % m[i];
            if (c % g) return -1;
            x = (multi(x, c / g, m[i] / g) + (m[i] / g)) % (m[i] / g); // x0
            ans += multi(x, LCM, LCM * (m[i] / g)), LCM = LCM * (m[i] / g);
        }
        return ans;
    }
}

1.1.4 欧拉定理(欧拉降幂)

C++
struct NumberTheory{
    using ll = long long;
    ll EulerFunction(ll x){ // 求单一数量的欧拉函数
        ll ans = x;
        for (ll i = 2;i*i <= x;i++){
            if (x % i == 0){
                ans = ans / i * (i-1);
                while(ans % i == 0) ans /= i;
            }
        }
        if (x > 1) ans = ans / x * (x-1);
        return ans;
    }

    ll EulerTheorem(ll a,std::string& x,ll m){
        std::function<ll(ll,ll,ll)> quickPower = [](ll a,ll p,ll m)->ll{
            ll r = 1;
            for (;p;p>>=1,a*=a,a%=m) if (p&1) r *= a,r %= m;
            return r;
        };
        ll d = std::gcd(a,m),Phi = EulerFunction(m),P = 0;
        bool less = true;
        for (int i = x.size()-1;i >= 0;i--)
            P *= 10,P += x[i]-'0',less = less & (P < Phi),P %= Phi;
        if (d == 1) return quickPower(a,P,m);
        else {
            if (less) return quickPower(a,P,m);
            else return quickPower(a,P+Phi,m);
        }
    }
};

1.1.5 欧拉函数

C++
namespace NumberTheory{
    constexpr int N = 1E7;
    std::vector<bool> np;
    std::vector<int> phi,primes;
    void initPhi(const int siz = N){
        np.resize(siz+1),phi.resize(siz+1,1);
        for (int i = 2;i <= siz;i ++){
            if (!np[i]) {
                phi[i] = i-1;
                primes.push_back(i);
            }
            for (const int x : primes){
                if (x * i > siz) break;
                np[x * i] = 1;
                if (i % x == 0) {
                    phi[i * x] = phi[i] * x;
                    break;
                }
                phi[x * i] *= (x - 1) * phi[i];
            }
        }
    }
}

1.1.6 原根

仅参考,实际可以预先处理出原根直接使用。

C++
std::vector<bool> withRoot;
std::vector<std::vector<int>> fac; // 分解因数

using NumberTheory::phi;
int getPrimitiveRoot(long long MOD){
    int p = phi[MOD];
    if (MOD == 2 || MOD == 4) return MOD - 1;
    if (!withRoot[MOD]) return 0;
    // 当 MOD ∈ Prime^x * 1/2 (x >= 1,Prime > 2) 或者 MOD = 2/4 才有原根
    DynModInt::setMod(MOD);
    for (int i = 2;i < MOD;i ++){
        if (DynModInt::Pow(i,p)() != 1) continue;
        bool flag = 1;
        for (auto const& j : fac[p]){
            if (DynModInt::Pow(i,j)() == 1) {
                flag = 0;
                break;
            }
        }
        if (flag) return i;
    }
    return 0;
}

常见质数模数的最小原根

modmod998244353998244353109+710^9+7109+910^9+921474836472147483647999999937999999937167772161167772161
gg3355131377111133

1.1.7 二次剩余

需要使用 ModInt 类和对 Complex<Z> 特化后的模板类

Cipolla 算法
C++
Z i2;// i²
template<>
struct Complex<Z>{
    Z real,imag;
    constexpr Complex operator*=(const Complex& x){
        Z rl = real * x.real + imag * x.imag * i2;
        imag = x.imag * real + x.real * imag;
        real = rl;
        return *this;
    }
    constexpr friend Complex operator*(const Complex& x,const Complex y){
        Complex r = x;
        return (r *= y);
    }
    constexpr static Complex Pow(Complex x,long long p){
        Complex res = {1,0};
        for (;p;p >>= 1,x *= x){
            if (p&1) res *= x;
        }
        return res;
    }
};
std::mt19937_64 rnd(time(0));

Z Quad_Restdue(Z n){
    if (n() == 0) return 0;
    long long p = MOD;
    assert(Z::Pow(n,(p-1)/2)() == 1);
    Z a = rnd() % (p-1)+1;
    while (Z::Pow(a,(p-1)/2)() != 1 || Z::Pow(a*a-n,(p-1)/2)() == 1){
        a = rnd() % (p-1)+1;
    }
    i2 = a*a-n;
    return Complex<Z>::Pow({a,1},(p+1)/2).real;
}

1.2 组合数学

1.2.1 排列组合及卢卡斯定理

需要配合 ModInt<MOD> 使用。

C++
template <long long MOD>
struct Combination{
    int siz = 0;
    using Z = ModInt<MOD>;
    std::vector<Z> fact,inv;
    Combination():siz(1),fact(1,1),inv(1,1){}
    void expend(int size){
        if (siz >= size) return;
        fact.resize(size),inv.resize(size);
        for (int i = siz;i < size;i++) fact[i] = fact[i-1] * i;
        inv[size-1] = 1 / fact[size-1];
        for (int i = size - 2;i >= siz;i--) inv[i] = inv[i+1] * (i+1);
        siz = size;
    }
    void check(int size){
        if (siz >= size) return;
        int n = siz;
        while(n < size) n <<= 1;
        n = std::min<unsigned int>(n,MOD);
        expend(n);
    }
    Z A(int n,int m){
        if (n < 0 || m < 0 || n < m) return 0;
        check(n+1);
        return fact[n]*fact[n-m];
    }
    Z C(int n,int m){
        if (n < 0 || m < 0 || n < m) return 0;
        if (n < MOD && m < MOD) {
            check(n+1);
            return fact[n] * inv[m] * inv[n - m];
        } else return C(n/MOD,m/MOD)*C(n%MOD,m%MOD);
    }
};
using CB = Combination<998244353>;

1.3 线性代数

1.3.1 矩阵快速幂

C++
template<typename T>
struct Matrix{
    std::vector<std::vector<T>> value;
    int siz = 0;
    Matrix(int siz = 0):siz(siz),value(siz,std::vector<T>(siz,0)){}
    const friend Matrix operator*(Matrix& a,Matrix& b){
        assert(a.siz == b.siz);
        Matrix r(a.siz);
        for (int i = 0; i < r.siz; ++i)
            for (int j = 0; j < r.siz; ++j)
                for (int k = 0; k < r.siz; ++k)
                    r.value[i][j] += a.value[i][k] * b.value[k][j];
        return r;
    }
    const Matrix& operator *=(Matrix &x){
        Matrix r = *this*x;
        value = r.value;
        return *this;
    }
    const Matrix& operator +=(Matrix &x){
        assert(siz==x.siz);
        for (int i = 0; i < siz; ++i)
            for (int j = 0; j < siz; ++j)
                value[i][j] += x.value[i][j];
        return *this;
    }
    std::vector<T>& operator[](int idx){
        return value[idx];
    }
    const friend Matrix operator + (Matrix x,Matrix &y){
        return x += y;
    }
    const static Matrix Power(Matrix raw,ll p){
        Matrix r(raw.siz);
        for (int i = 0;i < raw.siz;i ++) r.value[i][i] = T(1);
        for (;p;p >>= 1,raw *= raw) if (p&1) r *= raw;
        return r;
    }
    const friend std::istream& operator>>(std::istream& is,Matrix& m){
        for (int i = 0; i < m.siz; ++i)
            for (int j = 0; j < m.siz; ++j)
                is >> m.value[i][j];
        return is;
    }
    const friend std::ostream& operator<<(std::ostream& os,Matrix& m){
        for (int i = 0; i < m.siz; ++i)
            for (int j = 0; j < m.siz; ++j)
                os << m.value[i][j] << " \n"[j==m.siz-1];
        return os;
    }
};

1.3.2 高斯消元

C++
namespace Gauss{
    using ld = long double;
    using std::vector;
    constexpr ld eps = 1E-6;
    int work(vector<vector<ld>> &e){
        assert(e.size()+1 == e[0].size());
        int n = e.size(),m = 0;
        for (int i = 0;i < n;i ++){
            int mx = m;
            for (int j = m+1;j < n;j ++){
                if (fabsl(e[j][i]) > fabsl(e[mx][i])) mx = j;
            }
            if (fabsl(e[mx][i]) <= eps) continue;
            else swap(e[mx],e[m]);
            ld d = 1 / e[m][i];
            for (int j = 0;j <= n;j ++) e[m][j] *= d;
            assert(fabsl(e[m][i]-1) <= eps);
            for (int j = 0;j < n;j ++) {
                if (j == m || fabsl(e[j][i]) <= eps) continue;
                ld k = e[j][i];
                for (int p = 0;p <= n;p ++){
                    e[j][p] -= k * e[m][p];
                }
            }
            m++;
        }
        if (m == n) return 0;
        else {
            while(m < n){
                if (fabsl(e[m++][n]) > eps) return -1;
            }
            return 1;
        }
    }
};
using namespace Gauss;

1.3.3 线性基

C++
struct Basis{
    std::vector<long long> base;
    int size;
    Basis(int siz = 32):base(siz+1,0),size(siz){}
    bool operator>>(long long x){ // insert
        if (!x) return false;
        for(int i=size;i >= 0;i--){
            if (x>>i&1){
                if (base[i]) x ^= base[i];
                else {
                    base[i] = x;
                    return true;
                }
            }
        }
        return false;
    }
    long long operator[](int index){ // 获取对应位基底
        return base[index];
    }
};

1.4 生成函数以及多项式

1.4.1 快速傅里叶变换(FFT)

需要配合 Complex 类使用。

C++
// 需要配合 Complex 类使用
namespace FFT{
    using Comp = Complex<double>;
    using Poly = std::vector<Comp>;
    using i64 = long long;

    std::vector<int> revi;
    const double PI = acos(-1);
    inline void FFT(const int len,Poly& arr,const short sign){
        for (int i = 0;i < len;i ++)
            if (i < revi[i]) std::swap(arr[i],arr[revi[i]]);
        for (int p = 2;p <= len;p <<= 1){
            int mid = p >> 1;
            Comp Wn(std::cos(PI/mid),sign*std::sin(PI/mid));
            for (int l = 0;l < len;l += p){
                Comp w(1),tmp;
                for (int i = l,j = 0;j < mid;i ++,j ++,w *= Wn){
                    tmp = arr[i+mid] * w;
                    arr[i+mid] = arr[i] - tmp;
                    arr[i] += tmp;
                }
            }
        }
    }
    std::vector<i64> work(const std::vector<i64>& A,const std::vector<i64>& B){
        int limit = 1,limBit = 0;
        while (limit <= (A.size() + B.size())) limit <<= 1,limBit ++;
        // 蝴蝶变换
        revi.resize(limit);
        for (int i = 1;i < limit;i ++)
            revi[i] = revi[i] = (revi[i>>1]>>1) | ((i&1)<<(limBit-1));
        Poly poly(limit);
        for (int i = 0;i < A.size();i ++) poly[i].real = A[i];
        for (int i = 0;i < B.size();i ++) poly[i].imag = B[i];
        FFT(limit,poly,1);
        for (int i = 0;i < limit;i ++) poly[i] *= poly[i];
        FFT(limit,poly,-1);
        std::vector<i64> ans(A.size()+B.size()+1);
        for (int i = 0;i < ans.size();i++) ans[i] = std::round(poly[i].imag/2/limit);
        return ans;
    }
}
using namespace FFT;

1.4.2 快速沃尔什变换(FWT)

需要配合 ModInt 使用。

C++
struct FWT{
    using Z = ModInt<998244353>;
    using Poly = std::vector<Z>;
    Poly ele;
    int siz = 0;
    FWT(int n){
        while (n != n&(-n)) n += n&(-n);
        siz = n;
        ele.resize(n);
    }
    Z& operator[](int idx){return ele[idx];}
    void OR(int sign = 1){
        for (int len = 2;len <= siz;len <<= 1){
            int mid = len >> 1;
            for (int l = 0;l < siz;l += len){
                for (int i = l,j = l + mid;j < l + len;i++,j++){
                    ele[j] += ele[i] * sign;
                }
            }
        }
    }
    void AND(int sign = 1){
        for (int len = 2;len <= siz;len <<= 1){
            int mid = len >> 1;
            for (int l = 0;l < siz;l += len){
                for (int i = l,j = l + mid;j < l + len;i ++,j ++){
                    ele[i] += ele[j] * sign;
                }
            }
        }
    }
    void XOR(int sign = 1){
        Z inv2 = ~Z(2);
        for (int len = 2;len <= siz;len <<= 1){
            int mid = len >> 1;
            for (int l = 0;l < siz;l += len){
                for (int i = l,j = l + mid;j < l + len;i ++,j ++){
                    Z x = ele[i],y = ele[j];
                    ele[i] = x+y;
                    ele[j] = x-y;
                    if (sign == -1) ele[i] *= inv2,ele[j] *= inv2;
                }
            }
        }
    }
    friend FWT operator|(FWT a,FWT b){
        a.OR(1),b.OR(1);
        FWT c(std::max(a.siz,b.siz));
        for (int i = 0;i < c.siz;i ++) c[i] = a[i] * b[i];
        c.OR(-1);
        return c;
    }
    friend FWT operator&(FWT a,FWT b){
        a.AND(1),b.AND(1);
        FWT c(std::max(a.siz,b.siz));
        for (int i = 0;i < c.siz;i ++) c[i] = a[i] * b[i];
        c.AND(-1);
        return c;
    }
    friend FWT operator^(FWT a,FWT b){
        a.XOR(1),b.XOR(1);
        FWT c(std::max(a.siz,b.siz));
        for (int i = 0;i < c.siz;i ++) c[i] = a[i] * b[i];
        c.XOR(-1);
        return c;
    }
};

1.5 数值计算

1.5.1 拉格朗日插值法

1.5.1.1 x 无限制版本(求f(x)系数版本)

普适所有坐标版本,时间复杂度为 O(n2)O(n^2)。

C++
template<typename T>
std::vector<T> Lagrange_Interpolation(std::vector<T>& x,std::vector<T>& y){
    int n = x.size();
    std::vector<T> f(n),g(n+1),px(n,1);
    g[0] = 1;
    for (int i = 0;i < n;i ++){
        for (int j = i;j >= 0;j --){
            g[j+1] += g[j];
            g[j] *= -x[i];
        }
    }
    for (int i = 0;i < n;i ++){
        for (int j = 0;j < n;j ++){
            if (i == j) continue;
            px[i] *= x[i] - x[j];
        }
    }
    for (int i = 0;i < n;i ++){
        T c = y[i] / px[i],h = g[n];
        for (int j = n-1;j >= 0;j --){
            f[j] += h * c;
            h = g[j] + h * x[i];
        }
    }
    return f;
}
1.5.1.2 x 为连续正整数版本

其插值式子为:

f(x)=∑i=1nyi∏i≠jnx−ji−j=∑i=1nyi(−1)n−iprei−1⋅sufi+1(i−1)!(n−1)!\begin{equation}\begin{split}f(x)&=\sum_{i=1}^{n}y_i\prod_{i\neq j}^{n}\frac{x-j}{i-j}\\ &=\sum_{i=1}^{n}y_i(-1)^{n-i}\frac{pre_{i-1}\cdot suf_{i+1}}{(i-1)!(n-1)!}\end{split}\end{equation}
C++
template<typename T>
T Lagrange_Interpolation(std::vector<T> y,T x){ // For x=[1..n]
    int n = y.size();
    std::vector<T> fac(n+1,1),pre(n+2),suf(n+2);
    for (int i = 1;i <= n;i ++) fac[i] = fac[i-1] * i;
    pre[0] = suf[n+1] = 1;
    for (int i = 1;i <= n;i ++) pre[i] = pre[i-1] * (x - i);
    for (int i = n;i >= 1;i --) suf[i] = suf[i+1] * (x - i);
    T res = 0;
    for (int i = 1;i <= n;i ++){
        res += y[i-1] * pre[i-1] * suf[i+1] / (fac[i-1] * fac[n-i]) * ((n-i) % 2 == 0 ? 1 : -1);
    }
    return res;
}

1.6 其他数学

1.6.1 分数

C++
struct Fraction{
    long long p=1,q=1;
    int sign = 1;
    Fraction(long long P=0,long long Q=1){
        if (P) sign=P/std::abs(P),p=std::abs(P);
        else p = 0,sign = 1;
        q=Q;
        update();
    }
    void update(){
        assert(q != 0);
        long long cd = std::gcd(p,q);
        p /= cd,q /= cd;
    }
    void common(long long divisor){
        long long times = divisor / std::gcd(divisor,q);
        p *= times,q *= times;
    }
    void common(Fraction &f){
        common(f.q);
    }
    friend std::ostream& operator<<(std::ostream &os,Fraction f){
        if (f.sign < 0) os << '-';
        if (f.q != 1) os << f.p << "/" << f.q;
        else os << f.p;
        return os;
    }
    Fraction& operator+=(Fraction y){
        common(y),y.common(*this);
        p *= sign,p += y.p * y.sign;
        if (p) sign = p / std::abs(p),p = std::abs(p);
        else p = 0,sign = 1;
        update();
        return *this;
    }
    friend Fraction operator+(Fraction x,Fraction y){
        Fraction ans = x;
        return ans += y;
    }
    Fraction& operator-=(Fraction y){
        y.sign *= -1;
        this->operator+=(y);
        return *this;
    }
    friend Fraction operator-(Fraction x,Fraction y){
        Fraction ans = x;
        return ans -= y;
    }
    Fraction& operator*=(Fraction y){
        p *= y.p,q *= y.q;
        sign *= y.sign;
        update();
        return *this;
    }
    friend Fraction operator*(Fraction x,Fraction y){
        Fraction ans = x;
        return ans *= y;
    }
    Fraction& operator/=(Fraction y){
        std::swap(y.p,y.q);
        return this->operator*=(y);
    }
    friend Fraction operator/(Fraction x,Fraction y){
        Fraction ans = x;
        return ans /= y;
    }
    friend auto operator<=>(Fraction x,Fraction y){
        x.common(y),y.common(x);
        return x.p * x.sign <=> y.p * y.sign;
    }
    bool operator==(Fraction b) const {
        Fraction a = *this;
        a.update(),b.update();
        return (a.sign == b.sign && a.p == b.p && a.q == b.q);
    }
};

1.6.2 高精度运算

C++
struct BigInt{
    std::vector<int> num;
    int sign = 1,size = 0;
    BigInt(std::string raw){
        while (raw.size()) {
            int ch = raw.back();raw.pop_back();
            assert(ch == '-' || std::isdigit(ch));
            if (ch == '-') sign = -1;
            else num.push_back(ch - '0');
        }
        refresh();
    }
    BigInt(long long raw = 0){
        if (raw < 0) sign = -1,raw = -raw;
        while (raw) num.push_back(raw%10),raw /= 10;
        refresh();
    }
    BigInt& operator=(long long x){
        return *this = BigInt(x);
    }
    std::string to_string(){
        refresh();
        if (num.empty()) return "0";
        std::string str = "";
        if (sign == -1) str += "-";
        for (int i = size-1;i >= 0;i--)
            str += num[i]+'0';
        return str;
    }
    int& operator[](int index){ // 访问超过size的内容会自动扩容
        assert(index >= 0); // 防止越界
        if (index >= num.size()) num.resize(index+1,0);// 扩容
        return num[index];
    }
    void refresh(){ // 刷新当前位数,删除无用前导0
        while (num.size() && !num.back()) num.pop_back();
        size = num.size();
        if (!size) sign = 1;
    }
    friend bool operator<(BigInt& x,BigInt& y){
        x.refresh(),y.refresh();
        if (x.sign != y.sign) return x.sign < y.sign;
        bool inv = x.sign == -1;
        if (x.size != y.size) return (x.size < y.size) ^ inv;
        for (int i = x.size - 1;i >= 0;i--)
            if (x[i] != y[i]) return (x[i] < y[i]) ^ inv;
        return false;
    }
    static BigInt unsigned_add(BigInt x,BigInt y){ // 无符号加法
        x.refresh(),y.refresh();
        int sz = std::max(x.size,y.size);
        BigInt z = 0LL;
        for (int i = 0; i < sz; i++)
            z[i] += x[i] + y[i],z[i+1] += z[i]/10, z[i] %= 10;
        z.refresh();
        return z;
    }
    static BigInt unsigned_remove(BigInt x,BigInt y){ // 无符号减法
        x.sign = 1,y.sign = 1;
        if (x < y) std::swap(x,y);
        int sz = x.size;
        for (int i = 0; i < sz; i++) {
            if (i < y.size) x[i] -= y[i];
            if (x[i] < 0) x[i] += 10,x[i+1]--;
        }
        x.refresh();
        return x;
    }
    friend BigInt operator+(BigInt x,BigInt y){
        if (y.sign == -1) return y.sign = 1,x-y;
        if (x.sign == -1) return x.sign = 1,y-x;
        return unsigned_add(x,y);
    }
    friend BigInt operator-(BigInt x,BigInt y){
        BigInt z;
        if (y.sign == -1) return y.sign = 1,x+y;
        if (x.sign == -1) return z = unsigned_add(x,y),z.sign = -1,z;
        z = unsigned_remove(x,y),z.sign = (x < y ? -1 : 1);
        return z;
    }
    friend BigInt operator*(BigInt x,BigInt y){
        BigInt z;
        x.refresh(),y.refresh();
        for (int i = 0; i < x.size; ++i)
            for (int j = 0; j < y.size; ++j)
                z[i+j] += x[i]*y[j],z[i+j+1] += z[i+j]/10,z[i+j] %= 10;
        z.sign = x.sign * y.sign,z.refresh();
        return z;
    }
    friend BigInt operator/(BigInt x,BigInt y){
        BigInt z;
        x.refresh(),y.refresh();
        assert(y.size > 0);
        int sz = x.size - y.size;
        for (int i = sz;i >= 0; i--){
            BigInt t = y << i;
            while (!(x < t)) z[i]++,x -= t;
        }
        z.sign = x.sign * y.sign,z.refresh();
        return z;
    }
    friend BigInt operator%(BigInt x,BigInt y){
        x.refresh(),y.refresh();
        assert(y.size > 0);
        for (int i = x.size - y.size;i >= 0;i--){
            BigInt t = y << i;
            while (!(x < t)) x -= t;
        }
        return x;
    }
    friend BigInt operator<<(BigInt x,int y){ // x * 10^y
        std::string raw = x.to_string();
        for (;y > 0;y--) raw += "0";
        return BigInt(raw);
    }
    BigInt& operator += (BigInt y){
        return *this = *this + y;
    }
    BigInt& operator -= (BigInt y){
        return *this = *this - y;
    }
    BigInt& operator *= (BigInt y){
        return *this = *this * y;
    }
    BigInt& operator /= (BigInt y){
        return *this = *this / y;
    }
    BigInt& operator %= (BigInt y){
        return *this = *this % y;
    }
    friend std::ostream& operator<<(std::ostream& os,BigInt x){
        return os << x.to_string();
    }
    friend std::istream& operator>>(std::istream& is,BigInt &x){
        std::string str;
        is >> str,x = BigInt(str);
        return is;
    }
};

2.字符串

2.1 字符串算法

2.1.1 KMP(border 数组)

C++
struct KMP{
    std::vector<int> nxt;
    std::string match;
    KMP(const std::string &base):nxt(base.size()),match(base){
        for(int p=0,itr=1;itr < base.size();){
            if (base[itr] == base[p]) nxt[itr++] = ++p;
            else {
                if (!p) nxt[itr++] = 0;
                else p=nxt[p-1];
            }
        }
    }
    std::vector<int> operator()(const std::string &str){ // 获得每个子串的位置数组
        std::vector<int> ans;
        for(int p = 0,itr = 0;itr < str.size();){
            if (match[p] == str[itr]) p++,itr++;
            else {
                if (!p) itr++;
                else p = nxt[p-1];
            }
            if (p == match.size()){
                ans.push_back(itr-match.size());
                p = nxt[p-1];
            }
        }
        return ans;
    }
};

2.1.2 Manacher

C++
namespace Manacher{
    using Container=std::string;
    void work(Container &str,std::vector<int> &ans){
        std::vector<int> ch(str.size()*2+3,-1);
        ans = std::vector<int>(str.size()*2+3,0);
        ch[0] = 448268,ch[ch.size()-1] = -ch[0];
        for (int i = 0; i < str.size(); ++i) ch[(i+1)*2] = str[i];
        int mid = 1,r = 1;
        for (int i = 1; i < ch.size() - 1; ++i) {
            ans[i] = std::min(ans[mid*2-i],r-i);
            while(ch[i+ans[i]+1]==ch[i-ans[i]-1]) ans[i]++;
            if (i + ans[i] > r){
                mid = i;
                r = i + ans[i];
            }
        }
    }
    std::vector<int> work(Container &str){
        std::vector<int> ans;
        return work(str,ans),ans;
    }
};

2.1.3 Z 函数(exKMP)

C++
struct ZFun{
    std::string raw;
    std::vector<int> Z;
    ZFun(const std::string &S):raw(S),Z(S.size()){
        const int n = S.size();
        for (int i = 1,l = 0,r = 0; i < n; ++i){
            if (i < r){
                if (Z[i-l] < r-i+1) Z[i] = Z[i-l];
                else Z[i] = r-i+1;
            }
            while(i+Z[i] < n && S[i+Z[i]] == S[Z[i]]) Z[i]++;
            if (i + Z[i] - 1 > r) l = i,r = i+Z[i]-1;
        }
        Z[0] = n;
    }
    std::vector<int> operator()(const std::string &S){
        const int n = S.size(),m = raw.size();
        std::vector<int> P(n);
        for (int i = 0,l = 0,r = l;i < n; i++){
            if (i < r){
                if (Z[i-l] < r-i+1) P[i] = Z[i-l];
                else P[i] = r-i+1;
            }
            while(i+P[i] < n && P[i] < m && S[i+P[i]] == raw[P[i]]) P[i]++;
            if (i + P[i] - 1 > r) l = i,r = i+P[i]-1;
        }
        return P;
    }
};

2.1.4 Lyndon 分解

C++
namespace Lyndon{
    std::vector<int> lyndon(const std::string &str){
        std::vector<int> end;
        for (int i = 0,j,k;i < str.size();){
            for(j = i,k = i+1;k < str.size() && str[k] >= str[j];k++)
                if (str[j] == str[k]) j++;
                else j = i;
            while (i <= j) end.push_back(i+k-j),i += k-j;
        }
        return end;
    }
}

2.2 有限自动机(DFA)

2.2.1 AC自动机 (Aho-Corasick)

C++
template <int S = 'a',int E = 'z'>
struct AhoCorasick{
    std::vector<int> answerNodes;
    static constexpr int nxt_size = E-S+1;
    struct Node{
        int fa = 0, fail = 0, in = 0;bool built = 0;
        std::vector<int> next = std::vector<int>(nxt_size,0);
        long long value = 0;
        int& operator[](int index){return this->next[index];}
    };
    inline int ch(int raw){return raw-S;}
    std::vector<Node> nodes = std::vector<Node>(1);
    inline int newNode(int fa = 0){
        int idx = nodes.size();
        nodes.push_back(Node());
        nodes.back().fa = fa;
        return idx;
    }
    AhoCorasick& operator>>(std::string &str){
        int pointer = 0;
        for (int i = 0; i < str.size(); ++i) {
            if (!nodes[pointer][ch(str[i])]) nodes[pointer][ch(str[i])] = newNode(pointer);
            pointer = nodes[pointer][ch(str[i])];
        }
        answerNodes.push_back(pointer);
        return *this;
    }
    void build(){
        if (nodes[0].built) return;
        else nodes[0].built = 1;
        std::queue<int> bfs;
        for (int i = 0; i < nxt_size; ++i) {
            if (nodes[0][i])
                bfs.push(nodes[0][i]),nodes[nodes[0][i]].built=1;
        }
        while(!bfs.empty()){
            int index = bfs.front();bfs.pop();
            for (int i = 0; i < nxt_size; ++i) {
                int chd = nodes[index][i];
                if (chd){
                    if (!nodes[chd].built){
                        nodes[chd].built = 1;
                        bfs.push(chd);
                        nodes[chd].fail = nodes[nodes[index].fail][i];
                        nodes[nodes[chd].fail].in++;
                    }
                } else {
                    nodes[index][i] = nodes[nodes[index].fail][i];
                }
            }
        }
    }
    AhoCorasick& operator<<(std::string &str){
        if (!nodes[0].built) build();
        int pointer=0;
        for (int i = 0; i < str.size(); ++i) {
            pointer = nodes[pointer][ch(str[i])];
            nodes[pointer].value++;
        }
        Topo();
        return *this;
    }

    void Topo(){
        std::queue<int> bfs;
        std::vector<int> pre(nodes.size());
        pre[0] = nodes[0].in;
        for (int i = 1; i < nodes.size(); ++i) {
            pre[i] = nodes[i].in;
            if (!pre[i]) bfs.push(i);
        }
        while(!bfs.empty()){
            int index = bfs.front();bfs.pop();
            if (nodes[index].fail){
                pre[nodes[index].fail]--;
                nodes[nodes[index].fail].value += nodes[index].value;
                if (pre[nodes[index].fail]==0) bfs.push(nodes[index].fail);
            }
        }
    }
    long long getValue(int index){
        return nodes[answerNodes[index]].value;
    }
    Node& operator[](int idx){return nodes[idx];}
};
using ACAM=AhoCorasick<'a','z'>;

2.2.2 广义后缀自动机(GSAM)

C++
/*
 * 注意:SAM 题目往往会伴随着卡常,如果字符集大小不大的情况下,
 * 不要使用 std::unordered_map 或者 std::map,因为它们常数往往较大,时间复杂度上往往要算上4~8倍常数。
 *
 * 一般仅在字符集到达 50 以上在用,即字符集包含大小写字母加数字。
 */
struct SAMInfo{
    int cnt = 0;
    std::vector<int> ch;
    int link = 0,longest = 0;
    int& operator[](int idx){return ch[idx];}
};

// General SuffixAutomaton
template<typename Info,int S,int E>
struct SuffixAutomaton{
    std::vector<Info> nodes;
    int ed = 1;
    constexpr SuffixAutomaton(){
        newNode(); // Void Node
        newNode(); // Empty String Node -> ""
    }
    constexpr int newNode(){
        int idx = nodes.size();
        nodes.push_back(Info());
        nodes.back().ch.resize(E-S+1);
        return idx;
    }
    constexpr void extend(int c){
        if (nodes[ed][c] && nodes[ed].longest +1 == nodes[nodes[ed][c]].longest){
            ed = nodes[ed][c],nodes[ed].cnt ++;
            return;
        }
        int p = newNode(),lst = ed;
        nodes[p].longest = nodes[ed].longest + 1,nodes[p].cnt = 1;
        for (;ed && !nodes[ed][c];ed = nodes[ed].link) nodes[ed][c] = p;
        if (!ed) nodes[p].link = 1;
        else {
            int q = nodes[ed][c];
            if (nodes[q].longest == nodes[ed].longest + 1) nodes[p].link = q; // Legal link
            else {
                int x;
                if (lst == ed) x = p; // Split self
                else x = newNode(),nodes[p].link = x; // New Link
                nodes[x].ch = nodes[q].ch,nodes[x].link = nodes[q].link;
                nodes[x].longest = nodes[ed].longest + 1;
                nodes[q].link = x;
                for (;ed && nodes[ed][c] == q;ed = nodes[ed].link) nodes[ed][c] = x;
            }
        }
        ed = p; // update ed
    }
    constexpr void operator>>(const std::string &str){
        ed = 1;
        for (auto &c : str) extend(c-S);
    }
    constexpr Info& operator[](int idx){return nodes[idx];}
};
using GSAM = SuffixAutomaton<SAMInfo,'a','z'>;

2.2.3 回文树(PAM/Err Tree)

C++
struct PAMNode{
    int fail = 1,len = 0,cnt = 0;
    std::vector<int> ch = std::vector<int>(26);
    int& operator[](int idx){return ch[idx];}
};
struct PalindromicAutomaton{
    using Info = PAMNode;
    std::vector<Info> nodes;
    int lst = 1;
    std::string raw;
    PalindromicAutomaton():nodes(2){
        nodes[0].fail = 1,nodes[1].len = -1;
    }
    int newNode(){
        nodes.push_back(Info());
        return nodes.size()-1;
    }
    int matchFail(int u,int idx){
        while(idx - nodes[u].len - 1 < 0 || raw[idx] != raw[idx-nodes[u].len-1]) u = nodes[u].fail;
        return u;
    }
    // 返回插入该字符后添加的回文子串数量
    int extend(int c){
        raw += c + 'a';
        int p = matchFail(lst,raw.size()-1);
        if (!nodes[p][c]){
            int x = newNode();
            nodes[x].fail = nodes[matchFail(nodes[p].fail,raw.size()-1)][c];
            nodes[p][c] = x;
            nodes[x].len = nodes[p].len + 2;
            nodes[x].cnt = nodes[nodes[x].fail].cnt + 1;
        }
        lst = nodes[p][c];
        return nodes[lst].cnt;
    }
};
using PAM = PalindromicAutomaton;

2.3 字符串哈希 Hacks

2.3.1 Thue Morse 序列

用于 hack 自然溢出模数。(无视基数)

C++
// 用于 hack 自然溢出或者 2^x 作为模数
std::string ThueMorse(unsigned long long MOD = 0){
    assert(__builtin_popcountll(MOD) == 1 || MOD == 0);
    int p = 12;
    int len = 1 << p;// 冲突长度为 (2^(p-1))
    std::string str;
    for (int i = 0;i < len;i ++) str += 'a'+(__builtin_popcount(i)&1);
    return str;
}

3.数据结构

3.1 简单数据结构

3.1.1 并查集及可撤销并查集

C++
// 路径压缩版本
struct Disjoint{
    std::vector<int> fa,siz;
    int cnt=0;
    Disjoint(int n = 0){
        init(n);
    }
    void init(int n = 0){
        fa = std::vector<int>(n+1);
        siz = std::vector<int>(n+1,1);
        std::iota(fa.begin(),fa.end(),0);
        cnt = n;
    }
    void operator()(int head,int ele){ // merge
        if (root(head)==root(ele)) return;
        siz[root(head)]+=siz[root(ele)];
        fa[root(ele)]=root(head);
    }
    int operator[](int index){return root(index);}
    int size(int x){return siz[root(x)];}
private:
    int root(int x){
        return fa[x] = fa[x] == x ? x : root(fa[x]);
    }
};
// 启发式合并+可撤销
struct DisjointWithUndo{
    std::vector<int> siz,fa;
    std::vector<std::array<int,2>> tm;// fa,son
    DisjointWithUndo(int n = 0){init(n);}
    void init(int n){
        siz = std::vector<int>(n+1,1),fa = std::vector<int>(n+1),tm.clear();
        std::iota(fa.begin(),fa.end(),0);
    }
    bool operator()(int x,int y){ // 合并
        x = root(x),y = root(y);
        if (x == y) return false;
        if (siz[x] < siz[y]) std::swap(x,y);
        tm.push_back({x,y});
        siz[x] += siz[y],fa[y] = x;
        return true;
    }
    int operator[](int index){return root(index);}
    void undo(int cnt){ // 撤销
        while(cnt--){
            if (tm.empty()) break;
            auto [x,y] = tm.back();
            tm.pop_back();
            siz[x] -= siz[y];
            fa[y] = y;
        }
    }
private:
    int root(int x){
        while(x!=fa[x]) x=fa[x];
        return x;
    }
};
using DSU=Disjoint;

3.1.2 树状数组

C++
template<typename T>
struct Fenwick{
    std::vector<T> value;
    int size = 0;
    Fenwick(int n = 0):size(n+1){
        value.assign(size,T(0));
    }
    void add(int i,T x){
        for (;i < size;i += i&(-i)) value[i] += x;
    }
    void remove(int i,T x){
        for (;i < size;i += i&(-i)) value[i] -= x;
    }
    T presum(int i) const {
        T ans = 0;
        for (;i;i -= i & (-i)) ans += value[i];
        return ans;
    }
    T operator[](const int i) const {
        return presum(i);
    }
};

3.2 高级数据结构

3.2.1 线段树

C++
// 开点线段树(内存更少)
template <typename Info>
struct DynamicMemorySegmentTree{
    std::vector<int> lson,rson;
    std::vector<Info> info;
    int size = 0,root = 0;
    DynamicMemorySegmentTree(int n = 1){
        init(n);
    }
    void init(int n){
        size = n,lson = std::vector<int>(1),rson = std::vector<int>(1);
        info = std::vector<Info>(1);
        root = 0;
    }
    int newNode(int l,int r){
        int idx = info.size();
        info.push_back(Info()),lson.push_back(0),rson.push_back(0);
        info[idx].reload(l,r);
        return idx;
    }
    template<typename T>
    int modify(int option,T val,int rl,int rr,int idx,int l,int r){
        if (!idx) idx = newNode(l,r);
        if (rl == l && rr == r){
            info[idx](option,val);
            return idx;
        }
        int mid = (l+r)>>1;
        if (!lson[idx]) lson[idx] = newNode(l,mid);
        if (!rson[idx]) rson[idx] = newNode(mid+1,r);
        info[idx].lazy(info[lson[idx]],info[rson[idx]]);
        if (rl <= mid) lson[idx]=modify(option,val,rl,std::min(rr,mid),lson[idx],l,mid);
        if (rr > mid) rson[idx]=modify(option,val,std::max(rl,mid+1),rr,rson[idx],mid+1,r);
        info[idx] = info[lson[idx]] + info[rson[idx]];
        info[idx].reload(l,r);
        return idx;
    }
    Info query(int rl,int rr,int idx,int l,int r){
        if (!idx) return info[0];
        if (rl == l && rr == r){
            return info[idx];
        }
        int mid = (l+r)>>1;
        if (!lson[idx]) lson[idx] = newNode(l,mid);
        if (!rson[idx]) rson[idx] = newNode(mid+1,r);
        info[idx].lazy(info[lson[idx]],info[rson[idx]]);
        Info ans;
        if (rl <= mid) ans = query(rl,std::min(rr,mid),lson[idx],l,mid);
        if (rr > mid) ans = ans + query(std::max(rl,mid+1),rr,rson[idx],mid+1,r);
        ans.reload(rl,rr);
        return ans;
    }
    Info operator()(int l,int r){
        return query(l,r,root,1,size);
    }
    template<typename T>
    void operate(int option,T val,int l,int r){
        root = modify(option,val,l,r,root,1,size);
    }
};
// 静态线段树(常数更低)
template<typename Info>
struct StaticMemorySegmentTree{
#define ls(x) (x<<1)
#define rs(x) (x<<1|1)
    std::vector<Info> info;
    int size = 0;
    StaticMemorySegmentTree(int n = 0){
        init(n);
    }
    void init(int n){
        info = std::vector<Info>((n<<2)+5);
        size = n;
        if (n == 0) return;
        initInfo(std::vector<Info>(n+1));
    }
    void initInfo(std::vector<Info> val){
        val.reserve(size+1);
        initInfo(1,1,size,val);
    }
    void initInfo(int idx,int l,int r,std::vector<Info> &val){
        if (l == r){
            info[idx] = val[l];
            info[idx].reload(l,r);
            return;
        }
        int mid = (l+r)>>1;
        initInfo(ls(idx),l,mid,val);
        initInfo(rs(idx),mid+1,r,val);
        info[idx] = info[ls(idx)]+info[rs(idx)];
        info[idx].reload(l,r);
    }
    Info operator()(int l,int r){
        return query(l,r,1,1,size);
    }
    Info query(int rl,int rr,int idx,int l,int r){
        if (rl==l&&rr==r){
            return info[idx];
        }
        info[idx].lazy(info[ls(idx)],info[rs(idx)]);
        int mid = (l+r)>>1;
        Info ans;
        if (rl <= mid) ans = query(rl,std::min(mid,rr),ls(idx),l,mid);
        if (rr > mid) ans = ans+query(std::max(mid+1,rl),rr,rs(idx),mid+1,r);
        return ans;
    }
    template<typename T>
    void modify(int option,T val,int rl,int rr,int idx,int l,int r){
        if (rl==l&&rr==r){
            info[idx](option,val);
            return;
        }
        info[idx].lazy(info[ls(idx)],info[rs(idx)]);
        int mid = (l+r)>>1;
        if (rl <= mid) modify(option,val,rl,std::min(mid,rr),ls(idx),l,mid);
        if (rr > mid) modify(option,val,std::max(mid+1,rl),rr,rs(idx),mid+1,r);
        info[idx] = info[ls(idx)]+info[rs(idx)];
        info[idx].reload(l,r);
    }
    template<typename T>
    void operate(int option,T val,int l,int r){
        modify(option,val,l,r,1,1,size);
    }
#undef ls
#undef rs
};

// 需要修改 Info 结构和 Tag 结构
struct SegmentTreeInfo{
    // info
    int size = 0,L=0,R=0; // onCreate

    struct Tag{
        void operator()(SegmentTreeInfo &l,SegmentTreeInfo &r){ // pull down

        }
    } lazy;

    SegmentTreeInfo operator+(SegmentTreeInfo r){ // merge
        SegmentTreeInfo ans,l=*this;// ans = l + r

        return ans;
    }

    // modify: option + value
    template<typename T>
    void operator()(int op,T val){
    }

    // reload size,不要改
    void reload(int l=0,int r=0){
        L = l,R = r,size = R-L+1;
    }
};
using Segment = DynamicMemorySegmentTree<SegmentTreeInfo>;

3.2.2 主席树(可持久化线段树)

C++
struct SegmentTreeInfo{
    int size = 0,L=0,R=0; // onCreate

    struct Tag{
        void operator()(SegmentTreeInfo &l,SegmentTreeInfo &r){ // push tag

        }
    } lazy;

    SegmentTreeInfo operator+(SegmentTreeInfo r){ // merge
        SegmentTreeInfo ans,l=*this;// ans = l + r

        return ans;
    }

    // modify: option + value
    template<typename T>
    void operator()(int op,T val){
    }

    // reload size
    void reload(int l=0,int r=0){
        L = l,R = r,size = R-L+1;
    }
};
template<typename Info>
struct PersistentSegmentTree{
    std::vector<int> lson,rson;
    std::vector<Info> info;
    std::vector<int> ver;
    int size = 1;
    PersistentSegmentTree(const int n = 1){
        init(n);
    }
    void init(const int n){
        lson = std::vector<int>(1),rson = std::vector<int>(1);
        info = std::vector<Info>(1);
        size = n;
    }
    int copyNode(const int pre){
        int index = info.size();
        info.push_back(info[pre]);
        lson.push_back(lson[pre]),rson.push_back(rson[pre]);
        return index;
    }
    int push_down(const int pre){
        int idx = copyNode(pre);
        lson[idx] = copyNode(lson[idx]),rson[idx] = copyNode(rson[idx]);
        info[idx].lazy(info[lson[idx]],info[rson[idx]]);
        return idx;
    }
    template<typename T>
    int modify(const int option,const T val,const int rl,const int rr,const int pre,const int l,const int r){
        int idx = copyNode(pre);
        if (rl == l && rr == r){
            info[idx](option,val);
            return idx;
        }
        idx = push_down(idx);
        int mid = (l+r)>>1;
        if (rl <= mid) lson[idx] = modify(option,val,rl,std::min(mid,rr),lson[idx],l,mid);
        if (rr > mid) rson[idx] = modify(option,val,std::max(rl,mid+1),rr,rson[idx],mid+1,r);
        info[idx] = info[lson[idx]] + info[rson[idx]];
        info[idx].reload(l,r);
        return idx;
    }
    Info query(const int rl,const int rr,int idx,const int l,const int r){
        if (rl == l && rr == r){
            return info[idx];
        }
        idx = push_down(idx);
        Info ans;
        int mid = (l+r)>>1;
        if (rl <= mid) ans = query(rl,std::min(rr,mid),lson[idx],l,mid);
        if (rr > mid) ans = ans + query(std::max(rl,mid+1),rr,rson[idx],mid+1,r);
        return ans;
    }
    Info operator()(int l,int r,int v){
        return query(l,r,ver[v],1,size);
    }
    // replace 为是否替换原版本,而不创建新版本
    template<typename T>
    void operate(int option,T val,int l,int r,int v,bool replace = false){
        int idx = v;
        if (!replace) idx = ver.size(),ver.push_back(ver[v]);
        ver[idx] = modify(option,val,l,r,ver[v],1,size);
    }
};
using Segment = PersistentSegmentTree<SegmentTreeInfo>;

3.2.3 左偏树(可并堆)

C++
namespace LeftistTree{
    constexpr int maxn = 3e5+7;
    struct Node {
        int l = 0, r = 0, val = -1, dist = -1, id = 0;
        bool del = 0;
    } nodes[maxn];
    // ----并查集----
    int fa[maxn];
    inline int rt(int x) { return fa[x] = fa[x] == x ? x : rt(fa[x]); }
    // -------------

    int mergeHeap(int x, int y) {
        if (!x || !y) return x | y;
        if (nodes[x].val > nodes[y].val || (nodes[x].val == nodes[y].val && nodes[x].id > nodes[y].id)) std::swap(x, y);
        nodes[x].r = mergeHeap(nodes[x].r, y);
        nodes[x].dist = nodes[nodes[x].r].dist + 1;
        if (nodes[nodes[x].l].dist < nodes[nodes[x].r].dist) std::swap(nodes[x].l, nodes[x].r);
        return x;
    }

    int query(int x) {
        if (nodes[x].del) return -1;
        x = rt(x);
        int ans = nodes[x].val;
        nodes[x].del = 1;
        fa[nodes[x].l] = fa[nodes[x].r] = fa[x] = mergeHeap(nodes[x].l, nodes[x].r);
        nodes[x].l = nodes[x].r = 0;
        return ans;
    }

    inline void merge(int x, int y) { // 合并两个堆
        if (nodes[x].del || nodes[y].del) return;
        x = rt(x),y = rt(y);
        if (x == y) return;
        fa[x] = fa[y] = mergeHeap(x,y);
    }
}

3.3 平衡树

3.3.1 笛卡尔树

C++
struct Cartesian{
    template<typename T,typename CMP = std::less<T>>
    static std::vector<std::pair<int,int>> build(std::vector<T>& arr,int s = 0,int empty = -1,CMP compare = CMP()){
        std::vector<int> stk;
        std::vector<std::pair<int,int>> bst(arr.size(),{empty,empty});
        for (int i = s;i < arr.size();i ++){
            while(stk.size() && compare(arr[stk.back()],arr[i])){
                bst[i].first = stk.back();
                stk.pop_back();
            }
            if (stk.size()) bst[stk.back()].second = i;
            stk.push_back(i);
        }
        return bst;
    }
};

3.3.2 FHQ Treap(无旋 Treap)

C++
struct Info{
    long long value = 0;
    bool operator<=(long long val){ // splitValue CMP
        return value <= val;
    }
    void operator=(long long val){ // splitValue CMP
        value = val;
    }
};
// 需要修改Node结构
struct FHQ_Treap{
    std::mt19937 rnd = std::mt19937(448268);
#define ls(x) lson[x]
#define rs(x) rson[x]
    struct Node{
        int size = 0,key = 0;
        Info info;
        bool operator<=(long long val){ // splitValue CMP
            return info <= val;
        }
        long long operator=(long long val){
            info = val;
            return val;
        }
    };
    std::vector<int> lson = {0},rson = {0};
    std::vector<Node> nodes = {Node()};
    std::stack<int> rem;
    int root = 0;
    int newNode(int value=0){
        int idx;
        if (rem.size()) {
            idx = rem.top(),rem.pop();
            if (ls(idx)) rem.push(ls(idx)),ls(idx) = 0;
            if (rs(idx)) rem.push(rs(idx)),rs(idx) = 0;
            nodes[idx] = Node();
        }
        else {
            idx = nodes.size();
            lson.push_back(0),rson.push_back(0),nodes.push_back(Node());
        }
        nodes[idx] = value;
        nodes[idx].size = 1;
        nodes[idx].key = rnd();
        return idx;
    }
    void push_down(int idx){}
    void update(int idx){
        nodes[idx].size = nodes[ls(idx)].size + nodes[rs(idx)].size + 1;
    }
    void splitSize(int now,int size,int &x,int &y){
        if (!now) x=y=0;
        else {
            push_down(now);
            if (nodes[ls(now)].size + 1 <= size){
                x=now;
                splitSize(rs(now),size-nodes[ls(now)].size-1,rs(x),y);
            } else {
                y=now;
                splitSize(ls(now),size,x,ls(y));
            }
            update(now);
        }
    }
    void splitValue(int now,long long value,int &x,int &y){
        if (!now) x=y=0;
        else {
            push_down(now);
            if (nodes[now] <= value){
                x=now;
                splitValue(rs(now),value,rs(x),y);
            } else {
                y=now;
                splitValue(ls(now),value,x,ls(y));
            }
            update(now);
        }
    }
    int merge(int a,int b){
        if (!a||!b)return a|b;
        push_down(a), push_down(b);
        if (nodes[a].key<nodes[b].key){
            rs(a) = merge(rs(a),b);
            update(a);
            return a;
        } else {
            ls(b) = merge(a,ls(b));
            update(b);
            return b;
        }
    }
    void insertByPos(int pos,int val){
        int x,y;
        splitSize(root,pos-1,x,y);
        root = merge(merge(x, newNode(val)),y);
    }
    void deleteByPos(int pos){
        int x,y,z;
        splitSize(root,pos-1,x,y);
        splitSize(y,1,y,z);
        rem.push(y);
        root = merge(x,z);
    }
    Node& operator[](int index){
        if (index > nodes[root].size) return this->operator[](nodes[root].size);
        int x,y,z;
        splitSize(root,index-1,x,y);
        splitSize(y,1,y,z);
        Node &ans = nodes[y];
        root = merge(merge(x,y),z);
        return ans;
    }
#undef ls
#undef rs
};

4.图论

4.1 树

4.1.1 常用树上问题(树链剖分)

C++
namespace Graph{
    struct Edge{
        int to = 0,w = 1;
    };
    struct Info{ // 仅举例
        int dist = 0,w = 1; // 距离,点权
        int dia,mx1,mx2; // 直径(以点权为例)
        void operator()(Info last,Edge e){ // 下传信息
            dist = last.dist + e.w; // 根->点的边权和
            dia = 1,mx1 = mx2 = 0;
        }
        void operator<<(std::pair<Info,Edge> info){ // 上传信息
            auto &[v,e] = info;
            std::vector<int> temp = {mx1,mx2,v.mx1+w,mx2+w};
            std::sort(temp.begin(), temp.end());
            mx1 = temp[0],mx2 = temp[1];
            dia = std::max({dia,mx1+mx2+w,v.dia});
        }
    };
    struct Tree{
        std::vector<int> fa,sz,top,hvy,dfn,dep;
        std::vector<Info> info;
        std::vector<std::vector<Edge>> adj;
        int siz = 0,tt = 0;
        bool built = 0;
        Tree(int n = 1){ init(n);}
        void init(int n){
            siz = n,tt = 0,built = 0;
            std::vector<std::vector<int>*> vtr = {&fa,&sz,&top,&hvy,&dfn,&dep};
            for (auto v:vtr) v->resize(n+2);
            info.assign(n+2,Info());
            adj.assign(n+2,{});
        }
        void operator()(int u,Edge e){
            adj[u].push_back(e);
        }
        void build(int root = 1){
            assert(!built);
            built = 1;
            dep[root] = 0;
            dfs1(root,root);
            dfs2(root,root);
        }
        void dfs1(int u,int rt){
            sz[u] = 1;
            int mx = 0;
            for (auto e:adj[u]){
                int v = e.to,w = e.w;
                if (v == rt) continue;
                fa[v] = u,dep[v] = dep[u] + 1;
                info[v](info[u],e);
                dfs1(v,u);
                sz[u] += sz[v];
                if (sz[v] > mx) mx = sz[v],hvy[u] = v;
                std::pair<Info,Edge> up = {info[v],e};
                info[u] << up;
            }
        }
        void dfs2(int u,int tp){
            dfn[u] = ++tt,top[u] = tp;
            if (hvy[u]) dfs2(hvy[u],tp);
            for(auto &e:adj[u]){
                int v = e.to;
                if (v == fa[u] || v == hvy[u]) continue;
                dfs2(v,v);
            }
        }
        int lca(int a,int b){
            while (top[a] != top[b]){
                if (dep[top[a]] < dep[top[b]]) std::swap(a,b);
                a = fa[top[a]];
            }
            if (dep[a] < dep[b]) std::swap(a,b);
            return b;
        }
        int dist(int a,int b){
            return info[a].dist + info[b].dist - info[lca(a,b)].dist*2;
        }
        bool contain(int u,int v) { // 子树 u 是否包含v
            return dfn[u] <= dfn[v] && dfn[v] < dfn[u] + sz[u];
        }
    };
}
using Graph::Tree;

4.1.2 树链剖分(含子树和路径操作)

C++
// 需要修改 Info 结构和 Tag 结构
struct HPDInfo{
    // info
    int size = 0,L=0,R=0; // onCreate

    struct Tag{
        void operator()(HPDInfo &l,HPDInfo &r){ // pull down

        }
    } lazy;

    HPDInfo operator+(HPDInfo r){ // merge
        HPDInfo ans,l=*this;// ans = l + r

        return ans;
    }

    // modify: option + value
    template<typename T>
    void operator()(int op,T val){
    }

    // reload size,不要改
    void reload(int l=0,int r=0){
        L = l,R = r,size = R-L+1;
    }
};
// 线段树
template<typename Info>
struct SegmentTree{
#define ls(x) (x<<1)
#define rs(x) (x<<1|1)
    std::vector<Info> info;
    int size = 0;
    SegmentTree(int n = 0){
        init(n);
    }
    void init(int n){
        info = std::vector<Info>((n<<2)+5);
        size = n;
        if (n == 0) return;
        initInfo(std::vector<Info>(n+1));
    }
    void initInfo(std::vector<Info> val){
        val.resize(size+1);
        initInfo(1,1,size,val);
    }
    void initInfo(int idx,int l,int r,std::vector<Info> &val){
        if (l == r){
            info[idx] = val[l];
            info[idx].reload(l,r);
            return;
        }
        int mid = (l+r)>>1;
        initInfo(ls(idx),l,mid,val);
        initInfo(rs(idx),mid+1,r,val);
        info[idx] = info[ls(idx)]+info[rs(idx)];
        info[idx].reload(l,r);
    }
    Info operator()(int l,int r){
        return query(l,r,1,1,size);
    }
    Info query(int rl,int rr,int idx,int l,int r){
        if (rl==l&&rr==r){
            return info[idx];
        }
        info[idx].lazy(info[ls(idx)],info[rs(idx)]);
        int mid = (l+r)>>1;
        Info ans;
        if (rl <= mid) ans = query(rl,std::min(mid,rr),ls(idx),l,mid);
        if (rr > mid) ans = ans+query(std::max(mid+1,rl),rr,rs(idx),mid+1,r);
        return ans;
    }
    template<typename T>
    void modify(int option,T val,int rl,int rr,int idx,int l,int r){
        if (rl==l&&rr==r){
            info[idx](option,val);
            return;
        }
        info[idx].lazy(info[ls(idx)],info[rs(idx)]);
        int mid = (l+r)>>1;
        if (rl <= mid) modify(option,val,rl,std::min(mid,rr),ls(idx),l,mid);
        if (rr > mid) modify(option,val,std::max(mid+1,rl),rr,rs(idx),mid+1,r);
        info[idx] = info[ls(idx)]+info[rs(idx)];
        info[idx].reload(l,r);
    }
    template<typename T>
    void operate(int option,T val,int l,int r){
        modify(option,val,l,r,1,1,size);
    }
#undef ls
#undef rs
};
// 树链剖分+树上操作
template<typename Info>
struct HeavyPathDecomposition{
    int size = 0,tt=0;
    bool built = 0;
    SegmentTree<Info> sgt;
    struct Node{
        Info info;
        std::vector<int> adj;
        void operator += (int id){
            this->adj.push_back(id);
        }
        int& operator[](int id){
            return this->adj[id];
        }
        int fa=0,dep=0,size=0,top=0,hvy=0,dfn=0;
    };
    std::vector<Node> nodes;
    std::vector<Info> init_info;
    HeavyPathDecomposition(int size=0){
        init(size);
    }
    void init(int n){
        size = n;
        nodes = std::vector<Node>(n+3);
        sgt.init(n+1);
    }
    void setInfo(int index,Info info){
        nodes[index].info = info;
    }
    HeavyPathDecomposition& connect(int x,int y){
        assert(!built),nodes[x]+=y,nodes[y]+=x;
        return *this;
    }
    HeavyPathDecomposition& operator()(int x,int y){
        return connect(x,y);
    }
    void dfs1(int index,int fa){
        nodes[index].fa = fa,nodes[index].dep = nodes[fa].dep+1,nodes[index].size = 1;
        int maxSize =0;
        for(auto &v:nodes[index].adj){
            if (v == fa) continue;
            dfs1(v,index);
            if (maxSize < nodes[v].size){
                nodes[index].hvy = v;
                maxSize = nodes[v].size;
            }
            nodes[index].size += nodes[v].size;
        }
    }
    void dfs2(int index,int top){
        nodes[index].top = top,nodes[index].dfn = ++tt;
        init_info[tt] = nodes[index].info;
        if (nodes[index].hvy) dfs2(nodes[index].hvy,top);
        for (auto &v:nodes[index].adj){
            if (v == nodes[index].hvy || v == nodes[index].fa) continue;
            dfs2(v,v);
        }
    }
    void build(int root = 1){
        built = 1;
        init_info.resize(size+1);
        dfs1(root,root);
        dfs2(root,root);
        sgt.initInfo(init_info);
    }
    int lca(int x,int y){
        if (!built) build();
        while(nodes[x].top != nodes[y].top){
            if (nodes[nodes[x].top].dep < nodes[nodes[y].top].dep) std::swap(x,y);
            x = nodes[nodes[x].top].fa;
        }
        if (nodes[x].dep > nodes[y].dep) std::swap(x,y);
        return x;
    }
    template<typename T>
    void modifyPath(int x,int y,int op,T val){
        if (!built) build();
        while(nodes[x].top != nodes[y].top){
            if (nodes[nodes[x].top].dep < nodes[nodes[y].top].dep) std::swap(x,y);
            sgt.operate(op,val,nodes[nodes[x].top].dfn,nodes[x].dfn);
            x = nodes[nodes[x].top].fa;
        }
        if (nodes[x].dep > nodes[y].dep) std::swap(x,y);
        sgt.operate(op,val,nodes[x].dfn,nodes[y].dfn);
    }
    Info queryPath(int x,int y){
        if (!built) build();
        Info rst;
        while(nodes[x].top != nodes[y].top){
            if (nodes[nodes[x].top].dep < nodes[nodes[y].top].dep) std::swap(x,y);
            rst = rst + sgt(nodes[nodes[x].top].dfn,nodes[x].dfn);
            x = nodes[nodes[x].top].fa;
        }
        if (nodes[x].dep > nodes[y].dep) std::swap(x,y);
        rst = rst + sgt(nodes[x].dfn,nodes[y].dfn);
        return rst;
    }
    template<typename T>
    void modifySubtree(int x,int op,T val){
        if (!built) build();
        sgt.operate(op,val,nodes[x].dfn,nodes[x].dfn+nodes[x].size-1);
    }
    Info querySubtree(int x){
        if (!built) build();
        return sgt(nodes[x].dfn,nodes[x].dfn+nodes[x].size-1);
    }
};
using HPD = HeavyPathDecomposition<HPDInfo>;

4.2 有环图

4.2.1 强联通分量与缩点(SCC)

带点权合并版本。

C++
struct SCC{
    int size = 0,t = 0;
    std::vector<std::vector<int>> G1,G2;
    std::vector<int> low,dfn,W,stk,scc,W2;
    std::vector<bool> instack;
    SCC(int siz){
        size = siz+1;
        const std::vector<std::vector<int>*> tmp = {&low,&dfn,&W,&scc};
        G1.resize(size),instack.resize(size);
        G2.resize(1),W2.resize(1);
        for (const auto &ptr : tmp) ptr->resize(size);
    }
    void connect(int u,int v){
        G1[u].push_back(v);
    }
    std::vector<int>& operator[](int i){return G2[i];}
    void tarjan(int u){
        low[u] = dfn[u] = ++t;
        instack[u] = 1,stk.push_back(u);
        for (int v : G1[u]){
            if (!dfn[v]) {
                tarjan(v);
                low[u] = std::min(low[u],low[v]);
            } else if (instack[v]) {
                low[u] = std::min(low[u],dfn[v]);
            }
        }
        if (low[u] == dfn[u]) {
            int p = -1;
            G2.push_back({});
            W2.push_back(0);
            do {
                p = stk.back();
                stk.pop_back();
                scc[p] = G2.size()-1;
                W2[scc[p]] += W[p];
                instack[p] = 0;
            } while (p != u);
        }
    }
    void work(){
        G2.assign(1,{});
        for (int i = 1;i < size;i ++)
            if (!dfn[i]) tarjan(i);
        for (int i = 1;i < size;i ++){
            int u = scc[i];
            for (int v : G1[i]){
                if (u == scc[v]) continue;
                G2[u].push_back(scc[v]);
            }
        }
        for (int i = 1;i < G2.size();i ++){
            sort(G2[i].begin(),G2[i].end());
            G2[i].erase(unique(G2[i].begin(),G2[i].end()),G2[i].end());
        }
        size = G2.size();
    }
};

4.2.2 边双联通分量(e-DCC)

C++
struct EDCC{
    int size = 0,t = 0,eid = 0;
    std::vector<std::vector<std::pair<int,int>>> G1;// E:to,id
    std::vector<std::vector<int>> G2;
    std::vector<int> low,dfn,stk,edcc;
    EDCC(int siz){
        size = siz + 1;
        std::vector<std::vector<int>*> ptr = {&low,&dfn,&edcc};
        for (auto &v : ptr) v->assign(size,0);
        G1.assign(size,{});
        G2.assign(1,{});
    }
    void connect(int u,int v){
        eid++;
        G1[u].push_back({v,eid});
        G1[v].push_back({u,eid});
    }
    auto& operator[](int i){return G2[i];}
    void tarjan(int u,int e){
        low[u] = dfn[u] = ++t;
        stk.push_back(u);
        for (const auto &[v,id] : G1[u]){
            if (id == e) continue;
            if (!dfn[v]) {
                tarjan(v,id);
                low[u] = std::min(low[u],low[v]);
            } else low[u] = std::min(low[u],dfn[v]);
        }
        if (low[u] == dfn[u]){
            int p = -1;
            G2.push_back({});
            do {
                p = stk.back();
                stk.pop_back();
                edcc[p] = G2.size() - 1;
            } while(p != u);
        }
    }
    void work(){
        for (int u = 1;u < size;u ++)
            if (!dfn[u]) tarjan(u,-1);
        for (int i = 1;i < size;i ++){
            int u = edcc[i];
            for (auto [v,id] : G1[i]){
                if (edcc[v] == u) continue;
                G2[u].push_back(edcc[v]);
                G2[edcc[v]].push_back(u);
            }
        }
        size = G2.size();
        for (int u = 1;u < size;u ++){
            sort(G2[u].begin(),G2[u].end());
            G2[u].erase(unique(G2[u].begin(),G2[u].end()),G2[u].end());
        }
    }
};

4.2.3 Kruskal 重构树

C++
using namespace std;
// Warning! 该内容未模板化。
struct Edge{
    int a,b,w=0;
};
struct KruskalReconstructionTree{
    vector<Edge> edges;
    vector<int> fa;
    int root(int x){
        return fa[x] = fa[x]==x?x:root(fa[x]);
    }
    void merge(int x,int y){
        if (root(x)==root(y)) return;
        fa[root(y)] = root(x);
    }
    struct Node{
        int fa=0,top=0,hvy=0,sz=0,dep=0,w=0;
        int flag = 0;
        vector<int> adj;
    };
    vector<Node> nodes;
    int color = 0;
    void dfs1(int u,int rt){
        nodes[u].sz = 1,nodes[u].fa = rt,nodes[u].dep = nodes[rt].dep+1;
        int mxSize = 0;
        for (auto v:nodes[u].adj){ // 树建得没问题的话,这里是不需要判断父节点的
            dfs1(v,u);
            nodes[u].sz += nodes[v].sz;
            if (mxSize < nodes[v].sz){
                nodes[u].hvy = v;
                mxSize = nodes[v].sz;
            }
        }
        nodes[u].flag = color;
    }
    void dfs2(int u,int top){
        nodes[u].top = top;
        if (nodes[u].hvy) dfs2(nodes[u].hvy,top);
        for (auto v:nodes[u].adj){
            if (v == nodes[u].hvy) continue;
            dfs2(v,v);
        }
    }
    int lca(int a,int b){
        if (nodes[a].flag != nodes[b].flag) return -1;
        while (nodes[a].top != nodes[b].top){
            if (nodes[nodes[a].top].dep < nodes[nodes[b].top].dep) swap(a,b);
            a = nodes[nodes[a].top].fa;
        }
        if (nodes[a].dep < nodes[b].dep) swap(a,b);
        return b;
    }
    void buildRoot(int idx){
        ++color;
        dfs1(idx,idx);
        dfs2(idx,idx);
    }
    void build(){
        sort(edges.begin(),edges.end(),[](Edge a,Edge b)->bool{
            return a.w < b.w;
        });
        for (auto [a,b,w]:edges){
            if (root(a) == root(b)) continue;
            a = root(a),b = root(b);
            int u = nodes.size();
            nodes.push_back(Node());
            merge(u,a),merge(u,b);
            nodes[u].w = w;
            nodes[u].adj.push_back(a),nodes[u].adj.push_back(b);
        }
        for (int i = 1; i < nodes.size(); ++i) {
            if (nodes[i].flag) continue;
            int rt = root(i);
            buildRoot(rt);
        }
    }
};

5.计算几何

5.1 计算几何基础

5.1.1 点与向量(二维)

C++
namespace GeometryBase{
    template<typename T = double>
    struct Point{
        T x,y;
        Point(T X = 0,T Y = 0):x(X),y(Y){}
        constexpr auto operator<=>(const Point& b) const {
            if (x == b.x) return y <=> b.y;
            return x <=> b.x;
        }
        constexpr bool operator==(const Point& b) const = default;
        constexpr Point& operator+=(const Point b){
            x += b.x,y += b.y;
            return *this;
        }
        constexpr Point& operator-=(const Point b){
            x -= b.x,y -= b.y;
            return *this;
        }
        constexpr Point& operator*=(const T lambda){
            x *= lambda,y *= lambda;
            return *this;
        }
        constexpr Point& operator/=(const T lambda){
            x /= lambda,y /= lambda;
            return *this;
        }
        constexpr Point operator-(){
            return Point(-x,-y);
        }
        friend Point operator+(const Point a,const Point b){
            return Point(a.x + b.x,a.y + b.y);
        }
        friend Point operator-(const Point a,const Point b){
            return Point(a.x - b.x,a.y - b.y);
        }
        friend Point operator*(const Point a,const T lambda){
            return Point(a.x * lambda,a.y * lambda);
        }
        friend Point operator*(const T lambda,const Point a){
            return a *= lambda;
        }
        friend Point operator/(const Point a,const T lambda){
            assert(lambda != 0);
            return Point(a.x / lambda,a.y / lambda);
        }
        // Vector Operations
        static T dot(const Point a,const Point b){
            return a.x * b.x + a.y * b.y;
        }
        static T cross(const Point a,const Point b){
            return a.x * b.y - a.y * b.x;
        }
        constexpr double length(){ // Euclidean norm
            return std::sqrt(dot(*this,*this));
        }
        // STL
        friend std::istream& operator>>(std::istream& is,Point &p){
            return is >> p.x >> p.y;
        }
        friend std::ostream& operator<<(std::ostream& os,const Point &p){
            return os << p.x << ' ' << p.y;
        }
    };
}
using P = GeometryBase::Point<double>;

5.1.2 线

尚未完善

C++
namespace GeometryBase{
    template<typename T>
    struct Line{
        Point<T> x,y;
        constexpr Line(Point<T> X = Point<T>(),Point<T> Y = Point<T>()):x(X),y(Y){}
        constexpr double length(){
            return (x-y).length();
        }
        constexpr static Line toVector(const Line& l){
            return Line(l.x - l.x,l.y - l.x);
        }
    };
}
using LN = GeometryBase::Line<double>;

5.1.3 三角函数与极角

C++
namespace Trigonometric{ // 三角函数
    using LD = long double;
    const LD PI = std::acos(-1.0);
    LD toRadian(LD angle){ // 角度制转弧度制
        return PI*angle/180;
    }
    LD Polar(LD x,LD y){ // 坐标转极角(弧度制),值域[0,2PI)
        assert(x || y);// 坐标原点不存在极角
        if (x == 0) return (y > 0 ? 0.5 : 1.5) * PI;
        if (y == 0) return (x > 0 ? 0.0 : 1.0) * PI;
        LD ATAN = std::atan(y/x);
        if (ATAN < 0) ATAN += PI;
        return (y > 0 ? 0 : PI) + ATAN;
    }
    LD getAngle(LD rad1,LD rad2){ // x1->x2 求逆时针夹角弧度
        return rad2 - rad1 + (rad1 > rad2 ? 2*PI : 0);
    }
    LD arcLength(LD radius,LD angle = 2*PI){ // 求指定角度(弧度制)和半径的弧长
        return angle*radius;
    }
    LD sectorArea(LD radius,LD angle = 2*PI){ // 扇形面积(弧度制)
        return arcLength(radius,angle)*radius/2;
    }
}
using namespace Trigonometric;

5.2 二维计算几何

5.2.1 二维凸包

需要使用 Point。

C++
struct Andrew{
    static auto hull(std::vector<P> points,int s = 0){
        const int n = points.size() - 1;
        std::vector<P> hi,lo;
        sort(points.begin() + s,points.end());
        for (int i = s;i <= n;i ++){
            P p = points[i];
            while (hi.size() > 1 && P::cross(hi.back() - hi[hi.size() - 2],p - hi.back()) >= 0){
                hi.pop_back();
            }
            if (hi.size() && hi.back().x == p.x){
                hi.pop_back();
            }
            hi.push_back(p);
            while (lo.size() > 1 && P::cross(lo.back() - lo[lo.size() - 2],p - lo.back()) <= 0){
                lo.pop_back();
            }
            if (!lo.size() || lo.back().x < p.x) lo.push_back(p);
        }
        return std::make_pair(hi,lo);// high hull and low hull
    }
};

6.杂项

6.1 STL 拓展

6.1.1 int128

C++
#include <bits/stdc++.h>
using i128 = __int128;
namespace std {
    string to_string(i128 x) {
        string s;bool sign = x < 0;
        if (sign) x = -x;
        while (x) s += x % 10 + '0', x /= 10;
        if (sign) s += "-";
        reverse(s.begin(), s.end());
        return s;
    }
    i128 stoi128(const string &str){
        i128 x = 0;bool sign = 0;
        for(int i(0);i<str.size();i++)
            if (str[i] == '-') sign = 1;
            else x*=10,x+=str[i]-'0';
        return sign?-x:x;
    }
    i128 abs(const i128 x){return x < 0 ? -x : x;}
    istream& operator>>(istream& is,i128 &x){
        std::string s;
        is >> s,x = stoi128(s);
        return is;
    }
    ostream& operator<<(ostream& os,const i128 x){
        if (x == 0) return os << 0;
        os << to_string(x);
        return os;
    }
}

6.2 杂项数据结构

6.2.1 取模类(静态模数)

C++
template <long long MOD>
struct ModInt{
    long long val = 0;
    ModInt(long long x = 0):val(norm(x)){}
    long long operator()(){ return val; }
    constexpr ModInt operator-(){
        return ModInt(MOD - val);
    }
    constexpr ModInt operator~(){
        assert(val != 0);
        return Pow(val,MOD-2);
    }
    constexpr ModInt& operator+=(ModInt x){
        return val += x(),val = norm(val),*this;
    }
    constexpr ModInt& operator-=(ModInt x){
        return val -= x(),val = norm(val),*this;
    }
    constexpr ModInt& operator*=(ModInt x){
        return val *= x(),val = norm(val),*this;
    }
    constexpr ModInt& operator/=(ModInt x){
        return val *= (~x)(),val = norm(val),*this;
    }
    constexpr ModInt& operator^=(long long y){
        return val = Pow(*this,y)(),*this;
    }
    constexpr ModInt& operator++(){
        return val ++,val = norm(val),*this;
    }
    constexpr ModInt operator++(int){
        ModInt v = *this;
        return val ++,val = norm(val),v;
    }
    constexpr ModInt& operator--(){
        return val --,val = norm(val),*this;
    }
    constexpr ModInt operator--(int){
        ModInt v = *this;
        return val --,val = norm(val),v;
    }
    constexpr bool operator==(const long long x){
        return val == norm(x);
    }
    constexpr friend ModInt operator+(ModInt x, ModInt y){
        return x += y;
    }
    constexpr friend ModInt operator-(ModInt x, ModInt y){
        return x -= y;
    }
    constexpr friend ModInt operator*(ModInt x, ModInt y){
        return x *= y;
    }
    constexpr friend ModInt operator/(ModInt x, ModInt y){
        return x /= y;
    }
    constexpr friend ModInt operator^(ModInt x, long long y){
        return x ^= y;
    }
    constexpr friend bool operator==(long long x,ModInt y){
        return y == x;
    }
    constexpr friend std::ostream& operator<<(std::ostream& os,ModInt x){
        return os << x();
    }
    constexpr friend std::istream& operator>>(std::istream& is,ModInt &x){
        is >> x.val, x.val = norm(x.val);
        return is;
    }
    constexpr static long long norm(long long x){
        return x < 0 ? (x % MOD + MOD) % MOD : x % MOD;
    }
    constexpr static ModInt Pow(ModInt x,long long y){
        ModInt ans = 1;
        for (;y; y >>= 1,x *= x)
            if (y & 1) ans *= x;
        return ans;
    }
};
using Z = ModInt<998244353>;

6.2.2 取模类(全局模数)

C++
struct DynModInt{
    long long val = 0;
    static long long MOD;
    DynModInt(long long x = 0):val(norm(x)){}
    constexpr static void setMod(long long p){
        MOD = p;
    }
    long long operator()(){ return val; }
    constexpr DynModInt operator-(){
        return DynModInt(MOD - val);
    }
    constexpr DynModInt operator~(){
        assert(val != 0);
        return Pow(val,MOD-2);
    }
    constexpr DynModInt& operator+=(DynModInt x){
        return val += x(),val = norm(val),*this;
    }
    constexpr DynModInt& operator-=(DynModInt x){
        return val -= x(),val = norm(val),*this;
    }
    constexpr DynModInt& operator*=(DynModInt x){
        return val *= x(),val = norm(val),*this;
    }
    constexpr DynModInt& operator/=(DynModInt x){
        return val *= (~x)(),val = norm(val),*this;
    }
    constexpr DynModInt& operator^=(long long y){
        return val = Pow(*this,y)(),*this;
    }
    constexpr DynModInt& operator++(){
        return val ++,val = norm(val),*this;
    }
    constexpr DynModInt operator++(int){
        DynModInt v = *this;
        return val ++,val = norm(val),v;
    }
    constexpr DynModInt& operator--(){
        return val --,val = norm(val),*this;
    }
    constexpr DynModInt operator--(int){
        DynModInt v = *this;
        return val --,val = norm(val),v;
    }
    constexpr friend DynModInt operator+(DynModInt x, DynModInt y){
        return x += y;
    }
    constexpr friend DynModInt operator-(DynModInt x, DynModInt y){
        return x -= y;
    }
    constexpr friend DynModInt operator*(DynModInt x, DynModInt y){
        return x *= y;
    }
    constexpr friend DynModInt operator/(DynModInt x, DynModInt y){
        return x /= y;
    }
    constexpr friend DynModInt operator^(DynModInt x, long long y){
        return x ^= y;
    }
    constexpr friend std::ostream& operator<<(std::ostream& os,DynModInt x){
        return os << x();
    }
    constexpr friend std::istream& operator>>(std::istream& is,DynModInt &x){
        is >> x.val, x.val = norm(x.val);
        return is;
    }
    constexpr static long long norm(long long x){ return (x%MOD+MOD)%MOD;}
    constexpr static DynModInt Pow(DynModInt x,long long y){
        DynModInt ans = 1;
        for (;y; y >>= 1,x *= x)
            if (y & 1) ans *= x;
        return ans;
    }
};

6.2.3 复数

比 std::complex 常数更快

C++
template<typename T>
struct Complex{
    T real,imag;
    Complex(T x = 0,T y = 0):real(x),imag(y){}
    constexpr Complex& operator+=(const Complex &x){
        real += x.real,imag += x.imag;
        return *this;
    }
    constexpr Complex& operator-=(const Complex &x){
        real -= x.real,imag -= x.imag;
        return *this;
    }
    constexpr Complex& operator*=(const Complex &x){
        T rl = real * x.real - imag * x.imag;
        imag = x.imag * real + x.real * imag;
        real = rl;
        return *this;
    }
    constexpr Complex& operator/=(const Complex &x){
        T div = x.real * x.real + x.imag * x.imag;
        T rl = (real*x.real+imag*x.imag) / div;
        imag = (x.real * imag - real * x.imag) / div;
        real = rl;
        return *this;
    }
    constexpr friend Complex operator+(const Complex& x,const Complex y){
        Complex r = x;
        return (r += y);
    }
    constexpr friend Complex operator-(const Complex& x,const Complex y){
        Complex r = x;
        return (r -= y);
    }
    constexpr friend Complex operator*(const Complex& x,const Complex y){
        Complex r = x;
        return (r *= y);
    }
    constexpr friend Complex operator/(const Complex& x,const Complex y){
        Complex r = x;
        return (r /= y);
    }
    constexpr friend std::ostream& operator<<(ostream& os,Complex x){
        return os << x.real << "+" << x.imag << "i";
    }
    constexpr friend std::istream& operator>>(ostream& is,Complex& x){
        return is >> x.real >> x.imag;
    }
    constexpr static Complex Pow(Complex x,long long p){
        Complex res = {1,0};
        for (;p;p >>= 1,x *= x){
            if (p&1) res *= x;
        }
        return res;
    }
};
using Comp = Complex<double>;

The End

原文