跳到正文

个人记录

模板-缺省源

#SUSPENDED#约 22 分钟
原文
文章信息与版本

文章信息

发布
2025年12月20日
收录
2026年6月16日
更新
2026年11月17日
篇幅
约 22 分钟
获赞
1

版本

  1. v4当前
  2. v3
  3. v2
  4. v1
1. 数据结构模板

注意

不要使用 STL!

1.1 基础线性容器
1.2 单调优化线性容器
1.2.1 P5788【模板】单调栈
代码
暂无模板代码
1.2.2 P1886【模板】单调队列
代码
暂无模板代码
1.3 堆(优先队列)
1.4 Trie 字典树
1.4.1 基础 Trie
代码
暂无模板代码

2. 图论模板

2.1 最短路
2.1.1 B3647 【模板】Floyd\text{Floyd}

AC记录

C++
// 邻接矩阵
for(int k=1;k<=n;k++){
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			G[i][j]=min(G[i][j],G[i][k]+G[k][j]);
			G[j][i]=G[i][j];// 有向图删除此行
		}
	}
}

练习:

2.1.2 P4779 【模板】单源最短路径(标准版)

AC记录
注意:这里可以使用朴素 Dijkstra\text{Dijkstra},但是 mm 离 nn 更近,所以选择堆优化的 Dijkstra\text{Dijkstra},当然,SPFA\text{SPFA} 也行。

C++
#include<bits/stdc++.h>
using namespace std;
const int INF=(1LL<<31)-1;
const int MAXN=1e5+5,MAXM=2e5+5;

struct edge{
	int v,w;
	edge(){}
	edge(int v_,int w_){ v=v_;w=w_; }
};

vector<edge> G[MAXN];

int* heap_dijkstra(const int& s,const int& count){ // 堆优化的 Dijkstra
	struct Edge_Compare{ bool operator()(edge a,edge b){ return a.w>b.w; } };
	priority_queue<edge,vector<edge>,Edge_Compare> pq;
	int n=count+1;
	int *dis=new int[n+5];
	bool *vis=new bool[n+5];
	for(int i=0;i<=n;i++) dis[i]=INF,vis[i]=false;
	dis[s]=0;
	pq.emplace(s,dis[s]);
	while(!pq.empty()){
		int cu=pq.top().v;
		int d=pq.top().w;
		pq.pop();
		if(vis[cu]) continue;
		vis[cu]=1;
		for(const auto& e:G[cu]){
			if(dis[e.v]>d+e.w){
				dis[e.v]=d+e.w;
				pq.emplace(e.v,dis[e.v]);
			}
		}
	}
	return dis;
}

本代码复杂度:O(nlog⁡m)O(n \log m)

本题弱化版:P3371 【模板】单源最短路径(弱化版)(这道题 mm 更接近 n2n^2,所以选择朴素 Dijkstra\text{Dijkstra})。

2.2 Tarjan\textrm{Tarjan}
2.2.1 强连通分量
代码
暂无模板代码
2.2.2 缩点
代码
暂无模板代码

3. IO工具模板

3.1 快速读入

前置(程序缓冲区的getchar):

C++
// 缓冲区
const int BUF_SIZE = 1 << 25; // 如果MLE可以把25改成22,20
char inbuf[BUF_SIZE]; // 避免输出缓冲区重名
int pin = 0, lenin = 0;

// 一次性填充缓冲区版 getchar
inline char gc() {
	if (pin == lenin) { // inbuf 中已经没有数据可读
		lenin = fread(inbuf, 1, BUF_SIZE, stdin); // 从 stdin 一次性读入
		pin = 0;
		if (!lenin) return EOF;
	}
	return inbuf[pin++]; // 后续直接返回 inbuf 中的内容,不使用 stdin
}

// 判断是否空白字符
inline bool isws(char c){
	return c == ' ' || c == '\r' || c == '\n' || c == '\t' || c == '\v';
}

// 跳过空白字符
inline void skws(){
	char c;
	while ((c=gc()) != EOF && isws(c));
	// 非空白字符放回缓冲区
	if (c != EOF) pin--;
}
WARNING

如果本地测试时,程序一直在等待输入(光标不停闪烁且可以输入),那么请使用 Ctrl+D(Linux)/Ctrl+Z(Windows) 终止输入(即键入 EOF 标志)。
一定要换一行! 不然会出现许多玄学问题(比如导致答案与预期不同,但程序其实没有问题,然后调半天,尤其是这种需要单字符读入的!)

3.1.1 P10815 【模板】快速读入(整数)

AC记录

C++
// 在这里加上前置

inline bool is_digit(char c){
	return '0' <= c && c <= '9';
}
inline long long read_int() {
	long long res = 0;
	skws();
	char c = gc();
	bool neg = false;
	if (c == '-'){
		neg = true;
		c = gc();
	}
	while (is_digit(c)) {
		res = (res << 3) + (res << 1) + (c ^ 48); // 位运算优化
		c = gc();
	}
	if (c != EOF) pin--;
	return neg ? -res : res;
}

但我们通常会像下面这样写:

C++
#include<cstdio>
inline long long read() {
	long long res = 0;
	char c = getchar();
	bool f = false;
	while (c == ' ' || c == '\n' || c == '\r' || c == '\t')
			c = getchar();
	if (c == '-') {
			f = true;
			c = getchar();
	}
	while (c >= '0' && c <= '9') {
			res = res * 10 + (c - '0');
			c = getchar();
	}
	return f ? -res : res;
}

但该代码使用 getchar 单字符读入,每次读入都需要访问 stdin 缓冲区,所以只能应付 10610^6 的数据(关于此的教训)。对于本题 10810^8 数据,需要采用开头的 fread 一次性读入缓冲区方案。

3.1.2 快速读入字符串
C++
// 在这里加上前置

inline string read_str() {
	skws();
	vector<char> buf;
	buf.reserve(1024); // 预分配初始容量减少扩容
	char c;
	while ((c = gc()) != EOF && !isws(c)) {
		buf.push_back(c);
	}
	if (c != EOF) pin--;
	return string(buf.begin(), buf.end());
}
3.2 快速输出
3.2.1 __int128 输出
C++
inline void write(__int128_t n){ // 有符号 __int128
	if(n < 0){
		putchar('-');
		n = -n;
	}
	if(n > 9) write(n / 10);
	putchar(n % 10 + '0');
}
inline void write(__uint128_t n){ // 无符号 __int128
	if(n > 9) write(n / 10);
	putchar(n % 10 + '0');
}

需要注意的是,__int128 类型是 GCC 扩展,在洛谷和 NOI 系列比赛中可用,但不保证部分 OJ 或环境(如 MSVC)可用。

3.2.2 快速输出整型
C++
#include <type_traits>
template<typename T>
inline void write(T x) {
	// 判断是否是无符号类型
	constexpr bool is_uns = std::is_unsigned<T>::value;
	if (!is_uns) {
		if (x < 0) {
			putchar('-');
			// 转无符号避免负数取模溢出
			x = -static_cast<typename std::make_unsigned<T>::type>(x);
		}
	}
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
}

迭代版防栈溢出:

C++
#include <type_traits>
#include <algorithm> // swap

template<typename T>
inline void write(T x) {
	constexpr bool uns = std::is_unsigned<T>::value;
	// 临时存数字字符,足够容纳64位整数最多20位
	char tmp[32];
	int top = 0;

	// 负数符号处理
	if (!uns) {
		if (x < 0) {
			putchar('-');
			x = -static_cast<typename std::make_unsigned<T>::type>(x);
		}
	}

	// 逆序拆分数字存入tmp
	do {
		tmp[top++] = static_cast<char>((x % 10) + '0');
		x /= 10;
	} while (x);

	// 逆序输出,还原正确数字顺序
	for (int i = top - 1; i >= 0; --i) {
		putchar(tmp[i]);
	}
}
3.2.3 快速输出字符串
代码
暂无模板代码

4. 高精度计算模板

4.1 Python 高精度

Python 在逻辑前加上这两句就可以了:

Python
import sys
sys.set_int_max_str_digits(0)
# 其实就是解除字符串长度限制
# 因为 input() 读进来是字符串,而 Python 原生支持大整数
# 所以只需要保证读进来的字符串不被截断就可以了

555为什么这么少,不像其他语言还要字符串/数组

4.2 C++高精度

也可以直接用我的 bint 类

4.2.1 字符串存储高精度数字
代码
暂无模板代码
4.2.2 整型数组存储高精度数字
代码
暂无模板代码

5. 字符串算法模板

5.1 模式串匹配
5.1.1 KMP 单模式串匹配
代码
暂无模板代码
5.1.2 AC自动机 多模式串匹配
代码
暂无模板代码

6. 数论模板

6.1 快速幂
6.1.1 普通取模快速幂
C++
long long qpow(long long a,long long b,long long mod=0) {
	long long ans=1;
	if(mod) a%=mod;
	while(b){
		if(b&1) ans=(__int128)ans*a;
		if(mod) ans%=mod;
		a=(__int128)a*a;
		if(mod) a%=mod;
		b>>=1;
	}
	return ans;
}

特别的,如果传入的 mod=0mod=0 或者没有传入 modmod,那么将不会取模。

6.1.2 浮点快速幂
C++
long double qpow(long double a,long long b) {
	long double ans=1;
	while(b){
		if(b&1) ans=ans*a;
		a=a*a;
		b>>=1;
	}
	return ans;
}
6.2 GCD/欧几里得算法
6.2.1 朴素GCD
代码
暂无模板代码
6.2.2 exGCD/扩展欧几里得算法
代码
暂无模板代码
6.2.3 乘法逆元
代码
暂无模板代码
6.3 素数筛
6.3.1 普通筛法
代码
暂无模板代码
6.3.2 埃氏筛/埃拉托色尼筛法/Eratosthenes Sieve
代码
暂无模板代码

但我们通常可能会这样写:

代码
暂无模板代码

上述代码复杂度为 O(nlog⁡log⁡n)O(n \log \log n)。
但代码中,还有一处可以优化:

用 ii 去筛掉 2i,3i,4i…2i, 3i, 4i\dots 时,
我们发现:

  • 2i≤n2i \le n 的话,其一定被 22 给筛掉了。
  • 而 3i3i 也一定被 33 筛掉了。
    所以我们不需要从 2i2i 开始筛,直接从 i2i^2 开始筛即可(必须满足 i2≤ni^2 \le n),于是可以优化为开头的代码
6.3.3 线性筛/欧拉筛
代码
暂无模板代码
6.3.4 分块筛
代码
暂无模板代码
6.4 CRT/中国剩余定理
6.4.1 朴素CRT
代码
暂无模板代码
6.4.2 exCRT/扩展中国剩余定理
代码
暂无模板代码

7. DP 模板
7.1 数位 DP
C++
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const int MAXDIG=20,MAXST=25,MAXPRE=20;
int dig[MAXDIG];
// dp[pos]   [state][pre]
ll dp[MAXDIG][MAXST][MAXPRE];
ll dfs(int pos,int st,int pre,bool lim,bool lead0){
	// 边界
	if(pos==0)
		return 1;
	
	// 使用记忆化结果
	if(!lim && !lead0 && dp[pos][st][pre]!=-1)
		return dp[pos][st][pre];
	
	ll res=0;
	int maxlim=lim?dig[pos]:9; // 当前位限制
	for(int i=0;i<=maxlim;i++){
		bool nlim=lim&&(i==maxlim);
		bool nlead0=lead0&&!i;
		int npos=pos-1;
		int nst=st/* 根据题意修改 */;
		int npre=nlead0?-1:i;
		
		if(i==4 || (pre==6 && i==2)) continue;
		
		res+=dfs(npos,nst,npre,nlim,nlead0);
	}
	
	// 加入记忆化
	if(!lim && !lead0)
		dp[pos][st][pre]=res;
	return res;
}
ll calc(ll x){
	// 拆分 x
	int len=0;
	while(x){
		dig[++len]=x%10;
		x/=10;
	}
	
	return dfs(len,0,-1,true,true);
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	memset(dp,-1,sizeof(dp));
	ll l,r;
	cin>>l>>r;
	cout<<calc(r)-calc(l-1)<<'\n';
}

8. 其他模板
8.1 算法竞赛极限卡常(保留浮点精度)
C++
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,inline")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,sse4.1,sse4.2,avx,f16c,tune=native")
8.2 极速数值计算专用
C++
#pragma GCC optimize("Ofast,no-stack-protector,fast-math,unroll-loops,inline")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,sse4.1,sse4.2,avx,f16c,tune=native")
WARNING

洛谷通过 修改 GCC 禁用了 #pragma 和 __attribute__ 打开优化,所以如有这两个的代码会直接 CE。

8.3 体积缩小编译指令
代码
-Wl,--gc-sections -Wl,--strip-all -Wl,--discard-all -Wl,-e,WinMainCRTStartup -fno-exceptions -fno-rtti -fno-unwind-tables -fno-asynchronous-unwind-tables -fexec-charset=gbk
8.4 文件初始缺省源
C++
// C++ std
#include<bits/stdc++.h>
using namespace std;
// GNU pb_ds
#include<bits/extc++.h>
using namespace __gnu_cxx;
using namespace __gnu_pbds;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
}

AI 声明

本文章初次写作完成后使用 DeepSeek(实则豆包) 进行文字润色与格式规范修正,在 AI 完成后人工进行了格式修复。

原文