跳到正文

算法·理论

模板

___Mitsui_Hisashi___约 32 分钟
原文
文章信息与版本

文章信息

发布
2025年11月10日
收录
2025年12月12日
更新
2026年11月19日
篇幅
约 32 分钟
获赞
1

版本

  1. v2当前
  2. v1

图论

最短路

dijkstra

C++
void dijkstra() {
	memset(dis, 0x7f, sizeof dis);
	dis[s] = 0;
	q.push({s, 0});
	while (q.size()) {
		int u = q.top().v;
		q.pop();
		if (vis[u])
			continue;
		vis[u] = 1;
		for (auto [v, w] : g[u]) {
			if (dis[u] + w < dis[v]) {
				dis[v] = dis[u] + w;
				q.push({v, dis[v]});
			}
		}
	}
}

SPFA

C++
void spfa() {
	for (int i = 1; i <= n; i++)
		dis[i] = INT_MAX;
	dis[s] = 0;
	vis[s] = 1;
	q.push(s);
	while (q.size()) {
		int u = q.front();
		q.pop();
		vis[u] = 0;
		for (auto [v, w] : g[u]) {
			if (dis[u] + w < dis[v]) {
				dis[v] = dis[u] + w;
				if (!vis[v])
					vis[v] = 1, q.push(v);
			}
		}
	}
}

生成树

Prim

C++
struct node {
	int v, w;
	bool operator>(const node &x)const {
		return w > x.w;
	}
};
vector<node>g[N];
bool vis[N];
int dis[N];
priority_queue<node, vector<node>, greater<node>>q;
void Prim() {
	memset(dis, 0x4f, sizeof(dis));
	dis[1] = 0;
	int cnt = 0;
	q.push({1, 0});
	while (q.size()) {
		int u = q.top().v, w = q.top().w;
		q.pop();
		if (vis[u])
			continue;
		vis[u] = 1;
		cnt++;
		ans += w;
		if (cnt == n)
			return;
		for (auto t : g[u]) {
			int v = t.v, w = t.w;
			if (w < dis[v])
				dis[v] = w, q.push(t);
		}
	}
}

Kruskal

C++
struct node {
	int u,v,w;
	bool opreator<(const node &x)const {
		return w<x.w;
	}
};
void kruskal(DSU &dsu) {
	int cnt = 0;
	for (auto t : g) {
		int u = dsu.find(t.u), v = dsu.find(t.v);
		if (u == v)
			continue;
		dsu.mergy(u, v);
		cnt++;
		ans += t.w;
		if (cnt == n - 1)
			return;
	}
}

字符串

KMP

C++
void kmp() {
	for (int i = 2, j = 0; i <= m; i++) {
		while (j && s2[i] != s2[j + 1])
			j = nxt[j];
		if (s2[i] == s2[j + 1])
			j++;
		nxt[i] = j;
	}
	for (int i = 1, j = 0; i <= n; i++) {
		while (j && s1[i] != s2[j + 1])
			j = nxt[j];
		if (s1[i] == s2[j + 1])
			j++;
		if (j == m)
			j = nxt[j];
	}
}

Manacher

C++
void manacher() {
	t = "@ ";
	for (char c : s)
		t += c, t += " ";
	t += "~";
	int n = t.size();
	for (int i = 1; i < n - 1; i++) {
		p[i] = i < r ? min(p[2 * mid - i], r - i) : 1;
		while (t[i - p[i]] == t[i + p[i]])
			p[i]++;
		if (i + p[i] - 1) {
			mid = i;
			r = i + p[i] - 1;
		}
	}
}

数据结构

并查集

C++
struct DSU {
	vector<int>pa, size;
	DSU (int n) {
		pa.resize(n + 1);
		size.resize(n + 1, 1);
		for (int i = 1; i <= n; i++)
			pa[i] = i;
	}
	int find(int x) {
		return pa[x] == x ? x : pa[x] = find(pa[x]);
	}
	void mergy(int x, int y) {
		x = find(x), y = find(y);
		if (x == y)
			return;
		if (size[x] < size[y])
			swap(x, y);
		size[x] += size[y];
		pa[y] = x;
	}
};

线段树

C++
#define ll long long
#define M ((L+R)>>1)
#define ls u*2
#define rs u*2+1
using namespace std;
const int N = 1e5+5;
int n, m, op, x, y;
ll a[N], k;
struct node {
	ll w, lzy;
} tree[4 * N];
void pushup(int u) {
	tree[u].w = tree[u * 2].w + tree[u * 2 + 1].w;
}
void build(int u, int L, int R) {
	if (L == R) {
		tree[u].w = a[L];
		return;
	}
	build(ls, L, M);
	build(rs, M + 1, R);
	pushup(u);
}
void maketag(int u, int len, ll x) {
	tree[u].lzy += x;
	tree[u].w += len * x;
}
void pushdown(int u, int L, int R) {
	maketag(ls, M - L + 1, tree[u].lzy);
	maketag(rs, R - M, tree[u].lzy);
	tree[u].lzy = 0;
}
bool inrange(int L, int R, int l, int r) {
	return (L >= l) && (R <= r);
}
bool outrange(int L, int R, int l, int r) {
	return (L > r) || (R < l);
}
ll caory(int u, int L, int R, int l, int r) {
	if (inrange(L, R, l, r))
		return tree[u].w;
	else if (!outrange(L, R, l, r)) {
		pushdown(u, L, R);
		return caory(ls, L, M, l, r) + caory(rs, M + 1, R, l, r);
	} else
		return 0;
}
void update(int u, int L, int R, int l, int r, ll x) {
	if (inrange(L, R, l, r))
		maketag(u, R - L + 1, x);
	else if (!outrange(L, R, l, r)) {
		pushdown(u, L, R);
		update(ls, L, M, l, r, x);
		update(rs, M + 1, R, l, r, x);
		pushup(u);
	}
}

优先向量

C++
struct priority_vector {
	vector<int> aaa;
	void push(int num) {
		aaa.insert(upper_bound(aaa.begin(), aaa.end(), num), num);
	}
	void out(int it) {
		cout << aaa[it];
	}
	void clear() {
		aaa.clear();
	}
	bool empty() {
		return aaa.empty();
	}
	int size() {
		return aaa.size();
	}
	void pop_top() {
		aaa.erase(aaa.begin());
	}
	void pop_back() {
		aaa.erase(aaa.end());
	}
	auto begin() {
		return aaa.begin();
	}
	auto end() {
		return aaa.end();
	}
};

二维树状数组

C++
void add(int x, int y, int v) {
	for (int i = x; i <= n; i += lowbit(i))
		for (int j = y; j <= m; j += lowbit(j)) {
			tree[i][j][0] += v;
			tree[i][j][1] += v * x;
			tree[i][j][2] += v * y;
			tree[i][j][3] += v * x * y;
		}
}
void range_add(int x1, int y1, int x2, int y2, int v) {
	add(x1, y1, v);
	add(x2 + 1, y2 + 1, v);
	add(x1, y2 + 1, -v);
	add(x2 + 1, y1, -v);
}
int caory(int x, int y) {
	int re = 0;
	for (int i = x; i; i -= lowbit(i))
		for (int j = y; j; j -= lowbit(j)) 
			re += (x + 1) * (y + 1) * tree[i][j][0]
			- (y + 1) * tree[i][j][1]
			- (x + 1) * tree[i][j][2]
			+ tree[i][j][3];
	return re;
}
int range_caory(int x1, int y1, int x2, int y2) {
	return caory(x2, y2) - caory(x2, y1 - 1) - caory(x1 - 1, y2) + caory(x1 - 1, y1 - 1);
}

数学

快速幂

C++
long long fpow(long long a, long long b) {
	long long re = 1;
	while (b) {
		if (b & 1)
			re = (re * a) % mod;
		b >>= 1;
		a = (a * a) % mod;
	}
	return re;
}

欧拉筛

C++
vector<bool> isprime;
vector<int> prime(1);
void Sieve(int n) {
	isprime.resize(n + 1, 1);
	isprime[1] = 0;
	for (int i = 2; i <= n; i++) {
		if (isprime[i])
			prime.push_back(i);
		for (size_t j = 1; j < prime.size() && i * prime[j] <= n; j++) {
			isprime[i * prime[j]] = 0;
			if (i % prime[j] == 0)
				break;
		}
	}
}

exgcd

C++
int exgcd(int a, int b, int &x, int &y) {
	if (!b) {
		x = 1, y = 0;
		return a;
	}
	int re = exgcd(b, a % b, y, x);
	y -= a / b * x;
	return re;
}

中国剩余定理(CRT)

C++
int crt() {
	int M = 1, ans = 0;
	for (int i = 1; i <= n; i++)
		M *= m[i];
	for (int i = 1; i <= n; i++) {
		int mi = M / m[i];
		int x, y;
		exgcd(mi, m[i], x, y);
		x = (x % m[i] + m[i]) % m[i];
		ans = (ans + (__int128)a[i] * mi % M * x % M) % M;
	}
	return ans;
}

EXCRT

C++
fc unite(fc a1, fc a2) {
	int p, q;
	int d = exgcd(a1.m, a2.m, p, q);
	if ((a2.a - a1.a) % d)
		return {-1, -1};
	int step = a2.m / d;
	p = ((__int128)p * (a2.a - a1.a) / d % step + step) % step;
	int next_m = lcm(a1.m, a2.m);
	int next_a = ((__int128)a1.m * p + a1.a) % next_m;
	return {next_m, next_a};
}
int excrt() {
	fc ans = a[1];
	for (int i = 2; i <= n; i++) {
		ans = unite(ans, a[i]);
		if (ans.m == -1)
			return -1;
	}
	return ans.a;
}

矩阵

C++
struct matrix {
	int mat[105][105];
	int r, c;
	matrix () {
		memset(mat, 0, sizeof mat);
	}
	int *operator[](int i) {
		return mat[i];
	}
	matrix operator *(matrix &b) const {
		matrix re;
		re.r = r, re.c = b.c;
		for (int i = 1; i <= r; i++)
			for (int k = 1; k <= c; k++)
				for (int j = 1; j <= b.c; j++)
					re[i][j] = (re[i][j] + mat[i][k] * b[k][j]) % mod;
		return re;
	}
};
matrix fpow(matrix a, long long b) {
	matrix re;
	re[0][0] = re[1][1] = 1;
	while (b) {
		if (b & 1)
			re = re * a;
		a = a * a;
		b >>= 1;
	}
	return re;
}

高斯消元

C++
int Gauss() {
	int r = 1;
	for (int c = 1; c <= n; c++) {
		int cur = r;
		for (int i = r; i <= n; i++)
			if (fabs(a[i][c]) > fabs(a[cur][c]))
				cur = i;
		if (fabs(a[cur][c]) < eps)
			continue;
		swap(a[r], a[cur]);
		double div = a[r][c];
		for (int i = c; i <= n + 1; i++)
			a[r][i] /= div;
		for (int i = 1; i <= n; i++) {
			if (i == r)
				continue;
			double mul = a[i][c];
			for (int j = c; j <= n + 1; j++)
				a[i][j] -= mul * a[r][j];
		}
		r++;
	}
	if (r <= n) {
		for (int i = r; i <= n; i++)
			if (fabs(a[i][n + 1]) > eps)
				return -1;
		return 0;
	}
	for (int i = 1; i <= n; i++)
		ans[i] = a[i][n + 1];
	return 1;
}

其他

高精度

C++
struct BigInt {
	vector<int> digits;
	bool is_neg = false;
	BigInt() : digits(1, 0), is_neg(false) {}
	BigInt(long long v) {
		if (v < 0) {
			is_neg = true;
			v = -v;
		} else {
			is_neg = false;
		}
		if (v == 0) digits.push_back(0);
		while (v > 0) {
			digits.push_back(v % 10);
			v /= 10;
		}
	}
	BigInt(const string& s) {
		is_neg = false;
		if (s.empty()) {
			digits.push_back(0);
			return;
		}
		int start = 0;
		if (s[0] == '-') {
			is_neg = true;
			start = 1;
		} else if (s[0] == '+') {
			start = 1;
		}
		for (int i = s.length() - 1; i >= start; i--) {
			digits.push_back(s[i] - '0');
		}
		trim();
	}
	void trim() {
		while (digits.size() > 1 && digits.back() == 0) {
			digits.pop_back();
		}
		if (digits.size() == 1 && digits[0] == 0) {
			is_neg = false;
		}
	}
	BigInt abs() const {
		BigInt res = *this;
		res.is_neg = false;
		return res;
	}
	friend BigInt abs(const BigInt& a) {
		return a.abs();
	}
	BigInt operator-() const {
		if (digits.size() == 1 && digits[0] == 0) return *this;
		BigInt res = *this;
		res.is_neg = !res.is_neg;
		return res;
	}
	static bool abs_less(const BigInt& a, const BigInt& b) {
		if (a.digits.size() != b.digits.size()) {
			return a.digits.size() < b.digits.size();
		}
		for (int i = (int)a.digits.size() - 1; i >= 0; i--) {
			if (a.digits[i] != b.digits[i]) {
				return a.digits[i] < b.digits[i];
			}
		}
		return false;
	}
	bool operator<(const BigInt& b) const {
		if (is_neg != b.is_neg) return is_neg;
		if (is_neg) return abs_less(b, *this);
		return abs_less(*this, b);
	}
	bool operator>(const BigInt& b) const { return b < *this; }
	bool operator<=(const BigInt& b) const { return !(*this > b); }
	bool operator>=(const BigInt& b) const { return !(*this < b); }
	bool operator==(const BigInt& b) const { return is_neg == b.is_neg && digits == b.digits; }
	bool operator!=(const BigInt& b) const { return !(*this == b); }
	static BigInt add_unsigned(const BigInt& a, const BigInt& b) {
		BigInt res;
		res.digits.clear();
		int carry = 0;
		for (size_t i = 0; i < max(a.digits.size(), b.digits.size()) || carry; ++i) {
			if (i < a.digits.size()) carry += a.digits[i];
			if (i < b.digits.size()) carry += b.digits[i];
			res.digits.push_back(carry % 10);
			carry /= 10;
		}
		return res;
	}
	static BigInt sub_unsigned(const BigInt& a, const BigInt& b) {
		BigInt res;
		res.digits.clear();
		int borrow = 0;
		for (size_t i = 0; i < a.digits.size(); ++i) {
			int diff = a.digits[i] - borrow - (i < b.digits.size() ? b.digits[i] : 0);
			if (diff < 0) {
				diff += 10;
				borrow = 1;
			} else {
				borrow = 0;
			}
			res.digits.push_back(diff);
		}
		res.trim();
		return res;
	}
	BigInt operator+(const BigInt& b) const {
		if (is_neg == b.is_neg) {
			BigInt res = add_unsigned(*this, b);
			res.is_neg = is_neg;
			res.trim();
			return res;
		}
		if (abs_less(*this, b)) {
			BigInt res = sub_unsigned(b, *this);
			res.is_neg = b.is_neg;
			res.trim();
			return res;
		} else {
			BigInt res = sub_unsigned(*this, b);
			res.is_neg = is_neg;
			res.trim();
			return res;
		}
	}
	BigInt operator-(const BigInt& b) const {
		return *this + (-b);
	}
	BigInt operator*(const BigInt& b) const {
		BigInt res;
		res.digits.assign(digits.size() + b.digits.size(), 0);
		for (size_t i = 0; i < digits.size(); ++i) {
			long long carry = 0;
			for (size_t j = 0; j < b.digits.size(); ++j) {
				long long cur = res.digits[i + j] + (long long)digits[i] * b.digits[j] + carry;
				res.digits[i + j] = cur % 10;
				carry = cur / 10;
			}
			if (carry > 0) {
				res.digits[i + b.digits.size()] += carry;
			}
		}
		res.is_neg = is_neg ^ b.is_neg;
		res.trim();
		return res;
	}
	BigInt operator/(const int& b) const {
		BigInt res;
		res.digits.clear();
		long long current = 0;
		int abs_b = std::abs(b);
		for (int i = digits.size() - 1; i >= 0; i--) {
			current = current * 10 + digits[i];
			res.digits.push_back(current / abs_b);
			current %= abs_b;
		}
		reverse(res.digits.begin(), res.digits.end());
		res.is_neg = is_neg ^ (b < 0);
		res.trim();
		return res;
	}
	long long operator%(const int& b) const {
		long long current = 0;
		int abs_b = std::abs(b);
		for (int i = digits.size() - 1; i >= 0; i--) {
			current = (current * 10 + digits[i]) % abs_b;
		}
		return is_neg ? -current : current;
	}
	BigInt pow(long long n) const {
		BigInt res(1);
		BigInt base = *this;
		while (n > 0) {
			if (n % 2 == 1) res = res * base;
			base = base * base;
			n /= 2;
		}
		return res;
	}
	BigInt operator^(const long long& n) const { return this->pow(n); }
	friend istream& operator>>(istream& in, BigInt& a) {
		string s;
		in >> s;
		a = BigInt(s);
		return in;
	}
	friend ostream& operator<<(ostream& out, const BigInt& a) {
		if (a.is_neg) out << '-';
		for (int i = a.digits.size() - 1; i >= 0; i--) {
			out << a.digits[i];
		}
		return out;
	}
};

快读快输

C++
#include <iostream>
#include <cstdio>
#include <string>

// ---------------- 核心 FastIO 模板 ----------------
namespace FastIO {
    const int BUF_SIZE = 1 << 20; // 1MB 缓冲区

    // 输入类,模拟 std::cin
    class FastIn {
    private:
        char buf[BUF_SIZE], *p1, *p2;

        inline char gc() {
            return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, BUF_SIZE, stdin), p1 == p2) ? EOF : *p1++;
        }

    public:
        FastIn() : p1(buf), p2(buf) {}

        // 支持所有标准整型 (int, long long, __int128 等)
        template <typename T>
        inline FastIn& operator>>(T& x) {
            x = 0; int f = 1; char ch = gc();
            while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = gc(); }
            while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = gc(); }
            x *= f;
            return *this;
        }

        // 支持读取单个字符 (自动跳过空白字符)
        inline FastIn& operator>>(char& c) {
            c = gc();
            while (c == ' ' || c == '\n' || c == '\r' || c == '\t') c = gc();
            return *this;
        }

        // 支持读取 std::string (遇到空白字符停止)
        inline FastIn& operator>>(std::string& s) {
            s.clear();
            char c = gc();
            while (c == ' ' || c == '\n' || c == '\r' || c == '\t') c = gc();
            while (c != EOF && c != ' ' && c != '\n' && c != '\r' && c != '\t') {
                s += c;
                c = gc();
            }
            return *this;
        }
    } fin; // 实例化为 fin,代替 cin

    // 输出类,模拟 std::cout
    class FastOut {
    private:
        char buf[BUF_SIZE], *pout;

        inline void pc(char c) {
            if (pout - buf == BUF_SIZE) flush();
            *pout++ = c;
        }

    public:
        FastOut() : pout(buf) {}
        
        // 析构时自动清空缓冲区
        ~FastOut() { flush(); }

        inline void flush() {
            fwrite(buf, 1, pout - buf, stdout);
            pout = buf;
        }

        // 支持所有标准整型
        template <typename T>
        inline FastOut& operator<<(T x) {
            if (x < 0) { pc('-'); x = -x; }
            if (!x) { pc('0'); return *this; }
            static char stk[40]; int top = 0;
            while (x) { stk[++top] = (x % 10) ^ 48; x /= 10; }
            while (top) pc(stk[top--]);
            return *this;
        }

        // 支持输出单个字符
        inline FastOut& operator<<(char c) {
            pc(c);
            return *this;
        }

        // 支持输出 C 风格字符串
        inline FastOut& operator<<(const char* s) {
            while (*s) pc(*s++);
            return *this;
        }

        // 支持输出 std::string
        inline FastOut& operator<<(const std::string& s) {
            for (char c : s) pc(c);
            return *this;
        }
    } fout; // 实例化为 fout,代替 cout
}
using FastIO::fin;
using FastIO::fout;
// ---------------- 模板结束 ----------------


// 测试与使用示例
int main() {
    int a;
    long long b;
    std::string s;

    // 完美复刻 cin 的链式调用
    fin >> a >> b >> s;

    // 完美复刻 cout 的链式调用
    fout << "The sum is: " << a + b << '\n';
    fout << "The string is: " << s << '\n';

    // 甚至可以写循环
    // int n; fin >> n;
    // for(int i=0; i<n; ++i) { ... }

    return 0; // 程序结束时自动触发 fout 的析构函数,保证最后的数据被 flush 到屏幕
}
原文