快读
template<class T=int>
inline T read() {
T num = 0;
int neg = 1;
char c = getchar_unlocked();
while (!isdigit(c) and c != '-') {
c = getchar_unlocked();
}
if (c == '-') neg = -1;
else num = c-'0';
c = getchar_unlocked();
while (isdigit(c)) {
num = (num<<1)+(num<<3)+(c^48);
c = getchar_unlocked();
}
return num*neg;
}基础算法
离散化
// Coodinate Compression
template<typename T=int>
struct CC {
bool initialized;
vector<T> xs;
CC(): initialized(false) {}
void add(T x) { xs.push_back(x);}
void init() {
sort(xs.begin(), xs.end());
xs.erase(unique(xs.begin(),xs.end()),xs.end());
initialized = true;
}
int operator()(T x) {
if (!initialized) init();
return upper_bound(xs.begin(), xs.end(), x) - xs.begin() - 1;
}
T operator[](int i) {
if (!initialized) init();
return xs[i];
}
int size() {
if (!initialized) init();
return xs.size();
}
};test:
数学
取模
//const int mod = 998244353;
//const int mod = 1000000007;
struct mint {
ll x;
mint(ll x=0):x((x%mod+mod)%mod) {}
mint operator-() const {
return mint(-x);
}
mint& operator+=(const mint a) {
if ((x += a.x) >= mod) x -= mod;
return *this;
}
mint& operator-=(const mint a) {
if ((x += mod-a.x) >= mod) x -= mod;
return *this;
}
mint& operator*=(const mint a) {
(x *= a.x) %= mod;
return *this;
}
mint operator+(const mint a) const {
return mint(*this) += a;
}
mint operator-(const mint a) const {
return mint(*this) -= a;
}
mint operator*(const mint a) const {
return mint(*this) *= a;
}
mint pow(ll t) const {
if (!t) return 1;
mint a = pow(t>>1);
a *= a;
if (t&1) a *= *this;
return a;
}
// for prime mod
mint inv() const {
return pow(mod-2);
}
mint& operator/=(const mint a) {
return *this *= a.inv();
}
mint operator/(const mint a) const {
return mint(*this) /= a;
}
};
istream& operator>>(istream& is, mint& a) {
return is >> a.x;
}
ostream& operator<<(ostream& os, const mint& a) {
return os << a.x;
}有理数
struct Rat {
ll a, b;
Rat(ll _a=0, ll _b=1): a(_a), b(_b) {
if (b == 0) { a = 1; b = 0; return;}
if (b < 0) b = -b, a = -a;
ll g = gcd(abs(a),b);
a /= g; b /= g;
}
bool operator<(const Rat& x) const {
return a*x.b < x.a*b;
}
};struct frac {
ll a, b;
frac(ll _a=0, ll _b=1): a(_a), b(_b) {
if (b == 0) { a = 1; return; }
if (b < 0) a = -a, b = -b;
ll g = gcd(a, b);
a /= g; b /= g;
}
bool operator<(const frac& x) const {
return a*x.b < x.a*b;
}
bool operator==(const frac& x) const {
return a == x.a and b == x.b;
}
};求组合数模素数
Pascal三角形
comb[0][0] = 1;
rep(i, n)rep(j, i+1) {
comb[i+1][j] += comb[i][j];
comb[i+1][j+1] += comb[i][j];
}// combination mod prime
struct combination {
vector<mint> fact, ifact;
combination(int n):fact(n+1),ifact(n+1) {
fact[0] = 1;
for (int i = 1; i <= n; ++i) fact[i] = fact[i-1]*i;
ifact[n] = fact[n].inv();
for (int i = n; i >= 1; --i) ifact[i-1] = ifact[i]*i;
}
mint operator()(int n, int k) {
if (k < 0 || k > n) return 0;
return fact[n]*ifact[k]*ifact[n-k];
}
} comb(5005);test:
struct modinv {
int n; vector<mint> d;
modinv(): n(2), d({0,1}) {}
mint operator()(int i) {
while (n <= i) d.push_back(-d[mint::mod()%n]*(mint::mod()/n)), ++n;
return d[i];
}
mint operator[](int i) const { return d[i];}
} invs;
struct modfact {
int n; vector<mint> d;
modfact(): n(2), d({1,1}) {}
mint operator()(int i) {
while (n <= i) d.push_back(d.back()*n), ++n;
return d[i];
}
mint operator[](int i) const { return d[i];}
} facts;
struct modfactinv {
int n; vector<mint> d;
modfactinv(): n(2), d({1,1}) {}
mint operator()(int i) {
while (n <= i) d.push_back(d.back()*invs(n)), ++n;
return d[i];
}
mint operator[](int i) const { return d[i];}
} ifacts;
mint comb(int n, int k) {
if (n < k || k < 0) return 0;
return facts(n)*ifacts(k)*ifacts(n-k);
}卡特兰数
mint catalan(int n) {
return comb(2*n, n)/(n+1);
}Lucas定理
mint lucas(ll n, ll k) {
if (n == 0 && k == 0) return 1;
mint res = comb(n%mod, k%mod);
return res*lucas(n/mod, k/mod);
}exgcd
// ai+bj=g
ll extgcd(ll a, ll b, ll& i, ll& j) {
if (b == 0) { i = 1; j = 0; return a; }
ll p = a/b, g = extgcd(b, a-b*p, j, i);
j -= p*i;
return g;
}test:
类欧
// arithmetic progression sum
ll asum(ll s, ll d, ll n) {
return s*n + (n-1)*n/2*d;
}
// sum{(a+d*i)/e} [i=0~n-1]
ll gaussSum(ll a, ll d, ll n, ll e) {
if (!n) return 0;
ll res = asum(a/e,d/e,n);
a %= e; d %= e;
if (!d) return res;
ll z = a+d*(n-1);
return res + gaussSum(z%e+d,e,z/e,d);
}素数测试
bool isPrime(ll n) {
if (n < 2) return false;
if (n == 2) return true;
if (n%2 == 0) return false;
for (ll i = 3; i*i <= n; i += 2) {
if (n%i == 0) return false;
}
return true;
}线性筛
// linear sieve
vector<bool> isp;
vector<int> ps, pf;
void sieve(int mx) {
isp.resize(mx+1);
pf.resize(mx+1);
rep(i, mx+1) pf[i] = i;
for (int i = 2; i <= mx; ++i) {
if (pf[i] == i) isp[i] = true, ps.push_back(i);
rep(j, ps.size()) {
int x = ps[j]*i;
if (x > mx) break;
pf[x] = ps[j];
if (i%ps[j] == 0) break;
}
}
}素因数分解
vector<P> factorize(ll n) {
vector<P> res;
for (ll i = 2; i*i <= n; ++i) {
if (n%i != 0) continue;
res.emplace_back(i, 0);
while (n%i == 0) {
n /= i;
res.back().second++;
}
}
if (n != 1) res.emplace_back(n, 1);
return res;
}欧拉函数
ll euler_phi(ll n) {
auto fs = factorize(n);
ll res = n;
for (auto [p, _] : fs) res -= res/p;
return res;
}线性筛欧拉函数
// totient table
vector<int> ps, pf, phi;
void sieve(int mx) {
pf.resize(mx+1);
phi.resize(mx+1);
phi[1] = 1;
rep(i, mx+1) pf[i] = i;
for (int i = 2; i <= mx; ++i) {
if (pf[i] == i) {
ps.push_back(i);
phi[i] = i-1;
}
rep(j, ps.size()) {
int x = ps[j]*i;
if (x > mx) break;
pf[x] = ps[j];
if (i%ps[j] == 0) {
phi[x] = phi[i]*ps[j];
break;
}
phi[x] = phi[i]*(ps[j]-1);
}
}
}线性筛莫比乌斯函数
vector<bool> isp;
vector<int> ps, pf, mu;
void sieve(int mx) {
isp.resize(mx+1);
pf.resize(mx+1);
mu.resize(mx+1);
mu[1] = 1;
rep(i, mx+1) pf[i] = i;
for (int i = 2; i <= mx; ++i) {
if (pf[i] == i) isp[i] = true, ps.push_back(i), mu[i] = -1;
rep(j, ps.size()) {
int x = ps[j]*i;
if (x > mx) break;
pf[x] = ps[j];
if (i%ps[j] == 0) {
mu[i*ps[j]] = 0;
break;
}
mu[i*ps[j]] = -mu[i];
}
}
}埃氏筛完整版
struct Sieve {
int n;
vector<int> f, primes;
Sieve(int n=1): n(n), f(n+1) {
f[0] = f[1] = -1;
for (ll i = 2; i <= n; ++i) {
if (f[i]) continue;
primes.push_back(i);
f[i] = i;
for (ll j = i*i; j <= n; j += i) {
if (!f[j]) f[j] = i;
}
}
}
bool isPrime(int x) { return f[x] == x; }
vector<int> factorList(int x) {
vector<int> res;
while (x != 1) {
res.push_back(f[x]);
x /= f[x];
}
return res;
}
vector<P> factor(int x) {
vector<int> fl = factorList(x);
if (fl.size() == 0) return {};
vector<P> res(1, P(fl[0], 0));
for (int p : fl) {
if (res.back().first == p) {
res.back().second++;
}
else {
res.emplace_back(p, 1);
}
}
return res;
}
vector<ll> factorList(ll x) {
vector<ll> res;
for (int p : primes) {
while (x%p == 0) {
res.push_back(p);
x /= p;
}
}
if (x != 1) res.push_back(x);
return res;
}
vector<pair<ll, int>> factor(ll x) {
vector<ll> fl = factorList(x);
if (fl.size() == 0) return {};
vector<pair<ll, int>> res(1, P(fl[0], 0));
for (ll p : fl) {
if (res.back().first == p) {
res.back().second++;
}
else {
res.emplace_back(p, 1);
}
}
return res;
}
};test:
矩阵快速幂
template<typename T>
struct Matrix {
int h, w;
vector<vector<T>> d;
Matrix() {}
Matrix(int h, int w, T val=0): h(h), w(w), d(h, vector<T>(w,val)) {}
Matrix& unit() {
assert(h == w);
rep(i,h) d[i][i] = 1;
return *this;
}
const vector<T>& operator[](int i) const { return d[i];}
vector<T>& operator[](int i) { return d[i];}
Matrix operator*(const Matrix& a) const {
assert(w == a.h);
Matrix r(h, a.w);
rep(i,h)rep(k,w)rep(j,a.w) {
r[i][j] += d[i][k]*a[k][j];
}
return r;
}
Matrix pow(long long t) const {
assert(h == w);
if (!t) return Matrix(h,h).unit();
if (t == 1) return *this;
Matrix r = pow(t>>1);
r = r*r;
if (t&1) r = r*(*this);
return r;
}
};// 轻量级矩阵快速幂
using A = array<mint, 2>;
using D = array<A, 2>;
const D I = {A{1, 0}, A{0, 1}};
D operator*(const D& a, const D& b) {
D c = {A{0, 0}, A{0, 0}};
rep(i, 2)rep(j, 2)rep(k, 2) {
c[i][k] += a[i][j]*b[j][k];
}
return c;
}
D pow(D a, ll e) {
D x = I;
while (e) {
if (e&1) x = x*a;
a = a*a;
e >>= 1;
}
return x;
}test:
矩阵树定理
template<typename T>
struct Matrix {
int h, w;
vector<vector<T>> d;
Matrix() {}
Matrix(int h, int w, T val=0): h(h), w(w), d(h, vector<T>(w,val)) {}
Matrix& unit() {
assert(h == w);
rep(i,h) d[i][i] = 1;
return *this;
}
const vector<T>& operator[](int i) const { return d[i];}
vector<T>& operator[](int i) { return d[i];}
Matrix operator*(const Matrix& a) const {
assert(w == a.h);
Matrix r(h, a.w);
rep(i,h)rep(k,w)rep(j,a.w) {
r[i][j] += d[i][k]*a[k][j];
}
return r;
}
Matrix pow(long long t) const {
assert(h == w);
if (!t) return Matrix(h,h).unit();
if (t == 1) return *this;
Matrix r = pow(t>>1);
r = r*r;
if (t&1) r = r*(*this);
return r;
}
T det() {
assert(h == w);
T res = 1;
rep(k, h) {
for (int i = k; i < h; ++i) {
if (d[i][k] == 0) continue;
if (i != k) {
swap(d[i], d[k]);
res = -res;
}
}
if (d[k][k] == 0) return 0;
res *= d[k][k];
T inv = T(1)/d[k][k];
rep(j, h) d[k][j] *= inv;
for (int i = k+1; i < h; ++i) {
T c = d[i][k];
for (int j = k; j < h; ++j) d[i][j] -= d[k][j]*c;
}
}
return res;
}
void erase() {
h--; w--;
d.erase(d.begin());
for (auto& v : d) v.erase(v.begin());
}
};test:
Lagrange插值
的情况,可以做到
struct Interpolation {
int n;
vector<mint> a;
Interpolation() {}
Interpolation(const vector<mint>& p) {
n = p.size();
a.resize(n);
vector<mint> invf(n, 1);
mint f = 1;
for (int i = 1; i < n; ++i) f *= i;
invf[n-1] = mint(1)/f;
for (int i = n-1; i >= 1; --i) invf[i-1] = invf[i]*i;
for (int i = 0; i < n; ++i) {
mint b = invf[i] * invf[n-1-i];
a[i] = p[i] * ((n-1-i)%2 == 1 ? -b : b);
}
}
mint operator()(mint x) const {
vector<mint> r(n, 1);
for (int i = n-1; i >= 1; --i) r[i-1] = r[i]*(x-i);
mint l = 1, res;
for (int i = 0; i < n; ++i) {
res += a[i]*l*r[i];
l *= x-i;
}
return res;
}
};一般情况下求 ,只能做到
struct Interpolation {
vector<mint> x, y;
Interpolation() {}
Interpolation(const vector<mint> x, const vector<mint> y): x(x), y(y) {}
mint operator()(mint k) {
int n = x.size();
mint res;
rep(i, n) {
mint a = 1, b = 1;
rep(j, n) if (j != i) {
a *= mint(k)-x[j];
b *= x[i]-x[j];
}
res += y[i]*a/b;
}
return res;
}
};线性基
const int D = 50;
struct BitVector {
vector<ll> d;
BitVector(): d(D) {}
void add(ll x) {
x = getmin(x);
for (int i = D-1; i >= 0; --i) {
if (x>>i&1) {
rep(j, D) if (d[j]>>i&1) d[j] ^= x;
d[i] = x;
return;
}
}
}
ll getmin(ll x) {
for (int i = D-1; i >= 0; --i) {
if (x>>i&1) x ^= d[i];
}
return x;
}
ll calc() {
ll res = 0;
rep(i, D) if (d[i]) res ^= d[i];
return res;
}
};test:
斜率优化
// Convex Hull Trick
struct CHT {
struct Linear {
ll a, b;
Linear(ll a=0, ll b=0): a(a), b(b) {}
ll operator()(ll x) const { return a*x+b; }
};
deque<Linear> ls;
void add(ll a, ll b) { // decreasing order of a
Linear l(a, b);
assert(ls.size() == 0 or ls.back().a >= l.a);
while (ls.size() >= 2) {
const Linear& l1 = ls[ls.size()-2];
const Linear& l2 = ls.back();
if ((l.b-l2.b)*(l1.a-l2.a) > (l2.a-l.a)*(l2.b-l1.b)) break;
ls.pop_back();
}
ls.push_back(l);
}
ll operator()(ll x) {
while (ls.size() >= 2) {
ll a = ls[0](x);
ll b = ls[1](x);
if (a < b) break; // get min
ls.pop_front();
}
return ls[0](x);
}
};test:
数据结构
单调队列
struct SlideMin {
deque<P> q;
SlideMin() {}
void push(int i, int x) {
while (q.size() and q.back().second >= x) {
q.pop_back();
}
q.emplace_back(i, x);
}
int get(int l) { // l <= i
while (q.size() and q.front().first < l) {
q.pop_front();
}
assert(q.size());
return q.front().second;
}
};
struct SlideMax {
deque<P> q;
SlideMax() {}
void push(int i, int x) {
while (q.size() and q.back().second <= x) {
q.pop_back();
}
q.emplace_back(i, x);
}
int get(int l) { // l <= i
while (q.size() and q.front().first < l) {
q.pop_front();
}
assert(q.size());
return q.front().second;
}
};test:
ST 表
template<class D, class OP>
struct SparseTable {
D e;
OP op;
vector<vector<D>> data;
SparseTable(vector<D> v = vector<D>(), D _e = D(), OP _op = OP()): e(_e), op(_op) {
int n = v.size();
if (n == 0) return;
int lg = 31 - __builtin_clz(unsigned(n)) + 1;
data = vector<vector<D>>(lg);
data[0] = v;
int l = 1;
for (int s = 1; s < lg; ++s) {
data[s] = vector<D>(n);
rep(i, n-l) {
data[s][i] = op(data[s-1][i], data[s-1][i+l]);
}
l <<= 1;
}
}
D query(int l, int r) const {
assert(l <= r);
if (l == r) return e;
int u = 31 - __builtin_clz(unsigned(r-l));
return op(data[u][l], data[u][r-(1<<u)]);
}
};
template<class D, class OP>
SparseTable<D, OP> get_sparse_table(vector<D> v, D e, OP op) {
return SparseTable<D, OP>(v, e, op);
}test:
并查集
C++ 版本
struct UnionFind {
vector<int> d;
UnionFind(int n = 0): d(n, -1) {}
int find(int x) {
if (d[x] < 0) return x;
return d[x] = find(d[x]);
}
bool unite(int x, int y) {
x = find(x); y = find(y);
if (x == y) return false;
if (d[x] > d[y]) swap(x, y);
d[x] += d[y];
d[y] = x;
return true;
}
bool same(int x, int y) {
return find(x) == find(y);
}
int size(int x) {
return -d[find(x)];
}
};Python 版本
import sys
input = lambda: sys.stdin.readline().rstrip()
class UnionFind():
def __init__(self, n):
self.n = n
self.root = [-1]*(n+1)
self.rank = [0]*(n+1)
def find(self, x):
if self.root[x] < 0:
return x
self.root[x] = self.find(self.root[x])
return self.root[x]
def merge(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return False
if self.rank[x] > self.rank[y]:
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
return True
def same(self, x, y):
return self.find(x) == self.find(y)
def size(self, x):
return -self.root[self.find(x)]
n, m = map(int, input().split())
uf = UnionFind(n)
for _ in range(m):
s = input().split()
type = s[0]
a, b = int(s[1]), int(s[2])
a -= 1
b -= 1
if type == 'M':
uf.merge(a, b)
else:
if uf.same(a, b):
print('Yes')
else:
print('No')
带权并查集
struct WeightedUnionFind {
vector<int> p;
vector<ll> dif;
WeightedUnionFind(int n): p(n, -1), dif(n) {}
int root(int a) {
if (p[a] < 0) return a;
int b = p[a];
p[a] = root(b);
dif[a] += dif[b];
return p[a];
}
bool merge(int a, int b, ll w) { // b = a+w
int ra = root(a); int rb = root(b);
w = w+dif[b]-dif[a];
swap(a, ra); swap(b, rb);
if (a == b) return w == 0;
if (p[b] > p[a]) swap(a, b), w = -w;
p[b] += p[a];
p[a] = b; dif[a] = w;
return true;
}
};test:
可撤销并查集
struct UnionFind {
vector<int> d;
vector<P> hist;
vector<int> snap;
UnionFind(int n = 0): d(n, -1) {}
int find(int x) {
if (d[x] < 0) return x;
return find(d[x]);
}
bool unite(int x, int y) {
x = find(x); y = find(y);
if (x == y) return false;
if (d[x] > d[y]) swap(x, y);
hist.emplace_back(x, d[x]); d[x] += d[y];
hist.emplace_back(y, d[y]); d[y] = x;
return true;
}
bool same(int x, int y) {
return find(x) == find(y);
}
int size(int x) {
return -d[find(x)];
}
void snapshot() {
snap.push_back(hist.size());
}
void rollback() {
while (hist.size() > snap.back()) {
auto [i, x] = hist.back(); hist.pop_back();
d[i] = x;
}
snap.pop_back();
}
};test:
普通线段树
namespace atcoder {
namespace internal {
int ceil_pow2(int n) {
int x = 0;
while ((1U << x) < (unsigned int)(n)) x++;
return x;
}
constexpr int bsf_constexpr(unsigned int n) {
int x = 0;
while (!(n & (1 << x))) x++;
return x;
}
int bsf(unsigned int n) {
#ifdef _MSC_VER
unsigned long index;
_BitScanForward(&index, n);
return index;
#else
return __builtin_ctz(n);
#endif
}
} // namespace internal
} // namespace atcoder
namespace atcoder {
template <class S, S (*op)(S, S), S (*e)()> struct segtree {
public:
segtree() : segtree(0) {}
explicit segtree(int n) : segtree(std::vector<S>(n, e())) {}
explicit segtree(const std::vector<S>& v) : _n(int(v.size())) {
log = internal::ceil_pow2(_n);
size = 1 << log;
d = std::vector<S>(2 * size, e());
for (int i = 0; i < _n; i++) d[size + i] = v[i];
for (int i = size - 1; i >= 1; i--) {
update(i);
}
}
void set(int p, S x) {
assert(0 <= p && p < _n);
p += size;
d[p] = x;
for (int i = 1; i <= log; i++) update(p >> i);
}
S get(int p) const {
assert(0 <= p && p < _n);
return d[p + size];
}
S prod(int l, int r) const {
assert(0 <= l && l <= r && r <= _n);
S sml = e(), smr = e();
l += size;
r += size;
while (l < r) {
if (l & 1) sml = op(sml, d[l++]);
if (r & 1) smr = op(d[--r], smr);
l >>= 1;
r >>= 1;
}
return op(sml, smr);
}
S all_prod() const { return d[1]; }
template <bool (*f)(S)> int max_right(int l) const {
return max_right(l, [](S x) { return f(x); });
}
template <class F> int max_right(int l, F f) const {
assert(0 <= l && l <= _n);
assert(f(e()));
if (l == _n) return _n;
l += size;
S sm = e();
do {
while (l % 2 == 0) l >>= 1;
if (!f(op(sm, d[l]))) {
while (l < size) {
l = (2 * l);
if (f(op(sm, d[l]))) {
sm = op(sm, d[l]);
l++;
}
}
return l - size;
}
sm = op(sm, d[l]);
l++;
} while ((l & -l) != l);
return _n;
}
template <bool (*f)(S)> int min_left(int r) const {
return min_left(r, [](S x) { return f(x); });
}
template <class F> int min_left(int r, F f) const {
assert(0 <= r && r <= _n);
assert(f(e()));
if (r == 0) return 0;
r += size;
S sm = e();
do {
r--;
while (r > 1 && (r % 2)) r >>= 1;
if (!f(op(d[r], sm))) {
while (r < size) {
r = (2 * r + 1);
if (f(op(d[r], sm))) {
sm = op(d[r], sm);
r--;
}
}
return r + 1 - size;
}
sm = op(d[r], sm);
} while ((r & -r) != r);
return 0;
}
private:
int _n, size, log;
std::vector<S> d;
void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
};
} // namespace atcoder
using namespace atcoder;延迟线段树
template <class S, S (*op)(S, S), S (*e)(), class F, S (*mapping)(F, S), F (*composition)(F, F), F (*id)()>
struct lazy_segtree {
int n, size, log;
vector<S> d;
vector<F> lz;
void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
void all_apply(int k, F f) {
d[k] = mapping(f, d[k]);
if (k < size) lz[k] = composition(f, lz[k]);
}
void push(int k) { all_apply(2 * k, lz[k]); all_apply(2 * k + 1, lz[k]); lz[k] = id(); }
lazy_segtree(int n): lazy_segtree(vector<S>(n, e())) {}
lazy_segtree(const vector<S>& v) : n((int)v.size()) {
log = 0; while ((1 << log) < n) log++;
size = 1 << log;
d.assign(2 * size, e());
lz.assign(size, id());
for (int i = 0; i < n; i++) d[size + i] = v[i];
for (int i = size - 1; i >= 1; i--) update(i);
}
void set(int p, S x) {
assert(0 <= p and p < n);
p += size;
for (int i = log; i; --i) push(p>>i);
d[p] = x;
for (int i = 1; i <= log; ++i) update(p>>i);
}
void apply(int l, int r, F f) {
if (l >= r) return;
l += size; r += size;
for (int i = log; i >= 1; i--) {
if (((l >> i) << i) != l) push(l >> i);
if (((r >> i) << i) != r) push((r - 1) >> i);
}
{
int l2 = l, r2 = r;
while (l < r) {
if (l & 1) all_apply(l++, f);
if (r & 1) all_apply(--r, f);
l >>= 1; r >>= 1;
}
l = l2; r = r2;
}
for (int i = 1; i <= log; i++) {
if (((l >> i) << i) != l) update(l >> i);
if (((r >> i) << i) != r) update((r - 1) >> i);
}
}
S get(int p) {
p += size;
for (int i = log; i >= 1; --i) push(p>>i);
return d[p];
}
S prod(int l, int r) {
if (l >= r) return e();
l += size; r += size;
for (int i = log; i >= 1; i--) {
if (((l >> i) << i) != l) push(l >> i);
if (((r >> i) << i) != r) push((r - 1) >> i);
}
S sml = e(), smr = e();
while (l < r) {
if (l & 1) sml = op(sml, d[l++]);
if (r & 1) smr = op(d[--r], smr);
l >>= 1; r >>= 1;
}
return op(sml, smr);
}
S all_prod() { return d[1]; }
};树状数组
template<typename T>
struct BIT {
int n;
vector<T> d;
BIT(int n=0):n(n),d(n+1) {}
void add(int i, T x=1) {
for (i++; i <= n; i += i&-i) {
d[i] += x;
}
}
T sum(int i) {
T x = 0;
for (i++; i; i -= i&-i) {
x += d[i];
}
return x;
}
T sum(int l, int r) {
return sum(r-1) - sum(l-1);
}
int kth(ll k) {
int b = 1, i = 0;
while (b*2 <= n) b <<= 1;
while (b) {
if (i+b <= n and d[i+b] < k) {
k -= d[i+b];
i += b;
}
b >>= 1;
}
return i;
}
};倍增求LCA
template<typename T=int>
struct lca {
int n, l;
vector<vector<int>> to;
vector<vector<T>> co;
vector<int> dep;
vector<T> costs;
vector<vector<int>> par;
lca(int n): n(n), to(n), co(n), dep(n), costs(n) {
l = 0;
while (1<<l <= n) ++l;
par = vector<vector<int>>(n, vector<int>(l, -1));
}
void addEdge(int a, int b, T c=1) {
to[a].push_back(b); co[a].push_back(c);
to[b].push_back(a); co[b].push_back(c);
}
void dfs(int v, int d=0, T c=0, int p=-1) {
par[v][0] = p;
dep[v] = d;
costs[v] = c;
rep(i, to[v].size()) {
int u = to[v][i];
if (u == p) continue;
dfs(u, d+1, c+co[v][i], v);
}
}
void init(int root=0) {
dfs(root);
rep(i, l-1) {
rep(v, n) {
par[v][i+1] = par[v][i]==-1 ? -1 : par[par[v][i]][i];
}
}
}
// LCA
int operator()(int a, int b) {
if (dep[a] > dep[b]) swap(a, b);
int gap = dep[b]-dep[a];
for (int i = l-1; i >= 0; --i) {
int len = 1<<i;
if (gap >= len) {
gap -= len;
b = par[b][i];
}
}
if (a == b) return a;
for (int i = l-1; i >= 0; --i) {
int na = par[a][i];
int nb = par[b][i];
if (na != nb) a = na, b = nb;
}
return par[a][0];
}
int length(int a, int b) {
int c = (*this)(a, b);
return dep[a]+dep[b]-dep[c]*2;
}
T dist(int a, int b) {
int c = (*this)(a, b);
return costs[a]+costs[b]-costs[c]*2;
}
};换根dp
struct Rerooting {
struct DP {
DP() {}
DP operator+(const DP& a) const {
// edit here
}
DP addRoot() const {
// edit here
}
};
int n;
vector<vector<int>> to;
vector<vector<DP>> dp;
vector<DP> ans;
Rerooting(int n=0): n(n),to(n),dp(n),ans(n) {}
void addEdge(int a, int b) {
to[a].push_back(b);
to[b].push_back(a);
}
void init() {
dfs(0);
bfs(0);
}
DP dfs(int v, int p=-1) {
DP dpSum;
dp[v] = vector<DP>(to[v].size());
rep(i,to[v].size()) {
int u = to[v][i];
if (u == p) continue;
dp[v][i] = dfs(u,v).addRoot();
dpSum = dpSum + dp[v][i];
}
return dpSum;
}
void bfs(int v, const DP& dpP=DP(), int p=-1) {
int deg = to[v].size();
rep(i,deg) if (to[v][i] == p) dp[v][i] = dpP;
vector<DP> dpSumL(deg+1);
rep(i,deg) dpSumL[i+1] = dpSumL[i] + dp[v][i];
vector<DP> dpSumR(deg+1);
for (int i = deg-1; i >= 0; --i)
dpSumR[i] = dpSumR[i+1] + dp[v][i];
ans[v] = dpSumL[deg].addRoot();
rep(i,deg) {
int u = to[v][i];
if (u == p) continue;
DP d = dpSumL[i] + dpSumR[i+1];
bfs(u, d.addRoot(), v);
}
}
};test:
树链剖分
struct HL {
int n, root;
vector<vector<int>> to;
HL() {}
HL(int n): n(n), to(n) {}
void add_edge(int a, int b) {
to[a].push_back(b);
to[b].push_back(a);
}
vector<int> tsz, pa, dep;
int tfs(int v, int d=0, int p=-1) {
pa[v] = p;
dep[v] = d;
tsz[v] = 1;
rep(i, to[v].size()) {
int& u = to[v][i];
if (u == p) swap(u, to[v].back());
if (u == p) break;
tsz[v] += tfs(u, d+1, v);
if (tsz[u] > tsz[to[v][0]]) swap(u, to[v][0]);
}
if (~p) to[v].pop_back();
return tsz[v];
}
vector<int> in, out, nxt, kv;
void dfs(int v) {
in[v] = kv.size(); kv.push_back(v);
rep(i, to[v].size()) {
int u = to[v][i];
nxt[u] = i ? u : nxt[v];
dfs(u);
}
out[v] = kv.size();
}
void init(int v=0) {
tsz = pa = dep = vector<int>(n);
tfs(root=v);
in = out = nxt = vector<int>(n);
nxt[root] = root;
dfs(root);
}
int lca(int a, int b) {
while (nxt[a] != nxt[b]) {
if (in[a] < in[b]) swap(a, b);
a = pa[nxt[a]];
}
if (in[a] < in[b]) swap(a, b);
return b;
}
int dist(int a, int b) {
int c = lca(a, b);
return dep[a]+dep[b]-dep[c]*2;
}
};笛卡尔树
template<class T=long long>
struct CartesianTree {
int n, root;
vector<int> l, r;
CartesianTree() {}
CartesianTree(const vector<T>& a, bool _max=true) {
n = a.size();
l = r = vector<int>(n, -1);
vector<int> st;
rep(i, n) {
int p = -1;
while (st.size() and !((a[st.back()] < a[i]) ^ _max)) {
int j = st.back(); st.pop_back();
r[j] = p; p = j;
}
l[i] = p;
st.push_back(i);
}
rep(i, st.size()-1) r[st[i]] = st[i+1];
root = st[0];
}
};test:
对顶堆求中位数
struct Median {
multiset<int> l;
multiset<int> r;
Median() {}
void rebalance() {
while (l.size() >= r.size()+2) {
r.insert(*l.rbegin());
l.erase(prev(l.end()));
}
while (l.size() < r.size()) {
l.insert(*r.begin());
r.erase(r.begin());
}
if (r.size()) {
while (*l.rbegin() > *r.begin()) {
int lx = *l.rbegin(), rx = *r.begin();
l.erase(prev(l.end()));
r.erase(r.begin());
l.insert(rx); r.insert(lx);
}
}
}
void add(int x) {
l.insert(x);
rebalance();
}
void del(int x) {
auto it = l.find(x);
if (it != l.end()) l.erase(it);
else r.erase(r.find(x));
rebalance();
}
int get() {
int x = *l.rbegin();
if (l.size() != r.size()) return x;
return (x+*(r.begin()))/2;
}
};test:
归并树
struct segtree {
int n;
vector<vector<int>> a;
vector<vector<ll>> s;
segtree(int mx) {
n = 1;
while (n < mx) n <<= 1;
a.resize(n*2);
s.resize(n*2, vector<ll>(1));
}
void set(int i, int x) {
a[n+i] = {x};
s[n+i].push_back(x);
}
void init() {
for (int i = n-1; i >= 1; --i) {
int l = i<<1, r = l|1;
merge(a[l].begin(), a[l].end(), a[r].begin(), a[r].end(), back_inserter(a[i]));
s[i] = vector<ll>(a[i].size()+1);
rep(j, a[i].size()) s[i][j+1] = s[i][j]+a[i][j];
}
}
ll get(int i, int x) {
int j = upper_bound(a[i].begin(), a[i].end(), x) - a[i].begin();
return s[i][j];
}
ll solve(int l, int r, int x) {
l += n; r += n;
ll res = 0;
while (l < r) {
if (l&1) res += get(l, x), l++;
if (r&1) r--, res += get(r, x);
l >>= 1; r >>= 1;
}
return res;
}
};test:
用pbds求排列的逆序数
template<class T>
using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
ll f(vector<int>& a) {
ll res = 0;
Tree<int> t;
for (int x : a) {
res += t.size() - t.order_of_key(x);
t.insert(x);
}
return res;
}图论
强连通分量
struct scc_graph {
int n;
vector<vector<int>> to;
scc_graph(int n): n(n), to(n) {}
void add_edge(int a, int b) {
to[a].push_back(b);
}
pair<int, vector<int>> scc_id() {
int now_ord = 0, group_num = 0;
vector<int> id(n, -1), ord(n, -1), low(n, -1);
stack<int> stk;
auto dfs = [&](auto& f, int v) -> void {
stk.push(v);
ord[v] = low[v] = now_ord++;
for (int u : to[v]) {
if (ord[u] == -1) {
f(f, u);
low[v] = min(low[v], low[u]);
}
else if (id[u] == -1) {
low[v] = min(low[v], ord[u]);
}
}
if (ord[v] == low[v]) {
int u;
do {
u = stk.top(); stk.pop();
id[u] = group_num;
} while (u != v);
group_num++;
}
};
rep(i, n) if (ord[i] == -1) dfs(dfs, i);
return {group_num, id};
}
vector<vector<int>> scc() {
auto ids = scc_id();
int group_num = ids.first;
vector<int> cnt(group_num);
for (int x : ids.second) cnt[x]++;
vector<vector<int>> groups(ids.first);
rep(i, group_num) {
groups[i].reserve(cnt[i]);
}
rep(i, n) {
groups[ids.second[i]].push_back(i);
}
return groups;
}
};test:
2-SAT
struct two_sat {
int n;
vector<vector<int>> to;
vector<bool> ans;
two_sat(int n): n(n), to(2*n), ans(n) {}
void add_clause(int i, bool a, int j, bool b) {
to[2*i+!a].push_back(2*j+b);
to[2*j+!b].push_back(2*i+a);
}
bool satisfiable() {
int n2 = 2*n;
vector<int> id(n2, -1), ord(n2, -1), low(n2, -1);
stack<int> stk;
int now_ord = 0, group_num = 0;
auto dfs = [&](auto& f, int v) -> void {
stk.push(v);
ord[v] = low[v] = now_ord++;
for (int u : to[v]) {
if (ord[u] == -1) {
f(f, u);
low[v] = min(low[v], low[u]);
}
else if (id[u] == -1) {
low[v] = min(low[v], ord[u]);
}
}
if (ord[v] == low[v]) {
int u;
do {
u = stk.top(); stk.pop();
id[u] = group_num;
} while (u != v);
++group_num;
}
};
rep(i, n2) if (ord[i] == -1) dfs(dfs, i);
rep(i, n) {
if (id[2*i] == id[2*i+1]) return false;
ans[i] = id[2*i] > id[2*i+1];
}
return true;
}
vector<bool> answer() { return ans; }
};test:
点双连通分量
struct vcc_graph {
int n;
vector<vector<int>> to;
vcc_graph(int n): n(n), to(n) {}
void add_edge(int a, int b) {
if (a == b) return;
to[a].push_back(b);
to[b].push_back(a);
}
vector<vector<int>> vcc() {
int now_ord = 0;
vector<int> ord(n, -1), low(n, -1);
stack<int> stk;
vector<vector<int>> ans;
auto dfs = [&](auto f, int v, int p=-1) {
if (!to[v].size()) {
ans.emplace_back();
ans.back().push_back(v);
return;
}
stk.push(v);
ord[v] = low[v] = now_ord++;
for (int u : to[v]) {
if (u == p) continue;
if (ord[u] != -1) low[v] = min(low[v], ord[u]);
else {
f(f, u, v);
low[v] = min(low[v], low[u]);
if (low[u] >= ord[v]) {
ans.emplace_back();
int nv;
do {
nv = stk.top(); stk.pop();
ans.back().push_back(nv);
} while (nv != u);
ans.back().push_back(v);
}
}
}
};
rep(i, n) if (ord[i] == -1) dfs(dfs, i);
return ans;
}
};test:
边双连通分量
struct ecc_graph {
int n;
vector<vector<P>> g;
ecc_graph(int n): n(n), g(n) {}
void add_edge(int a, int b, int ei) {
if (a == b) return;
g[a].emplace_back(b, ei);
g[b].emplace_back(a, ei);
}
vector<vector<int>> ecc() {
vector<int> ord(n, -1), low(n, -1); int id = 0;
stack<int> stk;
vector<vector<int>> ans;
auto dfs = [&](auto& f, int v, int ei=-1) -> void {
ord[v] = low[v] = id++;
stk.push(v);
for (auto& [u, i] : g[v]) {
if (i == ei) continue;
if (ord[u] == -1) {
f(f, u, i);
chmin(low[v], low[u]);
}
else chmin(low[v], ord[u]);
}
if (ord[v] == low[v]) {
ans.emplace_back();
int u;
do {
u = stk.top(); stk.pop();
ans.back().push_back(u);
} while (u != v);
}
};
rep(i, n) if (ord[i] == -1) dfs(dfs, i);
return ans;
}
};test:
圆方树
struct BlockCutTree {
int n;
vector<vector<int>> to;
vector<int> ord, low, st;
int cnt, timer;
vector<P> es;
BlockCutTree(int n): n(n), to(n), ord(n, -1), low(n), cnt(0), timer(0) {}
void addEdge(int a, int b) {
to[a].push_back(b);
to[b].push_back(a);
}
void dfs(int v) {
st.push_back(v);
ord[v] = low[v] = timer++;
for (int u : to[v]) {
if (ord[u] == -1) {
dfs(u);
low[v] = min(low[v], low[u]);
if (low[u] == ord[v]) {
int nv;
do {
nv = st.back(); st.pop_back();
es.emplace_back(n+cnt, nv);
} while (nv != u);
es.emplace_back(v, n+cnt);
cnt++;
}
}
else {
low[v] = min(low[v], ord[u]);
}
}
}
pair<int, vector<P>> solve() {
dfs(0);
return {cnt, es};
}
};test:
最大流
template<typename Cap>
struct mf_graph {
static constexpr Cap INF = numeric_limits<Cap>::max();
int n;
struct Edge {
int to; Cap cap;
Edge(int to, Cap cap) : to(to), cap(cap) {}
};
vector<Edge> es;
vector<vector<int>> g;
vector<int> cur, h;
mf_graph(int n) : n(n), g(n) {}
void add_edge(int a, int b, Cap c) {
g[a].push_back(es.size());
es.emplace_back(b, c);
g[b].push_back(es.size());
es.emplace_back(a, 0);
}
bool bfs(int s, int t) {
h.assign(n, -1);
queue<int> q;
h[s] = 0;
q.push(s);
while (q.size()) {
int v = q.front(); q.pop();
for (int i : g[v]) {
int u = es[i].to;
Cap c = es[i].cap;
if (c > 0 and h[u] == -1) {
h[u] = h[v]+1;
if (u == t) return true;
q.push(u);
}
}
}
return false;
}
Cap dfs(int v, int t, Cap f) {
if (v == t) return f;
Cap r = f;
for (int &i = cur[v]; i < int(g[v].size()); ++i) {
int j = g[v][i];
int u = es[j].to;
Cap c = es[j].cap;
if (c > 0 and h[u] == h[v]+1) {
Cap a = dfs(u, t, min(r, c));
es[j].cap -= a;
es[j^1].cap += a;
r -= a;
if (r == 0) return f;
}
}
return f-r;
}
Cap flow(int s, int t) {
Cap res = 0;
while (bfs(s, t)) {
cur.assign(n, 0);
res += dfs(s, t, INF);
}
return res;
}
vector<bool> min_cut(int sv) {
vector<bool> vis(n);
queue<int> q;
q.push(sv);
while (q.size()) {
int v = q.front(); q.pop();
vis[v] = true;
for (int i : g[v]) {
int u = es[i].to;
Cap c = es[i].cap;
if (c and !vis[u]) {
vis[u] = true;
q.push(u);
}
}
}
return vis;
}
};test:
费用流
template<class Cap, class Cost>
struct mcf_graph {
static constexpr Cap INF = numeric_limits<Cap>::max();
struct Edge {
int to;
Cap cap;
Cost cost;
int rev;
};
int n;
vector<vector<Edge>> g;
vector<Cost> dual, dist;
vector<int> pv, pe;
mcf_graph(int n=0) : n(n), g(n), dual(n, 0), dist(n), pv(n), pe(n) {}
int add_edge(int from, int to, Cap cap, Cost cost) {
int id = g[from].size();
g[from].push_back({to, cap, cost, g[to].size()});
g[to].push_back({from, 0, -cost, id});
return id;
}
vector<pair<Cap, Cost>> slope(int s, int t, Cap flow_limit=INF) {
Cap flow = 0;
Cost cost = 0;
fill(dual.begin(), dual.end(), 0);
vector<pair<Cap, Cost>> res = {{0, 0}};
while (flow < flow_limit) {
fill(dist.begin(), dist.end(), INF);
using P = pair<Cost, int>;
priority_queue<P, vector<P>, greater<P>> q;
dist[s] = 0;
q.emplace(0, s);
while (q.size()) {
auto [d, v] = q.top(); q.pop();
if (dist[v] != d) continue;
rep(i, g[v].size()) {
auto& [u, cap, cost, _] = g[v][i];
if (cap <= 0) continue;
Cost nd = d + cost + dual[v] - dual[u];
if (dist[u] <= nd) continue;
dist[u] = nd;
pv[u] = v;
pe[u] = i;
q.emplace(nd, u);
}
}
if (dist[t] == INF) break;
for (int v = 0; v < n; ++v) {
if (dist[v] != INF) dual[v] += dist[v];
}
Cap add = flow_limit - flow;
for (int v = t; v != s; v = pv[v]) {
add = min(add, g[pv[v]][pe[v]].cap);
}
for (int v = t; v != s; v = pv[v]) {
auto& e = g[pv[v]][pe[v]];
e.cap -= add;
g[v][e.rev].cap += add;
}
flow += add;
cost += add * dual[t];
if (res.back().second - (res.size() > 1 ? res[res.size()-2].second : 0) == dual[t]) {
res.pop_back();
}
res.emplace_back(flow, cost);
}
return res;
}
pair<Cap, Cost> flow(int s, int t, Cap flow_limit=INF) {
return slope(s, t, flow_limit).back();
}
};test:
字符串
判断子序列
// 判断 s 是否是 t 的子序列
bool isSubsequence(string s, string t) {
int ti = 0;
for (int si = 0; si < s.size(); ++si) {
while (ti < t.size() and t[ti] != s[si]) ti++;
if (ti == t.size()) return false;
ti++;
}
return true;
}Binary Trie
template<typename T=int, int k=30>
struct BTrie {
struct Node {
array<int, 2> to;
int cnt;
Node(): to({-1, -1}), cnt(0) {}
};
vector<Node> d;
BTrie(): d(1) {}
int go(int v, int x) {
if (d[v].to[x] == -1) {
d[v].to[x] = d.size();
d.push_back(Node());
}
return d[v].to[x];
}
void add(T x, int num=1) {
int v = 0;
for (int i = k; i >= 0; --i) {
v = go(v, x>>i&1);
d[v].cnt += num;
}
}
T query(T x) {
if (d.size() == 1) return 0;
T res = 0; int v = 0;
for (int i = k; i >= 0; --i) {
int s = x>>i&1;
int u = d[v].to[!s];
if (u != -1 and d[u].cnt) {
res += 1<<i;
s ^= 1;
}
v = d[v].to[s];
}
return res;
}
};test:
Trie树
struct Trie {
struct Node {
map<char, int> to;
int cnt;
Node(): cnt(0) {}
};
vector<Node> d;
Trie(): d(1) {}
void add(const string& s) {
int v = 0;
for (char c : s) {
if (!d[v].to.count(c)) {
d[v].to[c] = d.size();
d.push_back(Node());
}
v = d[v].to[c];
}
d[v].cnt++;
}
int solve(string s) {
int v = 0;
for (char c : s) {
if (!d[v].to.count(c)) return 0;
v = d[v].to[c];
}
return d[v].cnt;
}
};test:
KMP
// Morris-Pratt
template<typename T>
struct MP {
int n;
T t;
vector<int> a;
MP() {}
MP(const T& t): t(t) {
n = t.size();
a = vector<int>(n+1);
a[0] = -1;
int j = -1;
rep(i, n) {
while (j != -1 and t[j] != t[i]) j = a[j];
j++;
a[i+1] = j;
}
}
int operator[](int i) { return a[i]; }
vector<int> findAll(const T& s) {
vector<int> res;
int j = 0;
for (int i = 0; i < s.size(); ++i) {
while (j != -1 and t[j] != s[i]) j = a[j];
j++;
if (j == n) {
res.push_back(i-j+1);
j = a[j];
}
}
return res;
}
};test:
Z-算法
struct Z {
int n;
string s;
vector<int> z;
Z(const string& s): s(s) { init(); }
void init() {
n = s.size();
z = vector<int>(n);
z[0] = n;
for (int i = 1, j = 0; i < n;) {
while (i+j < n and s[i+j] == s[j]) ++j;
z[i] = j;
if (j) {
int k = 1;
while (i+k < n and k+z[k] < j) {
z[i+k] = z[k];
k++;
}
i += k; j -= k;
}
else i++;
}
}
int operator[](int i) const { return z[i]; }
};test:
RLE 算法
// Run Length Encoding
namespace RLE {
template<typename T>
vector<pair<T, int>> f(const vector<T>& a) {
if (!a.size()) return {};
vector<pair<T, int>> res(1, {a[0], 1});
for (int i = 1; i < a.size(); ++i) {
if (res.back().first == a[i]) res.back().second++;
else res.emplace_back(a[i], 1);
}
return res;
}
using CP = pair<char, int>;
vector<CP> f(const string& a) {
if (!a.size()) return vector<CP>();
vector<CP> res(1, CP(a[0], 1));
for (int i = 1; i < a.size(); ++i) {
if (res.back().first == a[i]) res.back().second++;
else res.emplace_back(a[i], 1);
}
return res;
}
}test:
AC自动机
struct Aho {
bool inited;
using MP = unordered_map<char, int>;
vector<MP> to;
vector<int> cnt, fail;
Aho(): to(1), cnt(1) {}
int add(const string& s) {
int v = 0;
for (char c : s) {
if (!to[v].count(c)) {
to[v][c] = to.size();
to.push_back(MP());
cnt.push_back(0);
}
v = to[v][c];
}
cnt[v]++;
return v;
}
void init() {
fail = vector<int>(to.size(), -1);
queue<int> q;
q.push(0);
while (q.size()) {
int v = q.front(); q.pop();
for (auto [c, u] : to[v]) {
fail[u] = (*this)(fail[v], c);
cnt[u] += cnt[fail[u]];
q.push(u);
}
}
}
int operator()(int v, char c) const {
while (v != -1) {
auto it = to[v].find(c);
if (it != to[v].end()) return it->second;
v = fail[v];
}
return 0;
}
int operator[](int v) const { return cnt[v]; }
};test:
计算几何
// Geometry
const double eps = 1e-9;
bool equal(double a, double b) { return abs(a-b) < eps;}点/向量
const double eps = 1e-9;
struct V {
double x, y;
V(double x=0, double y=0): x(x), y(y) {}
V& operator+=(const V& v) { x += v.x; y += v.y; return *this; }
V operator+(const V& v) const { return V(*this) += v; }
V& operator-=(const V& v) { x -= v.x; y -= v.y; return *this; }
V operator-(const V& v) const { return V(*this) -= v; }
V& operator*=(double s) { x *= s; y *= s; return *this; }
V operator*(double s) const { return V(*this) *= s; }
V& operator/=(double s) { x /= s; y /= s; return *this; }
V operator/(double s) const { return V(*this) /= s; }
double dot(const V& v) const { return x*v.x + y*v.y; }
double cross(const V& v) const { return x*v.y - v.x*y; }
double norm2() const { return x*x + y*y; }
double norm() const { return sqrt(norm2()); }
int ort() const { // orthant
if (abs(x) < eps and abs(y) < eps) return 0;
if (y > 0) return x > 0 ? 1 : 2;
else return x < 0 ? 3 : 4;
}
bool operator<(const V& v) const {
int o = ort(), vo = v.ort();
if (o != vo) return o < vo;
return cross(v) > 0;
}
};
istream& operator>>(istream& is, V& v) {
is >> v.x >> v.y; return is;
}
ostream& operator<<(ostream& os, const V& v) {
os << "(" << v.x << "," << v.y << ")"; return os;
}整数版本
struct V {
ll x, y;
V(ll x=0, ll y=0): x(x), y(y) {}
V& operator+=(const V& v) { x += v.x; y += v.y; return *this;}
V operator+(const V& v) const { return V(*this) += v;}
V& operator-=(const V& v) { x -= v.x; y -= v.y; return *this;}
V operator-(const V& v) const { return V(*this) -= v;}
V& operator*=(ll s) { x *= s; y *= s; return *this;}
V operator*(ll s) const { return V(*this) *= s;}
V& operator/=(ll s) { x /= s; y /= s; return *this;}
V operator/(ll s) const { return V(*this) /= s;}
ll dot(const V& v) const { return x*v.x + y*v.y;}
ll cross(const V& v) const { return x*v.y - v.x*y;}
ll norm2() const { return x*x + y*y;}
ll norm() const { return sqrt(norm2());}
V normalize() const { return *this/norm();}
V rotate90() const { return V(y, -x);}
int ort() const { // orthant
if (abs(x) < 0 && abs(y) < 0) return 0;
if (y > 0) return x>0 ? 1 : 2;
else return x>0 ? 4 : 3;
}
bool operator<(const V& v) const {
int o = ort(), vo = v.ort();
if (o != vo) return o < vo;
return cross(v) > 0;
}
};
istream& operator>>(istream& is, V& v) {
is >> v.x >> v.y; return is;
}
ostream& operator<<(ostream& os, const V& v) {
os<<"("<<v.x<<","<<v.y<<")"; return os;
}直线
struct Line {
V s, t;
Line(V s=V(0,0), V t=V(0,0)):s(s),t(t){}
V dir() const { return t-s;}
// V normalize() const { return dir().normalize();}
double norm() const { return dir().norm();}
/* +1: s-t,s-p : ccw
* -1: s-t,s-p : cw
* +2: t-s-p
* -2: s-t-p
* 0: s-p-t */
int ccw(const V& p) const {
if (dir().cross(p-s) > eps) return +1;
if (dir().cross(p-s) < -eps) return -1;
if (dir().dot(p-s) < -eps) return +2;
if (dir().norm()+eps < (p-s).norm()) return -2;
return 0;
}
bool touch(const Line& l) const {
int a = ccw(l.s)*ccw(l.t), b = l.ccw(s)*l.ccw(t);
return !a || !b || (a == -1 && b == -1);
}
};整数版本
struct Line {
V s, t;
Line(V s=V(0,0), V t=V(0,0)):s(s),t(t){}
V dir() const { return t-s;}
V normalize() const { return dir().normalize();}
ll norm() const { return dir().norm();}
/* +1: s-t,s-p : ccw
* -1: s-t,s-p : cw
* +2: t-s-p
* -2: s-t-p
* 0: s-p-t */
int ccw(const V& p) const {
if (dir().cross(p-s) > 0) return +1;
if (dir().cross(p-s) < 0) return -1;
if (dir().dot(p-s) < 0) return +2;
if (dir().dot(t-p) < 0) return -2;
return 0;
}
bool touch(const Line& l) const {
int a = ccw(l.s)*ccw(l.t), b = l.ccw(s)*l.ccw(t);
return !a || !b || (a == -1 && b == -1);
}
};test:
圆
const double eps = 1e-9;
bool equal(double a, double b) { return abs(a-b) < eps; }
struct V {
double x, y;
V(double x=0, double y=0): x(x), y(y) {}
V operator+(const V& p) const { return V(x+p.x, y+p.y); }
V operator-(const V& p) const { return V(x-p.x, y-p.y); }
V operator*(double a) const { return V(x*a, y*a); }
double sqrNorm() const { return x*x+y*y; }
double norm() const { return sqrt(sqrNorm()); }
V rotate90() const { return V(y, -x); }
};
struct Circle {
V o; double r;
Circle(V o=V(), double r=0): o(o), r(r) {}
vector<V> xp(const Circle& c) {
V v = c.o-o;
double l = v.norm();
if (equal(l, 0)) return {};
if (equal(l+r+c.r, max({l, r, c.r})*2)) {
if (equal(l+r, c.r)) return {o - v*(r/l)};
return {o + v*(r/l)};
}
if (l+r+c.r < max({l, r, c.r})*2) return {};
double x = (l*l + r*r - c.r*c.r) / (2*l);
double y = sqrt(r*r - x*x);
V mid = o + v*(x/l);
v = v.rotate90();
return {mid + v*(y/l), mid - v*(y/l)};
}
bool isInside(const V& p) {
return (p-o).norm() < r+eps;
}
};dp优化
Convex Hull Trick
// 求最大值
struct CHT {
deque<P> d;
void add(ll a, ll b) {
while (d.size() >= 2) {
auto [a1, b1] = d[d.size()-1];
auto [a0, b0] = d[d.size()-2];
if ((b0-b1)*(a-a1) < (b1-b)*(a1-a0)) break;
d.pop_back();
}
d.emplace_back(a, b);
}
ll get(ll x) {
while (d.size() >= 2) {
auto [a0, b0] = d[0];
auto [a1, b1] = d[1];
if (a0*x+b0 > a1*x+b1) break;
d.pop_front();
}
auto [a, b] = d[0];
return a*x+b;
}
};// 求最小值
struct CHT {
deque<P> d;
void add(ll a, ll b) {
while (d.size() >= 2) {
auto [a1, b1] = d[d.size()-1];
auto [a0, b0] = d[d.size()-2];
if ((b0-b1)*(a-a1) < (b1-b)*(a1-a0)) break;
d.pop_back();
}
d.emplace_back(a, b);
}
ll get(ll x) {
while (d.size() >= 2) {
auto [a0, b0] = d[0];
auto [a1, b1] = d[1];
if (a0*x+b0 < a1*x+b1) break;
d.pop_front();
}
auto [a, b] = d[0];
return a*x+b;
}
};test:
多项式
using ll = long long;
using unit = unsigned int;
using ull = unsigned long long;
const int mod = 1004535809;
// const int mod = 998244353;
// const int mod = 1000000007;
struct mint {
uint x;
mint(ll v = 0) { x = (uint)((v % mod + mod) % mod); }
mint operator-() const { return mint(x ? mod - x : 0); }
mint& operator+=(const mint& a) { if ((x += a.x) >= mod) x -= mod; return *this; }
mint& operator-=(const mint& a) { if (x < a.x) x += mod; x -= a.x; return *this; }
mint& operator*=(const mint& a) { x = (uint)((ull)x * a.x % mod); return *this; }
mint operator+(const mint& a) const { return mint(*this) += a; }
mint operator-(const mint& a) const { return mint(*this) -= a; }
mint operator*(const mint& a) const { return mint(*this) *= a; }
mint pow(ll t) const {
mint res = 1, a = *this;
while (t > 0) { if (t & 1) res *= a; a *= a; t >>= 1; }
return res;
}
mint operator~() const { return pow(mod - 2); }
};
ostream& operator<<(ostream& os, const mint& a) {
return os << a.x;
}
using vm = vector<mint>;
struct NTT {
int ceil_pow2(int n) { int x = 0; while ((1U << x) < (uint)(n)) x++; return x; }
int bsf(uint n) { return __builtin_ctz(n); }
const static int _g = 3;
void butterfly(vm& a) {
static mint g = _g; int n = a.size(), h = ceil_pow2(n);
static bool first = true; static mint sum_e[30];
if (first) {
first = false; mint es[30], ies[30]; int cnt2 = bsf(mod-1);
mint e = g.pow((mod-1) >> cnt2), ie = ~e;
for (int i = cnt2; i >= 2; i--) {
es[i-2] = e; ies[i-2] = ie; e *= e; ie *= ie;
}
mint now = 1;
rep(i, cnt2-1) sum_e[i] = es[i] * now, now *= ies[i];
}
for (int ph = 1; ph <= h; ++ph) {
int w = 1<<(ph-1), p = 1<<(h-ph); mint now = 1;
rep(s, w) {
int offset = s<<(h-ph+1);
rep(i, p) {
auto l = a[i+offset], r = a[i+offset+p]*now;
a[i+offset] = l+r; a[i+offset+p] = l-r;
}
now *= sum_e[bsf(~(uint)(s))];
}
}
}
void butterfly_inv(vm& a) {
static mint g = _g; int n = a.size(), h = ceil_pow2(n);
static bool first = true; static mint sum_ie[30];
if (first) {
first = false; mint es[30], ies[30];
int cnt2 = bsf(mod-1); mint e = g.pow((mod-1) >> cnt2), ie = ~e;
for (int i = cnt2; i >= 2; --i) {
es[i-2] = e; ies[i-2] = ie; e *= e; ie *= ie;
}
mint now = 1; rep(i, cnt2-1) sum_ie[i] = ies[i]*now, now *= es[i];
}
for (int ph = h; ph >= 1; --ph) {
int w = 1<<(ph-1), p = 1<<(h-ph); mint inow = 1;
rep(s, w) {
int offset = s<<(h-ph+1);
rep(i, p) {
auto l = a[i+offset], r = a[i+offset+p];
a[i+offset] = l+r;
a[i+offset+p] = (ull)(mod+l.x-r.x)*inow.x;
}
inow *= sum_ie[bsf(~(uint)(s))];
}
}
}
vm operator()(vm a, vm b) {
int n = a.size(), m = b.size(); if (!n || !m) return {};
if (min(n, m) <= 60) {
if (n < m) swap(n, m), swap(a, b);
vm ans(n+m-1); rep(i, n) rep(j, m) ans[i+j] += a[i]*b[j];
return ans;
}
int z = 1<<ceil_pow2(n+m-1);
a.resize(z); butterfly(a); b.resize(z); butterfly(b);
rep(i, z) a[i] *= b[i];
butterfly_inv(a); a.resize(n+ m-1); mint iz = ~(mint(z));
rep(i, n + m - 1) a[i] *= iz;
return a;
}
} ntt;形式幂级数
// Formal Power Series
using vm = vector<mint>;
struct fps : vm {
#define d (*this)
#define s int(vm::size())
template<class...Args> fps(Args...args): vm(args...) {}
fps(initializer_list<mint> a): vm(a.begin(),a.end()) {}
void rsz(int n) { if (s < n) resize(n);}
fps& low_(int n) { resize(n); return d;}
fps low(int n) const { return fps(d).low_(n);}
mint& operator[](int i) { rsz(i+1); return vm::operator[](i);}
mint operator[](int i) const { return i<s ? vm::operator[](i) : 0;}
mint operator()(mint x) const {
mint r;
for (int i = s-1; i >= 0; --i) r = r*x+d[i];
return r;
}
fps operator-() const { fps r(d); rep(i,s) r[i] = -r[i]; return r;}
fps& operator+=(const fps& a) { rsz(a.size()); rep(i,a.size()) d[i] += a[i]; return d;}
fps& operator-=(const fps& a) { rsz(a.size()); rep(i,a.size()) d[i] -= a[i]; return d;}
fps& operator*=(const fps& a) { return d = convolution(d, a);}
fps& operator*=(mint a) { rep(i,s) d[i] *= a; return d;}
fps& operator/=(mint a) { rep(i,s) d[i] /= a; return d;}
fps operator+(const fps& a) const { return fps(d) += a;}
fps operator-(const fps& a) const { return fps(d) -= a;}
fps operator*(const fps& a) const { return fps(d) *= a;}
fps operator*(mint a) const { return fps(d) *= a;}
fps operator/(mint a) const { return fps(d) /= a;}
fps operator~() const {
fps r({d[0].inv()});
for (int i = 1; i < s; i <<= 1) r = r*mint(2) - (r*r*low(i<<1)).low(i<<1);
return r.low_(s);
}
fps& operator/=(const fps& a) { int w = s; d *= ~a; return d.low_(w);}
fps operator/(const fps& a) const { return fps(d) /= a;}
fps integ() const {
fps r;
rep(i,s) r[i+1] = d[i]/(i+1);
return r;
}
#undef s
#undef d
};
ostream& operator<<(ostream&o,const fps&a) {
rep(i,a.size()) o<<(i?" ":"")<<a[i].val();
return o;
}