1. 数据结构模板
注意
不要使用 STL!
1.1 基础线性容器
1.1.1 B3614 【模板】栈
1.1.2 B3616 【模板】队列
1.2 单调优化线性容器
1.2.1 P5788【模板】单调栈
暂无模板代码1.2.2 P1886【模板】单调队列
暂无模板代码1.3 堆(优先队列)
1.3.1 P3378 【模板】堆
1.4 Trie 字典树
1.4.1 基础 Trie
暂无模板代码2. 图论模板
2.1 最短路
2.1.1 B3647 【模板】
// 邻接矩阵
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记录
注意:这里可以使用朴素 ,但是 离 更近,所以选择堆优化的 ,当然, 也行。
#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;
}本代码复杂度:
本题弱化版:P3371 【模板】单源最短路径(弱化版)(这道题 更接近 ,所以选择朴素 )。
2.2
2.2.1 强连通分量
暂无模板代码2.2.2 缩点
暂无模板代码3. IO工具模板
3.1 快速读入
前置(程序缓冲区的getchar):
// 缓冲区
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 【模板】快速读入(整数)
// 在这里加上前置
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;
}但我们通常会像下面这样写:
#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 缓冲区,所以只能应付 的数据(关于此的教训)。对于本题 数据,需要采用开头的 fread 一次性读入缓冲区方案。
3.1.2 快速读入字符串
// 在这里加上前置
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 输出
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 快速输出整型
#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');
}迭代版防栈溢出:
#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 在逻辑前加上这两句就可以了:
import sys
sys.set_int_max_str_digits(0)
# 其实就是解除字符串长度限制
# 因为 input() 读进来是字符串,而 Python 原生支持大整数
# 所以只需要保证读进来的字符串不被截断就可以了555为什么这么少,不像其他语言还要字符串/数组
4.2 C++高精度
5. 字符串算法模板
5.1 模式串匹配
5.1.1 KMP 单模式串匹配
暂无模板代码5.1.2 AC自动机 多模式串匹配
暂无模板代码6. 数论模板
6.1 快速幂
6.1.1 普通取模快速幂
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;
}特别的,如果传入的 或者没有传入 ,那么将不会取模。
6.1.2 浮点快速幂
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
暂无模板代码但我们通常可能会这样写:
暂无模板代码上述代码复杂度为 。
但代码中,还有一处可以优化:
用 去筛掉 时,
我们发现:
- 的话,其一定被 给筛掉了。
- 而 也一定被 筛掉了。
所以我们不需要从 开始筛,直接从 开始筛即可(必须满足 ),于是可以优化为开头的代码
6.3.3 线性筛/欧拉筛
暂无模板代码6.3.4 分块筛
暂无模板代码6.4 CRT/中国剩余定理
6.4.1 朴素CRT
暂无模板代码6.4.2 exCRT/扩展中国剩余定理
暂无模板代码7. DP 模板
7.1 数位 DP
#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 算法竞赛极限卡常(保留浮点精度)
#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 极速数值计算专用
#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=gbk8.4 文件初始缺省源
// 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 完成后人工进行了格式修复。