【模板】模板整理贴
Author: Kendieer
Last updated: 2026/08/19
1.数学
1.1 数论
1.1.1 质数筛
namespace Sieve{
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)
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)
需要 exgcd 模板。
i64 multi(i64 a, i64 b, i64 p) { // 龟速乘
i64 ans = 0;
for (; b; b >>= 1, a += a, a %= p) if (b & 1) ans += a, ans %= p;
return ans;
}
i64 crt(int n, std::vector <i64> &m, std::vector <i64> &p) { // x%m=p
i64 LCM = 1, ans = 0;
for (int i = 0; i < n; i++) LCM *= m[i];
assert(LCM);
for (int i = 0; i < n; i++) {
i64 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;
}
i64 excrt(int n, std::vector <i64> &m, std::vector <i64> &p) {
i64 LCM = 1, ans = 0;
for (int i = 0; i < n; i++) {
i64 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 欧拉定理(欧拉降幂)
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(x % i == 0) x /= 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 欧拉函数
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 原根
仅参考,实际可以预先处理出原根直接使用。
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;
}
常见质数模数的最小原根
1.1.7 二次剩余
需要使用 ModInt 类和对 Complex<Z> 特化后的模板类
Cipolla 算法
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.1.8 Miller Rabin 素性测试
using i64 = long long;
i64 mul(const i64& x,const i64& y,const i64& m){
return static_cast<__int128>(x) * y % m;
}
i64 quickPower(i64 a,i64 p,i64 m){
i64 r = 1;
for(a %= m;p;p>>=1,a = mul(a,a,m)) {
if (p & 1) r = mul(r,a,m);
}
return r;
}
bool isPrime(i64 n){
if (n == 2 || n == 3) return 1;
if (n % 2 == 0 || n % 3 == 0 || n < 2) return 0;
int p2 = __builtin_ctzll(n-1);
static constexpr int P[] = {2,325,9375,28178,450775,9780504,1795265022};
for (const auto& p : P){
if (p % n == 0) break;
i64 x = quickPower(p, n-1 >> p2,n);
if (x == 1 || x == n-1) continue;
for (int i = 1;i <= p2;i++){
i64 y(x);
x = mul(x,x,n);
if (x == 1) {
if (y != n-1) return 0;
break;
}
}
if (x != 1) return 0;
}
return 1;
}
1.1.9 质因数分解(Pollard-Rho)
时间复杂度为
需要 Miller Rabin 素性测试 模板。
using i64 = long long;
std::vector<i64> factorize(i64 v) {
static constexpr int C = 1e4;
std::vector<i64> p;
while ((v & 1) == 0) {
p.push_back(2);
v >>= 1;
}
std::function<void(i64)> PollardRho = [&](i64 n)->void {
if (isPrime(n)) {
p.push_back(n);
return;
}
if (n <= C) {
for (int i = 2;i * i <= n;i++){
while (n % i == 0) {
p.push_back(i);
n /= i;
}
}
if (n > 1) p.push_back(n);
return;
}
static std::mt19937_64 rng(time(0));
std::uniform_int_distribution<i64> uf(1,n-1);
i64 c = uf(rng);
auto f = [&](i64 x)->i64 {
return (static_cast<__int128>(x) * x + c) % n;
};
while (1) {
i64 x = 0,y = 0;
i64 d = 1,prod = 1;
int lmt = 1,cnt = 0;
while (d == 1) {
y = f(y);
prod = mul(prod,std::abs(x-y),n);
++cnt;
if (cnt % 127 == 0) {
d = std::gcd(prod,n);
prod = 1;
}
if (lmt == cnt) {
x = y;
cnt = 0;
lmt <<= 1;
d = std::gcd(prod,n);
prod = 1;
}
}
if (d != n) {
PollardRho(n/d);
PollardRho(d);
return;
}
c = uf(rng);
}
};
PollardRho(v);
std::sort(p.begin(),p.end());
return p;
}
1.2 组合数学
1.2.1 排列组合及卢卡斯定理
需要配合 ModInt<MOD> 使用。
template <unsigned long long MOD>
struct Combination{
using Z = ModInt<MOD>;
private:
int siz = 0;
std::vector<Z> _fact,_inv;
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);
}
public:
Combination():siz(1),_fact(1,1),_inv(1,1){}
Z fact(int n){
if (n < 0) return inv(-n);
check(n+1);
return _fact[n];
}
Z inv(int n){
if (n < 0) return fact(-n);
check(n+1);
return _inv[n];
}
Z A(int n,int m){
if (n < 0 || m < 0 || n < m) return 0;
check(n+1);
return _fact[n]*_inv[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);
}
Z Catalan(int n){
if (n < 0) return 0;
if (n == 0) return 1;
return C(2*n,n) - C(2*n,n-1);
}
};
Combination<998244353> comb;
1.2.2 二项式定理和二项式反演
1.2.2.1 二项式定理
1.2.2.2 二项式反演
1.3 线性代数
1.3.1 矩阵
using std::vector;
template<typename T,typename Mul = std::multiplies<T>,typename Add = std::plus<T>>
struct Matrix{
int N,M;
vector<vector<T>> value;
Matrix(int n,int m):N(n),M(m),value(vector<vector<T>>(n,vector<T>(m))){}
Matrix(int n):N(n),M(n),value(vector<vector<T>>(n,vector<T>(n))){}
Matrix(const vector<T>& v):N(1),M(v.size()),value(vector<vector<T>>(1,v)){}
Matrix(const vector<vector<T>>& v):value(v),N(v.size()),M(v[0].size()){}
void normalize(){
assert(N==M);
for (int i = 0;i < N;i++){
for (int j = 0;j < N;j++){
value[i][j] = T(i == j);
}
}
}
void fill(const T& val){
std::fill(value.begin(),value.end(),vector<T>(M,val));
}
vector<T>& operator[](int idx){
return value[idx];
}
Matrix& operator+=(const Matrix &x){
assert(N==x.N&&M==x.M);
for (int i = 0; i < N; ++i){
for (int j = 0; j < M; ++j){
value[i][j] = Add()(value[i][j],x.value[i][j]);
}
}
return *this;
}
friend Matrix operator+(Matrix x,const Matrix &y){
return x += y;
}
friend Matrix operator*(const Matrix& a,const Matrix& b){
assert(a.M == b.N);
Matrix r(a.N,b.M);
for (int i = 0; i < a.N; ++i){
for (int k = 0; k < a.M; ++k){
for (int j = 0; j < b.M; ++j){
r.value[i][j] = Add()(r.value[i][j],Mul()(a.value[i][k],b.value[k][j]));
}
}
}
return r;
}
Matrix& operator *=(const Matrix &x){
Matrix r = *this*x;
std::swap(value,r.value);
return *this;
}
static Matrix Pow(const Matrix& a,long long p){
assert(a.N == a.M);
Matrix r(a.N),tmp = a;
r.normalize();
for (;p;p >>= 1,tmp *= tmp) if (p&1) r *= tmp;
return r;
}
Matrix operator^(long long p){
return Pow(*this,p);
}
Matrix& operator^=(long long p){
*this = Pow(*this,p);
return *this;
}
friend std::istream& operator>>(std::istream& is,Matrix& m){
for (int i = 0; i < m.N; ++i){
for (int j = 0; j < m.M; ++j){
is >> m.value[i][j];
}
}
return is;
}
friend std::ostream& operator<<(std::ostream& os,const Matrix& m){
for (int i = 0; i < m.N; ++i){
for (int j = 0; j < m.M; ++j){
os << m.value[i][j] << " \n"[j==m.M-1];
}
}
return os;
}
};
1.3.2 高斯消元
1.3.2.1 高斯消元求解线性方程组
namespace Gauss{
using f64 = long double;
using std::vector;
constexpr f64 eps = 1E-6;
int work(vector<vector<f64>> &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]);
f64 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;
f64 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.2.2 高斯消元计算行列式
取模版本使用于任意模数,时间复杂度为
浮点数版本可能误差较大,需要手动调整误差,时间复杂度为
namespace Guass {
using MInt = Z;
using std::vector;
MInt det(vector<vector<MInt>> R){
const int n = R.size();
MInt w = 1;
for (int i = 0;i < n;i++){
assert(R[i].size() == n);
for (int j = i + 1;j < n;j++){
while (R[i][i] != 0) {
int div = R[j][i]() / R[i][i]();
for (int k = 0;k < n;k++) R[j][k] -= R[i][k] * div;
swap(R[j],R[i]);
w = -w;
}
swap(R[i],R[j]);
w = -w;
}
}
MInt ans = 1;
for (int i = 0;i < n;i++) ans *= R[i][i];
return ans * w;
}
constexpr double eps = 1e-8;
double det(vector<vector<double>> R){
const int n = R.size();
double w = 1;
for (int i = 0;i < n;i++){
assert(R[i].size() == n);
for (int j = i+1;j < n;j++){
if (R[j][i] > R[i][i]) {
swap(R[i],R[j]);
w = -w;
}
}
if (abs(R[i][i]) <= eps) return 0;
double d = R[i][i];
w *= d;
for (int j = i;j < n;j++) R[i][j] /= d;
for (int j = i+1;j < n;j++){
if (abs(R[i][i]) <= eps) return 0;
double t = R[j][i];
for (int k = i;k < n;k++){
R[j][k] -= t * R[i][k];
}
}
}
double ans = 1;
for (int i = 0;i < n;i++) ans *= R[i][i];
return ans * w;
}
};
1.3.2.3 高斯-约旦消元法求矩阵逆
namespace Guass {
using MInt = Z;
using std::vector;
vector<vector<MInt>> inverse(const vector<vector<MInt>>& R){
const int n = R.size();
vector<vector<MInt>> A(n,vector<MInt>(2*n));
for (int i = 0;i < n;i++){
assert(R[i].size() == n);
for (int j = 0;j < n;j++){
A[i][j] = R[i][j];
}
A[i][i+n] = 1;
}
vector<vector<MInt>> I;
for (int i = 0;i < n;i++){
for (int j = i;j < n;j++){
if (A[j][i] != 0) {
swap(A[i],A[j]);
break;
}
}
if (A[i][i] == 0) return I;
MInt inv = 1 / A[i][i];
for (int k = 0;k < 2*n;k++) A[i][k] *= inv;
for (int j = 0;j < n;j++){
if (i == j) continue;
MInt x = A[j][i];
for (int k = 0;k < 2*n;k++){
A[j][k] -= A[i][k] * x;
}
}
}
I.assign(n,vector<MInt>(n));
for (int i = 0;i < n;i++){
for (int j = 0;j < n;j++){
I[i][j] = A[i][j+n];
}
}
return I;
}
};
using namespace Guass;
1.3.3 线性基(含高斯消元)
template<int N = 30>
struct Basis{
using i64 = long long;
private:
i64 b[N+1];
int cnt = 0;
public:
Basis() {
std::fill(b,b+N+1,0);
}
bool insert(i64 x) {
if (!x) return 0;
for (int i = N;i >= 0;i--){
if (!(x >> i & 1)) continue;
if (!b[i]) {
b[i] = x;
for (int j = N;j >= 0;j--){
if (i == j || !b[j]) continue;
if (b[j] >> i & 1) b[j] ^= x;
}
++cnt;
return 1;
} else x ^= b[i];
}
return 0;
}
i64 operator[](const int& i){return b[i];}
bool operator==(const Basis& rhs) const {
if (cnt != rhs.count()) return 0;
for (int i = N;i >= 0;i--) {
if (b[i] != rhs.b[i]) return 0;
}
return 1;
}
int count() const {
return cnt;
}
};
1.4 生成函数以及多项式
1.4.1 快速傅里叶变换(FFT)
需要配合 Complex 类使用。
// 需要配合 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 使用。
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.4.3 快速数论变换(NTT)
需要 ModInt 取模类以及对应的原根。
注意,NTT 仅能至多处理原长度为
1.4.3.0 DFT 与 IDFT 函数
以下所有模板均需要依赖 DFT 和 IDFT 运行。
constexpr int PolyMod = 998244353;
using MInt = ModInt<PolyMod>;
const MInt g = 3,gi = ~g;
using Poly = std::vector<MInt>;
using std::min;
void dft(const int& len,Poly& arr,int sign){ // sign = -1 -> IDFT
int lg2 = std::__lg(len);
std::vector<int> revi(len);
for (int i = 1;i < len;i ++)
revi[i] = revi[i] = (revi[i>>1]>>1) | ((i&1)<<(lg2-1));
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;
MInt Wn = (sign == 1 ? g : gi);
Wn = MInt::Pow(Wn,(PolyMod-1)/p);
for (int l = 0;l < len;l += p){
MInt 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].val - tmp;
arr[i] += tmp;
}
}
}
if (sign == -1){
MInt inv = ~MInt(len);
for (int i = 0;i < arr.size();i ++) arr[i] *= inv;
}
}
1.4.3.1 多项式杂项函数
包含多项式求导和多项式积分。
Poly polyDiff(Poly f){
assert(f.size());
for (int i = 0;i < f.size()-1;i ++) f[i] = f[i+1] * (i+1);
f.back() = 0;
return f;
}
Poly polyInteg(Poly f){
assert(f.size());
for (int i = f.size()-1;i >= 1;i --) f[i] = f[i-1] / i;
f.front() = 0;
return f;
}
1.4.3.2 多项式乘法
Poly& operator*=(Poly& A,Poly B){
int limit = 1,siz = A.size() + B.size() - 1;
while (limit <= siz) limit <<= 1;
A.resize(limit,0);
B.resize(limit,0);
dft(limit,A,1);
dft(limit,B,1);
for (int i = 0;i < limit;i ++) A[i] *= B[i];
dft(limit,A,-1);
A.resize(siz);
return A;
}
Poly polyMul(Poly A,Poly B){
return A *= B;
}
1.4.3.2 多项式乘法逆
前置模板:1.4.3.2 多项式乘法
Poly polyInv(const Poly& F){
Poly G(1,1 / F[0]);
const int& n = F.size();
for (int i = 1;i < n << 1;i <<= 1){
const int& len = i << 1;
G.resize(len);
Poly F2(F.begin(),F.begin()+std::min(i,n));
F2.resize(len,0);
dft(len,F2,1);
dft(len,G,1);
for (int j = 0;j < len;j++){
G[j] = (2 - G[j] * F2[j]) * G[j];
}
dft(len,G,-1);
std::fill(G.begin()+i,G.end(),0);
}
G.resize(n);
return G;
}
1.4.3.4 多项式除法与多项式求余
需要前置模板:1.4.3.2 多项式乘法,1.4.3.3 多项式乘法逆。
Poly& operator/=(Poly& A,Poly B){
const int& n = A.size(),m = B.size(),k = n - m + 1;
std::reverse(A.begin(),A.end());
std::reverse(B.begin(),B.end());
A.resize(k);
B.resize(k);
A *= polyInv(B);
A.resize(k);
std::reverse(A.begin(),A.end());
return A;
}
Poly polyDiv(Poly A,Poly B){
return A /= B;
}
Poly& operator%=(Poly& A,Poly B){
const int& n = A.size(),m = B.size();
Poly C = polyDiv(A,B);
B *= C;
for (int i = 0;i < n;i++){
A[i] -= B[i];
}
A.resize(m-1);
return A;
}
Poly polyMod(Poly A,Poly B){
return A %= B;
}
1.4.3.5 多项式对数(自然底数)
需要前置模板:1.4.3.1 多项式杂项,1.4.3.2 多项式乘法,1.4.3.3 多项式乘法逆。
Poly polyLn(const Poly& F){
Poly dF = polyMul(polyDiff(F),polyInv(F));
return polyInteg(dF);
}
1.4.3.6 多项式指数函数(exp)
需要前置模板:1.4.3.1 多项式杂项,1.4.3.2 多项式乘法,1.4.3.3 多项式乘法逆,1.4.3.5 多项式对数。
Poly polyExp(const Poly& F){
Poly G(1,1);
const int& n = F.size();
for (int i = 2;i < n << 1;i <<= 1){
G.resize(i);
Poly F2(polyLn(G));
for (int j = 0;j < min(i,n);j++){
F2[j] = F[j]-F2[j];
}
++F2[0];
G *= F2;
}
G.resize(n);
return G;
}
1.4.3.7 多项式开根
需要前置模板:1.4.3.3 多项式乘法逆。
使用条件:当前 Newton 迭代要求选出的常数项平方根非零,从而可以求逆,且若 Cipolla 等二次剩余算法求出。
Poly polySqrt(const Poly& F){
Poly G(1,1);// 如果 F[0] 不为 1 需要求 F[0] 的二次剩余
const int& n = F.size();
const MInt& inv2 = ~MInt(2);
for (int i = 2;i < n << 1;i <<= 1){
G.resize(i);
Poly F2(F.begin(),F.begin()+min(i,n)),G2(G);
for (int j = 0;j < i;j++) G2[j] += G2[j];
G2 = polyInv(G2);
G2 *= F2;
G2.resize(i);
for (int j = 0;j < i;j++){
G[j] = G2[j] + G[j] * inv2;
}
}
G.resize(n);
return G;
}
1.4.3.8 多项式快速幂
前置模板:1.4.3.1 多项式杂项,1.4.3.2 多项式乘法,1.4.3.3 多项式乘法逆,1.4.3.5 多项式对数,1.4.3.6 多项式指数函数。
Poly polyPow(Poly F,const int& k){
const int& n = F.size();
F = polyLn(F);
for (int i = 0;i < n;i++){
F[i] *= k;
}
return polyExp(F);
}
1.5 数值计算
1.5.1 拉格朗日插值法
1.5.1.1 x 无限制版本(求f(x)系数版本)
普适所有坐标版本,时间复杂度为
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 为连续正整数版本
其插值式子为:
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 分数
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 高精度运算
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 数组)
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
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)
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 分解
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)
如果需要精确每个模式串匹配到的次数,需要记录终止节点编号+拓扑统计。
template<int S,int E>
struct AhoCorasick{
AhoCorasick(){
nodes.resize(1);
}
static constexpr int charSiz = E-S+1;
struct ACNode{
int fa = 0, fail = 0, in = 0;
bool built = 0;
std::vector<int> nxt = std::vector<int>(charSiz);
int& operator[](int i){return nxt[i];}
};
std::vector<ACNode> nodes;
constexpr int ch(int raw){
return raw - S;
}
constexpr int newNode(int fa = 0){
nodes.push_back(ACNode());
nodes.back().fa = fa;
return nodes.size() - 1;
}
int operator>>(const std::string& s){
assert(!nodes[0].built);
int cur = 0;
for (int i = 0;i < s.size();i ++){
int chd = ch(s[i]);
if (!nodes[cur][chd]) nodes[cur][chd] = newNode(cur);
cur = nodes[cur][chd];
}
return cur;
}
int& fail(int u){
return nodes[u].fail;
}
void build(){
if (nodes.front().built) return;
nodes.front().built = 1;
std::queue<int> bfs;
for (int v : nodes[0].nxt){
if (v) {
bfs.push(v);
nodes[v].built = 1;
}
}
while(bfs.size()){
int u = bfs.front();
bfs.pop();
for (int i = 0;i < charSiz;i ++){
const int &chd = nodes[u][i];
if (chd) {
if (!nodes[chd].built){
nodes[chd].built = 1;
bfs.push(chd);
fail(chd) = nodes[fail(u)][i];
nodes[fail(chd)].in ++;
}
} else {
nodes[u][i] = nodes[fail(u)][i];
}
}
}
}
ACNode& operator[](int i){
return nodes[i];
}
};
using ACAM = AhoCorasick<'a','z'>;
2.2.2 广义后缀自动机(GSAM)
/*
* 注意: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)
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 自然溢出模数。(无视基数)
// 用于 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 并查集及可撤销并查集
// 路径压缩版本
struct Disjoint{
std::vector<int> fa,siz,top;
int cnt=0;
Disjoint(int n = 0){
init(n);
}
void init(int n = 0){
fa.resize(n+1);
top.resize(n+1);
siz.assign(n+1,1);
std::iota(fa.begin(),fa.end(),0);
std::iota(top.begin(),top.end(),0);
cnt = n;
}
void operator()(int head,int ele){ // merge
head = root(head),ele = root(ele);
if (head == ele) return;
top[ele] = top[head];
if (siz[head] < siz[ele]) std::swap(head,ele);
siz[head]+=siz[ele];
fa[ele]=head;
}
int operator[](int index){return top[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 树状数组
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.1.3 ST表(Sparse Table)
template<typename T>
struct SparseTable {
std::vector<std::vector<T>> st;
std::function<T(T, T)> opt;
SparseTable(const vector<T>& ele, int beg, std::function<T(T, T)> func) : opt(func) {
build(ele, beg);
}
SparseTable(const vector<T>& ele, int beg = 0) {
opt = [](T a, T b) { return max(a, b); };
build(ele, beg);
}
void build(const vector<T>& ele, int beg) {
int n = ele.size() - 1;
int len = n - beg + 1;
if (len <= 0) return;
int p = __lg(len);
st.assign(n + 1, vector<T>(p + 1));
for (int i = beg; i <= n; i++) st[i][0] = ele[i];
for (int j = 1; j <= p; j++) {
for (int i = beg; i + (1 << j) - 1 <= n; i++) {
st[i][j] = opt(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
}
}
}
T operator()(int l, int r) const {
int p = __lg(r - l + 1);
return opt(st[l][p], st[r - (1 << p) + 1][p]);
}
};
3.2 高级数据结构
3.2.1 线段树
template<typename Info,typename Tag>
struct SegmentTree {
private:
int _n = 0;
std::vector<Info> _info;
std::vector<Tag> _tag;
public:
SegmentTree(int n = 0){
rebuild(n);
}
SegmentTree(const std::vector<Info>& v){
assert(v.size() >= 1);
rebuild(v.size() - 1,v);
}
void rebuild(int n,const std::vector<Info>& v = std::vector<Info>(0)){
_n = n;
_info.assign((_n + 2) << 2,Info());
_tag.assign((_n + 2) << 2,Tag());
if (n > 0) build(1,1,n,v);
}
private:
void build(int i,int l,int r,const std::vector<Info>& v){
if(l == r){
if (v.size() > l) _info[i] = v[l];
resize(_info[i],l,r);
return;
}
int mid = l + r >> 1;
build(i << 1,l,mid,v);
build(i << 1 | 1,mid + 1,r,v);
push_up(i,l,r);
}
void resize(Info& info,int l,int r){
info.l = l;
info.r = r;
}
void push_down(int i){
_info[i << 1].apply(_tag[i]);
_info[i << 1 | 1].apply(_tag[i]);
_tag[i << 1].apply(_tag[i]);
_tag[i << 1 | 1].apply(_tag[i]);
_tag[i] = Tag();
}
void push_up(int i,int l,int r){
_info[i] = _info[i << 1] + _info[i << 1 | 1];
resize(_info[i],l,r);
}
void modify(int i,const Tag& val,int l,int r,int ql,int qr){
if (ql <= l && r <= qr) {
_info[i].apply(val);
_tag[i].apply(val);
return;
}
push_down(i);
int mid = l + r >> 1;
if (ql <= mid) modify(i << 1, val, l, mid, ql, qr);
if (qr > mid) modify(i << 1 | 1, val, mid+1, r, ql, qr);
push_up(i,l,r);
}
Info ask(int i,int l,int r,int ql,int qr){
if (ql <= l && r <= qr) {
return _info[i];
}
push_down(i);
int mid = l + r >> 1;
if (qr <= mid) return ask(i << 1, l, mid, ql, qr);
else if (ql > mid)return ask(i << 1 | 1, mid+1, r, ql, qr);
Info res = ask(i << 1, l, mid, ql, qr);
res = res + ask(i << 1 | 1, mid+1, r, ql, qr);
resize(res,std::max(ql,l),std::min(qr,r));
return res;
}
public:
void modify(int l,int r,const Tag& val){
if (l > r) return;
modify(1,val,1,_n,std::max(1,l),std::min(r,_n));
}
Info operator()(int l,int r){
if (l > r) return Info();
return ask(1,1,_n,std::max(1,l),std::min(r,_n));
}
};
struct Tag{
Tag(){}
void apply(const Tag& t){
}
};
struct Info{
int l = 1,r = 0;
Info(){}
void apply(const Tag& t){
}
friend Info operator+(const Info& lhs,const Info& rhs){
Info res;
return res;
}
};
3.2.2 主席树(可持久化线段树)
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 左偏树(可并堆)
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 笛卡尔树
struct Cartesian{
template<typename T,typename CMP = std::less<T>>
static std::vector<std::array<int,2>> build(std::vector<T>& arr,int s = 0,int empty = -1,CMP compare = CMP()){
std::vector<int> stk;
std::vector<std::array<int,2>> bst(arr.size(),{empty,empty});
for (int i = s;i < arr.size();i ++){
while(stk.size() && compare(arr[stk.back()],arr[i])){
bst[i][0] = stk.back();
stk.pop_back();
}
if (stk.size()) bst[stk.back()][1] = i;
stk.push_back(i);
}
return bst;
}
};
3.3.2 Splay
本版本为 多重集 版本。存在多个相等值时,删除时仅删除其中一个。
template <typename T = long long>
struct Splay{
using u32 = unsigned int;
std::vector<T> key;
u32 head = 0;
std::vector<u32> fa,siz,h;
std::vector<std::array<u32,2>> son;
Splay(){
newNode();
tr_siz = 0;
}
u32 rank(T x){
u32 rk = 0,u = head,lst = 0;
while (u) {
lst = u;
if (key[u] < x) {
rk += siz[son[u][0]] + 1;
}
u = son[u][key[u] < x];
}
splay(lst,0);
return rk+1;
}
void insert(T x){
if (head == 0) {
u32 v = newNode();
head = v;
key[v] = x;
update(v);
} else {
u32 lst,i,u = head;
while (u) {
lst = u;
i = !(x < key[u]);
u = son[u][i];
}
u32 v = newNode();
son[lst][i] = v;
fa[v] = lst;
key[v] = x;
update(v);
update(lst);
splay(v,0);
}
}
void remove(T x){
u32 rk = rank(x);
if (rk == rank(x+1)) return;
u32 i = find(rk);
splay(i,0);
if (son[i][0] == 0 || son[i][1] == 0) {
u32 j = son[i][0] == 0;
head = son[i][j];
delNode(i);
} else {
u32 j = find(rk+1);
assert(son[j][0] == 0); // self check
splay(j,i);
assert(son[i][1] == j); // self check
if (son[i][0]) fa[son[i][0]] = j;
son[j][0] = son[i][0];
delNode(i);
update(j);
head = j;
}
fa[head] = 0;
}
T index(u32 rk) {
u32 i = find(rk);
splay(i,0);
return key[i];
}
// STL-like:
u32 size() const {
return tr_siz;
}
u32 height() const {
return h[head];
}
u32 count(T x) {
return rank(x+1) - rank(x);
}
bool contains(T x) {
u32 u = head,lst = 0;
bool ans = 0;
while (u) {
lst = u;
if (key[u] == x) {
ans = 1;
break;
}
u32 i = x < key[u];
u = son[u][i];
}
splay(lst,0);
return ans;
}
private:
u32 tr_siz = 0;
std::vector<u32> del;
u32 newNode(){
u32 cur = 0;
if (del.size()){
cur = del.back();
del.pop_back();
} else {
cur = key.size();
key.emplace_back(0);
fa.emplace_back(0);
siz.emplace_back(0);
h.emplace_back(0);
son.emplace_back(std::array<u32,2>({0,0}));
}
tr_siz++;
return cur;
}
void delNode(u32 i){
del.push_back(i);
siz[i] = 0;
fa[i] = 0;
son[i][0] = son[i][1] = 0;
h[i] = 0;
tr_siz--;
}
u32 find(u32 rank) const {
u32 i = head;
while (i){
if (siz[son[i][0]] + 1 == rank){
return i;
}
if (siz[son[i][0]] + 1 < rank){
rank -= siz[son[i][0]] + 1;
i = son[i][1];
} else {
i = son[i][0];
}
}
return 0;
}
void update(u32 i){
if (i <= 0) return;
siz[i] = siz[son[i][0]] + siz[son[i][1]] + 1;
h[i] = std::max(h[son[i][0]],h[son[i][1]]) + 1;
}
u32 dir(u32 u) const {
return son[fa[u]][1] == u;
}
void rotate(u32 u){
u32 f = fa[u],gf = fa[f];
u32 i = dir(u);
son[f][i] = son[u][!i];
if (son[f][i]) fa[son[f][i]] = f;
son[u][!i] = f;
if (gf) {
u32 gi = dir(f);
son[gf][gi] = u;
}
fa[f] = u;
fa[u] = gf;
update(f);
update(u);
}
void splay(u32 u,u32 rt){
if (u == 0) return;
u32 f = fa[u];
while (f != rt) {
if (fa[f] != rt) {
rotate(dir(f) == dir(u) ? f : u);
}
rotate(u);
f = fa[u];
}
if (!rt) head = u;
}
public:
// Debug
void __selfValidation(){
std::vector<u32> pts;
std::function<void(u32)> dfs = [&](u32 u)->void {
if (u == 0) return;
dfs(son[u][0]);
pts.push_back(u);
dfs(son[u][1]);
};
dfs(head);
bool MonoValid = true,RankValid = true;
for (u32 i = 0,j = 1;j < pts.size();i++,j++){
if (key[pts[i]] > key[pts[j]]) MonoValid = false;
}
for (u32 l = 0,r = 0,rk = 0;r < pts.size();r++){
if (key[pts[r]] > key[pts[l]]) rk += r-l,l = r;
if (rank(key[pts[r]]) != rk + 1) RankValid = false;
}
assert(MonoValid);
assert(RankValid);
}
};
3.3.3 FHQ Treap(无旋 Treap)
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 静态树
4.1.1.1 O(1) LCA
需要 SparseTable 模板。
vector<int> dfn(n+1),dep(n+1),fa(n+1),seq(1);
int dfnt = 0;
auto dfs = [&](this auto&& dfs,int u,int pa) -> void {
dfn[u] = ++dfnt;
dep[u] = dep[pa] + 1,fa[u] = pa;
seq.push_back(u);
for (int v : G[u]){
if (v == pa) continue;
dfs(v,u);
}
};
dfs(1,1);
SparseTable<int> st(seq, 1,[&](int x,int y) -> int {
return dep[x] <= dep[y] ? x : y;
});
auto lca = [&](int x,int y) -> int {
if (x == y) return x;
x = dfn[x],y = dfn[y];
if (x > y) swap(x,y);
return fa[st(x+1,y)];
};
4.1.1.2 树链剖分(重链剖分)
vector<int> siz(n+1,1),dep(n+1),fa(n+1),son(n+1),top(n+1),dfn(n+1),seq(1);
auto dfs1 = [&](this auto&& dfs,int u,int pa)->void {
fa[u] = pa;
dep[u] = dep[pa] + 1;
int mx = 0;
for (int v : G[u]){
if (v == pa) continue;
dfs(v,u);
siz[u] += siz[v];
if (mx < siz[v]){
son[u] = v;
mx = siz[v];
}
}
};
int tick = 0;
auto dfs2 = [&](this auto&& dfs,int u,int tp)->void {
dfn[u] = ++tick;
seq.push_back(u);
top[u] = tp;
if (son[u]) {
dfs(son[u],tp);
}
for (int v : G[u]){
if (v == fa[u] || v == son[u]) continue;
dfs(v,v);
}
};
dfs1(1,1);
dfs2(1,1);
auto lca = [&](int x,int y) -> int {
while (top[x] != top[y]) {
if (dep[top[x]] > dep[top[y]]) swap(x,y);
y = fa[top[y]];
}
return dep[x] > dep[y] ? y : x;
};
4.1.1.3 Prufer 序列
struct Prufer{
static std::vector<int> encode(std::vector<std::vector<int>>& G,int n){
std::vector<int> fa = transfromFa(G,n);
return encode(fa,n);
}
static std::vector<int> encode(std::vector<int>& fa,int n){
std::vector<int> deg(n+1);
for (int i = 1;i < n;i++) {
deg[i]++;
deg[fa[i]]++;
}
std::vector<int> res;
for (int cur = 1;cur < n;cur++){
int u = cur;
while (deg[u] == 1 && u <= cur){
res.push_back(fa[u]);
deg[fa[u]]--,deg[u]--;
u = fa[u];
}
}
return res;
}
static std::vector<int> decode(std::vector<int> a,int n){
std::vector<int> deg(n+1),fa(n+1);
for (int i = 0;i < a.size();i++) deg[a[i]]++;
a.push_back(n);
for (int cur = 1,i = 0,tmp = -1;i < a.size();i++){
int u;
if (tmp != -1) {
u = tmp;
tmp = -1;
} else {
while (deg[cur] > 0) cur++;
u = cur;
cur++;
}
fa[u] = a[i];
deg[a[i]]--;
if (deg[a[i]] == 0 && cur > a[i]) tmp = a[i];
}
return fa;
}
private:
static std::vector<int> transfromFa(std::vector<std::vector<int>>& G,int n){
std::vector<int> fa(n+1);
auto dfs = [&](this auto&& dfs,int u,int pa)->void {
fa[u] = pa;
for (int v : G[u]) {
if (v == pa) continue;
dfs(v,u);
}
};
dfs(n,n);
return fa;
}
};
4.1.2 动态树
4.1.2.1 Link Cut Tree
模板为求路径异或和版本。
struct LinkCutTree {
using u32 = unsigned int;
LinkCutTree(u32 _n){
init(_n);
}
struct Node {
int w = 0,sum = 0;
};
std::vector<Node> G;
std::vector<u32> siz,fa;
std::vector<std::array<u32,2>> son;
std::vector<bool> rev;
u32 size() const {
return treeSize;
}
void pushDown(u32 u){
if (!u) return;
if (rev[u]){
if (u32 v = son[u][0]) flipNode(v);
if (u32 v = son[u][1]) flipNode(v);
rev[u] = false;
}
}
void pushUp(u32 u){
if (!u) return;
G[u].sum = G[u].w;
if (son[u][0]) G[u].sum ^= G[son[u][0]].sum;
if (son[u][1]) G[u].sum ^= G[son[u][1]].sum;
siz[u] = siz[son[u][0]] + siz[son[u][1]] + 1;
}
private:
u32 treeSize = 0;
void init(u32 n){
G.resize(n+1);
fa.resize(n+1);
siz.resize(n+1);
son.resize(n+1);
rev.resize(n+1);
treeSize = n;
for (u32 i = 0;i <= n;i++) initNode(i);
}
void initNode(u32 x){
son[x] = {0,0};
fa[x] = 0;
siz[x] = x == 0 ? 0 : 1;
rev[x] = 0;
}
bool isRoot(u32 u) const {
return !u || son[fa[u]][0] != u && son[fa[u]][1] != u;
}
u32 dir(u32 u){
assert(!isRoot(u));
return son[fa[u]][1] == u;
}
void rotate(u32 u){
if (!u || !fa[u] || isRoot(u)) return;
u32 f = fa[u],i = dir(u);
u32 gf = fa[f];
if (!isRoot(f)) son[gf][dir(f)] = u;
son[f][i] = son[u][!i];
son[u][!i] = f;
if (son[f][i]) fa[son[f][i]] = f;
fa[u] = gf;
fa[f] = u;
pushUp(f);
pushUp(u);
}
void flipNode(u32 u){
std::swap(son[u][0],son[u][1]);
rev[u] = !rev[u];
}
void reverse(u32 u){
if (!u) return;
splay(u);
flipNode(u);
}
public:
void splay(u32 u){
std::vector<u32> stk;
stk.emplace_back(u);
u32 x = u;
while (!isRoot(x)){
x = fa[x];
stk.emplace_back(x);
}
while (!stk.empty()) {
pushDown(stk.back());
stk.pop_back();
}
u32 f = fa[u];
while (!isRoot(u)){
if (!isRoot(f)){
rotate(dir(f) == dir(u) ? f : u);
}
rotate(u);
f = fa[u];
}
pushUp(u);
}
void access(u32 u){
u32 lst = 0;
for (u32 x = u;x;x = fa[x]){
splay(x);
son[x][1] = lst;
pushUp(x);
lst = x;
}
splay(u);
}
void make_root(u32 u){
access(u);
reverse(u);
}
void split(u32 x,u32 y){
make_root(x);
access(y);
splay(y);
}
void link(u32 x,u32 y){
if (find_root(x) == find_root(y)) return;
make_root(x);
fa[x] = y;
}
void cut(u32 x,u32 y){
split(x,y);
if (son[x][1] || son[y][0] != x) return;
fa[x] = son[y][0] = 0;
pushUp(y);
}
u32 find_root(u32 u){
access(u),splay(u);
while(son[u][0]) u = son[u][0];
return u;
}
void modify(u32 x,int val){
splay(x);
G[x].w = val;
pushUp(x);
}
};
4.2 有环图
4.2.1 强联通分量与缩点(SCC)
带点权合并版本。
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 边双联通分量(EBCC)
struct EBCC{
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,ebcc;
EBCC(int siz){
size = siz + 1;
std::vector<std::vector<int>*> ptr = {&low,&dfn,&ebcc};
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();
ebcc[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 = ebcc[i];
for (auto [v,id] : G1[i]){
if (ebcc[v] == u) continue;
G2[u].push_back(ebcc[v]);
G2[ebcc[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 割点与割边
4.2.3.1 割点
struct CutVertex{
int siz,tim = 0;
std::vector<std::vector<int>> G;
std::vector<int> dfn,low;
std::vector<bool> vis,isCut;
CutVertex(int n = 1):siz(n),G(n+1),dfn(n+1),low(n+1),vis(n+1),isCut(n+1){}
void connect(int u,int v){
assert(u <= siz && v <= siz);
G[u].push_back(v);
G[v].push_back(u);
}
void dfs(int u,int pa,bool isRoot = 0){
vis[u] = 1;
dfn[u] = ++tim,low[u] = dfn[u];
int deg = 0;
for (int v : G[u]){
if (v == pa) continue;
if (vis[v]) {
low[u] = std::min(low[u],dfn[v]);
} else {
deg++;
dfs(v,u);
low[u] = std::min(low[u],low[v]);
if (!isRoot && low[v] >= dfn[u]) isCut[u] = 1;
}
}
if (isRoot && deg >= 2) isCut[u] = 1;
}
void work(){
for (int i = 1;i <= siz;i++) {
if (vis[i]) continue;
dfs(i,i,1);
}
}
};
4.2.3.2 割边
所有边双联通大于 EBCC。
4.3 网络流
4.3.1 网络最大流/网络最小割
4.3.1.1 Edmonds-Karp 算法
using i64 = long long;
constexpr i64 INF = 1e18;
struct EdmondsKarp {
int n;
struct Edge {
int to = 0,nxt = 0;
i64 f = 0,c = 0;
};
std::vector<int> head,fr;
std::vector<Edge> edge;
EdmondsKarp(int _n):n(_n),head(n+1),edge(2),fr(n+1){}
void addEdge(int u,int v,i64 f,i64 c){
edge.push_back({v,head[u],f,c});
head[u] = edge.size() - 1;
}
void connect(int u,int v,i64 w){
addEdge(u,v,w,w);
addEdge(v,u,0,w);
}
i64 work(int s,int t){
i64 ans = 0;
while (1) {
std::queue<int> que;
std::fill(fr.begin(),fr.end(),-1);
que.push(s);
fr[s] = 0;
while (!que.empty()){
int u = que.front();
que.pop();
for (int e = head[u];e;e = edge[e].nxt){
int v = edge[e].to;
i64 w = edge[e].f;
if (fr[v] != -1 || w == 0) continue;
fr[v] = e^1;
que.push(v);
}
}
if (fr[t] == -1) break;
i64 mn = INF;
for (int u = t;u != s;u = edge[fr[u]].to){
mn = std::min(mn,edge[fr[u] ^ 1].f);
}
for (int u = t;u != s;u = edge[fr[u]].to){
edge[fr[u]].f += mn;
edge[fr[u] ^ 1].f -= mn;
}
ans += mn;
}
return ans;
}
};
4.3.1.2 Dinic 算法
- 对于无边权版本(即容量大小均为
1 )的情况下,Dinic 算法总时间复杂度为O(m\cdot \min(m^\frac{1}{2},n^\frac{2}{3})) 。 - 对于二分图最大匹配问题(无权),Dinic 的时间复杂度为
O(n^\frac{1}{2}\cdot m)
using i64 = long long;
constexpr i64 INF = 1e18;
struct Dinic {
int n;
std::vector<int> dis,now,head;
struct Edge {
int to = 0,nxt = 0;
i64 f = 0,c = 0;
};
std::vector<Edge> edge;
Dinic(int _n):n(_n),dis(_n+1),now(n+1),head(n+1),edge(2) {}
void addEdge(int u,int v,i64 f,i64 c){
edge.push_back({v,head[u],f,c});
head[u] = edge.size() - 1;
}
void connect(int u,int v,i64 w){
addEdge(u,v,w,w);
addEdge(v,u,0,w);
}
bool level_graph(int s,int t){
std::queue<int> que;
std::fill(dis.begin(),dis.end(),-1);
dis[s] = 0,que.push(s);
now[s] = head[s];
while (!que.empty()) {
auto u = que.front();
que.pop();
for (int e = head[u];e;e = edge[e].nxt){
int v = edge[e].to;
i64 w = edge[e].f;
if (dis[v] != -1 || w == 0) continue;
dis[v] = dis[u] + 1;
now[v] = head[v];
que.push(v);
if (v == t) return 1;
}
}
return 0;
}
i64 blocking_flows(int u,i64 cap,const int& t){
if (u == t) return cap;
i64 sum = 0;
for (int e = now[u];e;e = edge[e].nxt){
int v = edge[e].to;
i64 w = edge[e].f;
if (!cap) break;
now[u] = e;
if (dis[v] != dis[u] + 1 || w <= 0) continue;
i64 k = blocking_flows(v,std::min(cap,w),t);
if (!k) dis[v] = -1;
edge[e].f -= k,edge[e^1].f += k;
sum += k,cap -= k;
}
return sum;
}
i64 work(int s,int t){
i64 sum = 0;
while (level_graph(s,t)){
sum += blocking_flows(s,INF,t);
}
return sum;
}
};
4.3.2 网络费用流
4.3.2.1 SSP 算法
基于 Edmonds Karp 算法 的 SSP 算法实现。
using i64 = long long;
using p64 = std::array<i64,2>;
constexpr i64 INF = 1e18;
struct SSP {
int n;
struct Edge {
int to = 0,nxt = 0;
i64 f = 0,c = 0,w = 0;
};
std::vector<int> head,fr;
std::vector<Edge> edge;
std::vector<i64> dis;
std::vector<bool> vis;
SSP(int _n):n(_n),head(n+1),edge(2),fr(n+1),dis(n+1),vis(n+1){}
void addEdge(int u,int v,i64 f,i64 c,i64 w){
edge.push_back({v,head[u],f,c,w});
head[u] = edge.size() - 1;
}
void connect(int u,int v,i64 c,i64 w){
addEdge(u,v,c,c,w);
addEdge(v,u,0,c,-w);
}
p64 work(int s,int t){
p64 ans = {0,0};
while (1) {
std::queue<int> que;
que.push(s);
std::fill(fr.begin(),fr.end(),0);
std::fill(vis.begin(),vis.end(),0);
std::fill(dis.begin(),dis.end(),INF);
dis[s] = 0,vis[s] = 1;
while (!que.empty()) {
int u = que.front();
que.pop();
vis[u] = 0;
for (int e = head[u];e;e = edge[e].nxt){
i64 f = edge[e].f,w = edge[e].w;
int v = edge[e].to;
if (f > 0 && dis[u] + w < dis[v]){
dis[v] = dis[u] + w;
fr[v] = e^1;
if (!vis[v]){
que.push(v);
vis[v] = 1;
}
}
}
}
if (dis[t] >= INF) break;
i64 mn = INF;
for (int u = t;u != s;u = edge[fr[u]].to){
mn = std::min(mn,edge[fr[u] ^ 1].f);
}
for (int u = t;u != s;u = edge[fr[u]].to){
edge[fr[u]].f += mn;
edge[fr[u] ^ 1].f -= mn;
}
ans[0] += mn;
ans[1] += dis[t] * mn;
}
return ans;
}
};
基于 Dinic 算法 + Dijkstra 势能优化的 SSP 算法实现
using i64 = long long;
using p64 = std::array<i64,2>;
constexpr i64 INF = 1e18;
struct MinCostFlow {
int n;
struct Edge {
int to = 0,nxt = 0;
i64 f = 0,c = 0,w = 0;
};
std::vector<int> head,now;
std::vector<Edge> edge;
std::vector<i64> dis,h;
std::vector<bool> vis;
MinCostFlow (int _n):n(_n),head(n+1),edge(2),now(n+1),dis(n+1),h(n+1),vis(n+1){}
void addEdge(int u,int v,i64 f,i64 c,i64 w){
edge.push_back({v,head[u],f,c,w});
head[u] = edge.size() - 1;
}
void connect(int u,int v,i64 c,i64 w){
addEdge(u,v,c,c,w);
addEdge(v,u,0,c,-w);
}
void SPFA(int s,int t){
std::fill(h.begin(),h.end(),INF);
std::fill(vis.begin(),vis.end(),0);
std::queue<int> que;
que.push(s);
h[s] = 0,vis[s] = 1;
while (!que.empty()){
int u = que.front();
que.pop();
vis[u] = 0;
for (int e = head[u];e;e = edge[e].nxt){
i64 f = edge[e].f,w = edge[e].w;
int v = edge[e].to;
if (f > 0 && h[u] + w < h[v]){
h[v] = h[u] + w;
if (!vis[v]) {
que.push(v);
vis[v] = 1;
}
}
}
}
}
bool dijkstra(int s,int t){
std::fill(dis.begin(),dis.end(),INF);
std::fill(vis.begin(),vis.end(),0);
std::priority_queue<p64> pq;
pq.push({0,s});
dis[s] = 0;
while (!pq.empty()){
auto [dist,u] = pq.top();
pq.pop();
if (vis[u]) continue;
vis[u] = 1;
for (int e = head[u];e;e = edge[e].nxt){
int v = edge[e].to;
i64 w = edge[e].w,f = edge[e].f;
if (f > 0 && dis[u] + w + h[u] - h[v] < dis[v]){
dis[v] = dis[u] + w + h[u] - h[v];
pq.push({-dis[v],v});
}
}
}
return vis[t];
}
i64 dfs(int u,const int& t,i64 flow,i64 &cost){
if (u == t) return flow;
i64 sum = 0;
vis[u] = 1;
for (int e = now[u];e;e = edge[e].nxt){
now[u] = e;
int v = edge[e].to;
i64 f = edge[e].f,w = edge[e].w;
if (f > 0 && !vis[v] && h[v] == h[u] + w) {
i64 f2 = dfs(v,t,std::min(f,flow),cost);
edge[e].f -= f2;
edge[e^1].f += f2;
sum += f2;
flow -= f2;
cost += f2 * w;
if (flow == 0) break;
}
}
vis[u] = 0;
return sum;
}
p64 work(int s,int t){
p64 ans = {0,0};
SPFA(s,t);
while (dijkstra(s,t)){
std::fill(vis.begin(),vis.end(),0);
for (int i = 0;i <= n;i++){
h[i] += dis[i];
now[i] = head[i];
}
ans[0] += dfs(s,t,INF,ans[1]);
}
return ans;
}
};
值得注意的是,这两种算法均无法完成带负环费用的最小费用最大网络流。
4.3.3 上下界网络流
4.3.3.1 上下界可行流/最大流/最小流
需要 Dinic 类。
struct BoundFlow {
Dinic G;
std::vector<i64> w,f;
int n,m = 0;
BoundFlow (int _n) : n(_n),G(_n + 2),w(_n+1),f(1) {}
void connect(int u,int v,i64 l,i64 r) {
m++;
G.connect(u,v,r-l);
f.push_back(l);
w[u] -= l;
w[v] += l;
}
bool getFlow(int s = 0,int t = 0) {
int S = n+1,T = n+2;
for (int i = 1;i <= n;i++){
if (w[i] > 0) {
G.connect(S,i,abs(w[i]));
} else if (w[i] < 0) {
G.connect(i,T,abs(w[i]));
}
}
int M = G.edge.size();
if (s && t) G.connect(t,s,INF);
G.work(S,T);
for (int i = 2;i <= m*2;i += 2){
f[i/2] += G.edge[i].c - G.edge[i].f;
}
for (int i = m*2+2;i < M;i += 2){
if (G.edge[i].f != 0 || G.edge[i^1].f != G.edge[i^1].c) return 0;
}
return 1;
}
i64 maxflow(int s,int t){
if (!getFlow(s,t)) return -1;
int rid = G.head[t];
i64 sum = G.edge[rid^1].f;
G.edge[rid].f = G.edge[rid^1].f = 0;
G.edge[rid].c = G.edge[rid^1].c = 0;
sum += G.work(s,t);
return sum;
}
i64 minflow(int s,int t){
if (!getFlow(s,t)) return -1;
int rid = G.head[t];
i64 sum = G.edge[rid^1].f;
G.edge[rid].f = G.edge[rid^1].f = 0;
G.edge[rid].c = G.edge[rid^1].c = 0;
sum -= G.work(t,s);
return sum;
}
};
4.3.4 最小割树
需要网络最大流算法。
时间复杂度为
template<typename MinCut>
struct GomoryHuTree {
int n;
MinCut Flow;
std::vector<std::vector<std::array<long long,2>>> G;
std::vector<int> vdx;
GomoryHuTree(int _n):n(_n),Flow(n),G(n+1),vdx(n+1){
iota(vdx.begin(),vdx.end(),0);
}
void connect(int u,int v,i64 c){
Flow.connect(u,v,c);
}
void build(int l,int r){
if (l >= r) return;
for (int e = 2;e < Flow.edge.size();e += 2){
Flow.edge[e].f = Flow.edge[e].c;
Flow.edge[e^1].f = Flow.edge[e^1].c;
}
Flow.work(vdx[l],vdx[r]);
i64 cut = 0;
for (int e = Flow.head[vdx[l]];e;e = Flow.edge[e].nxt){
cut += Flow.edge[e].c - Flow.edge[e].f;
}
G[vdx[r]].push_back({vdx[l],cut});
G[vdx[l]].push_back({vdx[r],cut});
vector<int> v1,v2;
for (int i = l;i <= r;i++){
int u = vdx[i];
if (Flow.dis[u] != -1) v1.push_back(u);
else v2.push_back(u);
}
const int mid = l + v1.size();
for (int i = l;i < mid;i++){
vdx[i] = v1[i - l];
}
for (int i = mid;i <= r;i++){
vdx[i] = v2[i - mid];
}
build(l,mid-1);
build(mid,r);
}
};
4.4 Matrix-Tree 定理
4.4.1 普通生成树计数
namespace MatrixTree {
using MInt = Z;
using std::vector;
using std::array;
MInt undirected(int n,vector<array<int,3>> E){
vector K(n,vector(n,MInt(0)));
for (auto [x,y,w] : E){
K[x][y] -= w;
K[y][x] -= w;
K[x][x] += w;
K[y][y] += w;
}
for (int i = 0;i < n;i++){
K[i].pop_back();
}
K.pop_back();
return Guass::det(K);
}
// 该版本为外向树版本,如果为内向树则需要边权取反
MInt directed(int n,int rt,vector<array<int,3>> E){
vector K(n,vector(n,MInt(0)));
for (auto [x,y,w] : E){
K[x][y] -= w;
K[y][y] += w;
}
for (int i = 0;i < n;i++){
K[i].erase(K[i].begin()+rt,K[i].begin()+rt+1);
}
K.erase(K.begin()+rt,K.begin()+rt+1);
return Guass::det(K);
}
};
4.4.2 BEST 定理
若有向强连通图中存在欧拉回路,那么它的欧拉回路个数为
namespace MatrixTree {
MInt BEST(int n,vector<array<int,3>> E){
if (E.size() == 0 || n == 1) return 1;
vector<int> in(n),out(n);
for (auto [x,y,w] : E){
in[x] += w;
out[y] += w;
}
for (int i = 0;i < n;i++) {
if (in[i] != out[i]) return 0;
}
MInt prod = 1;
int m = E.size();
vector<MInt> fact(m+1,1);
for (int i = 1;i <= m;i++) fact[i] = fact[i-1] * i;
for (int i = 0;i < n;i++) prod *= fact[in[i]-1];
return directed(n,0,E) * prod;
}
};
5.计算几何
5.1 计算几何基础
5.1.1 点与向量(二维)
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 线
5.1.2.1 三点共线
bool Col(const Point<T> &a,const Point<T> &b,const Point<T> &c){//三点共线
return Point<T>::cross( b - a , c - a ) == 0 ;
}
template<typename T = double>
bool onSeg(const Point<T>& a, const Point<T>& b, const Point<T>& p) {//点在线段上
return Point<T>::cross(b - a, p - a) == 0 &&
std::min(a.x,b.x) <= p.x && p.x <= std::max(a.x,b.x) &&
std::min(a.y,b.y) <= p.y && p.y <= std::max(a.y,b.y);
}
5.1.3 多边形
5.1.3.1 点与多边形的关系
template<typename T = double>
bool inPolygon(const std::vector<Point<T>>& a,Point<T>& p) {//点是否在简单多边形内
const int& n = a.size();
bool ans = 0;
for (int i = 0, j = n - 1; i < n; j = i++) {
if (onSeg(a[i],a[j],p)) return true;
if ((a[i].y > p.y) != (a[j].y > p.y)) {
Point<T> del1 = a[j] - a[i];
Point<T> del2 = p - a[i];
T l = del1.y * del2.x;
T r = del1.x * del2.y;
if ((del1.y > 0 && l < r) || (del1.y < 0 && l > r)) {
ans = !ans;
}
}
}
return ans;
}
5.1.3 三角函数与极角
namespace Trigonometric{ // 三角函数
using f64 = long double;
const f64 PI = std::acos(-1.0);
f64 toRadian(f64 angle){ // 角度制转弧度制
return PI*angle/180;
}
f64 Polar(f64 x,f64 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;
f64 ATAN = std::atan(y/x);
if (ATAN < 0) ATAN += PI;
return (y > 0 ? 0 : PI) + ATAN;
}
f64 getAngle(f64 rad1,f64 rad2){ // x1->x2 求逆时针夹角弧度
return rad2 - rad1 + (rad1 > rad2 ? 2*PI : 0);
}
f64 arcLength(f64 radius,f64 angle = 2*PI){ // 求指定角度(弧度制)和半径的弧长
return angle*radius;
}
f64 sectorArea(f64 radius,f64 angle = 2*PI){ // 扇形面积(弧度制)
return arcLength(radius,angle)*radius/2;
}
}
using namespace Trigonometric;
5.2 二维计算几何
5.2.1 二维凸包
需要使用 Point。
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
#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 取模类(静态模数)
template <int MOD>
struct ModInt{
long long val = 0;
ModInt(long long x = 0):val(norm(x)){}
ModInt(const std::string& s){
for (const int& ch : s){
val = val * 10 + ch - '0';
val = norm(val);
}
}
long long operator()() const { return val; }
constexpr ModInt operator-() const {
return ModInt(MOD - val);
}
constexpr ModInt operator~() const {
assert(val != 0);
return Pow(val,MOD-2);
}
constexpr ModInt& operator+=(const ModInt& x){
return val += x(),val = norm(val),*this;
}
constexpr ModInt& operator-=(const ModInt& x){
return val -= x(),val = norm(val),*this;
}
constexpr ModInt& operator*=(const ModInt& x){
return val *= x(),val = norm(val),*this;
}
constexpr ModInt& operator/=(const ModInt& x){
return val *= (~x)(),val = norm(val),*this;
}
constexpr ModInt& operator^=(long long y){
return val = Pow(*this,y)(),*this;
}
constexpr bool operator==(const ModInt& x) const {
return val == x();
}
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 friend ModInt operator+(ModInt x,const ModInt& y){
return x += y;
}
constexpr friend ModInt operator-(ModInt x,const ModInt& y){
return x -= y;
}
constexpr friend ModInt operator*(ModInt x,const ModInt& y){
return x *= y;
}
constexpr friend ModInt operator/(ModInt x,const ModInt& y){
return x /= y;
}
constexpr friend ModInt operator^(ModInt x, long long y){
return x ^= y;
}
constexpr friend std::ostream& operator<<(std::ostream& os,const 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(const 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 取模类(全局模数)
static int MOD = 998244353;
struct DynModInt{
long long val = 0;
DynModInt(long long x = 0):val(norm(x)){}
DynModInt(const DynModInt& x):val(x.val){}
DynModInt(const std::string& s){
for (const int& ch : s){
val = val * 10 + ch - '0';
val = norm(val);
}
}
constexpr static void setMod(long long p){
MOD = p;
}
long long operator()() const { return val; }
constexpr DynModInt operator-() const {
return DynModInt(MOD - val);
}
constexpr DynModInt operator~() const {
assert(val != 0);
return Pow(val,MOD-2);
}
constexpr DynModInt& operator+=(const DynModInt& x){
return val += x(),val = norm(val),*this;
}
constexpr DynModInt& operator-=(const DynModInt& x){
return val -= x(),val = norm(val),*this;
}
constexpr DynModInt& operator*=(const DynModInt& x){
return val *= x(),val = norm(val),*this;
}
constexpr DynModInt& operator/=(const DynModInt& x){
return val *= (~x)(),val = norm(val),*this;
}
constexpr DynModInt& operator^=(long long y){
return val = Pow(*this,y)(),*this;
}
constexpr bool operator==(const DynModInt& x) const {
return val == x();
}
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,const DynModInt& y){
return x += y;
}
constexpr friend DynModInt operator-(DynModInt x,const DynModInt& y){
return x -= y;
}
constexpr friend DynModInt operator*(DynModInt x,const DynModInt& y){
return x *= y;
}
constexpr friend DynModInt operator/(DynModInt x,const DynModInt& y){
return x /= y;
}
constexpr friend DynModInt operator^(DynModInt x,const long long& y){
return x ^= y;
}
constexpr friend std::ostream& operator<<(std::ostream& os,const 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 < 0 ? (x % MOD + MOD) % MOD : x % 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 常数更快
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>;
6.3 时空优化
6.3.1 读入优化
namespace QuickStream {
template<typename T>
T read() {
T x;
std::cin >> x;
return x;
}
template<typename T>
inline T read_int() {
T x = 0;
bool f = 0;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = 1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + (ch - '0');
ch = getchar();
}
return f ? -x : x;
}
template<>
int read<int>() {
return read_int<int>();
}
template<>
long long read<long long>() {
return read_int<long long>();
}
template<>
std::string read<std::string>() {
std::string s;
char ch = getchar();
while (ch != EOF && (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t')) {
ch = getchar();
}
while (ch != EOF && ch != ' ' && ch != '\n' && ch != '\r' && ch != '\t') {
s += ch;
ch = getchar();
}
return s;
}
}
using QuickStream::read;
6.3.2 指令集
#pragma GCC optimize("O3,unroll-loops,inline")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")