版本比较
trick
正文
增加 339 行删除 179 行
1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118911912012112212312415161718192021125126127128129130131132133241341351362728291371381391401411421431441451461471481491503515115215315415520 行未改动1761771781791801811826667686970717273747576777879801831841851863 行未改动1901911921939293194195196197198199200201202203204205206207208962092109821121221321410121521621721821929 行未改动2492502512522532542552562571412582592602612622632642652662671502682692702712721531541551561571581592732742752762772782792802812821632832842852861661671682872882892902912922931712942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233246 行未改动331332333334186187188189335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376194195196197198199200377378379380204205206207208209210211212213214215381382383384385386220221222223224225387388389390391392227228229230393394395396397398399400401234402403404405406407408409410411412413414415416417418245419420421422423424249425426427251428429430431255256257258259260261262432433264434435266436437438439440441442443268444445446447448449270450451272452453454455456457458459274460461276277462463464465466467468281469470471472473474475285476477287288289290478479480481294295296482483298484485486487488301489490491303304305306492493494308495496497310311312313314315316317498499319320321322323324325326327328329330331332333334500501502503504505336506507508509510511512513339340341342343344345346347348349350351352353354355356357358359360361362363364514515516517518367519520369370371521522373374523524525526527376377378379528529530531532533534381535536537538539540541542素数计数函数 $\pi(n) \sim \frac {n} {\ln n}$# [欢迎来我的新博客玩](https://dk-qwq.github.io/blog/)
# 常用 ACM 算法竞赛笔记与模板(整理版)---## 目录
- [环境与 IO](#环境与-io) - [标准输入 输出 重定向](#标准输入--输出-重定向)
- [常用模板与输入加速](#常用模板与输入加速) - [Template](#template) - [快读](#快读)
- [随机 生成 校验工具](#随机--生成--校验工具) - [Python 生成与校验](#python生成与校验)
- [数据结构 DSU BIT multiset fenwick](#数据结构-dsu--bit--multiset--fenwick) - [带权并查集](#带权并查集) - [二维树状数组 fenwick](#二维树状数组fenwick) - [multiset 常见用法与效率提示](#multiset-常见用法与效率提示)
- [图论与最小生成树 MST 桥](#图论与最小生成树-mst--桥) - [桥 割边 的性质](#桥割边的性质) - [1 到 n 路径与桥的关系](#1--n-路径与桥的关系)
- [数论与位运算技巧](#数论与位运算技巧) - [异或前缀性质](#异或前缀性质) - [k平方模3性质](#性质) - [计数某一位为1的快速方法](#计数某一位为-1-的快速方法-计算区间)
- [距离变换 曼哈顿 切比雪夫](#距离变换曼哈顿与切比雪夫常用技巧)
- [哈希与模数表](#哈希与模数表)
- [C20 ranges STL 小技巧](#c20-ranges--stl--小技巧) - [内存占用估算技巧](#内存占用估算技巧) - [Python 技巧](#python-技巧) - [views](#views) - [生成下一个排列](#生成下一个排列字典序) - [常用 debug 宏](#常用-debug-宏) - [unordered_map pair 哈希](#unordered_map-pair-哈希)
- [常见数学结论 快查](#常见数学结论快查)
- [代码片段速查](#代码片段速查零散但常用) - [C++ 随机数](#c-随机数可复现--不可复现) - [pair 哈希](#pair-哈希) - [清空容器](#清空容器swap-trick)
- [实用命令](#实用命令) - [测时](#测时)
- [AI持续维护Prompt](#AI持续维护Prompt)
- [返回目录](#返回目录)
---
# 环境与 IO
## 标准输入 / 输出 重定向
#### 说明
* PowerShell **不支持** `<` 作为 stdin 重定向(与 CMD 不同)。
#### 示例
```powershell# PowerShell — 方式 1:使用管道Get-Content in.txt -Raw | A.exe > out.txt
# PowerShell — 方式 2:调用 cmd(/C 表示执行指定的命令后关闭命令提示符窗口)cmd /c "A.exe < in.txt > out.txt"```
```bash# Linux / 通用./A.exe < in.txt > out.txt```
---
# 常用模板与输入加速
### Template
```cpp#include <bits/stdc++.h>using namespace std;using ll = long long;const int N = 2e5 + 5;string s;int n;void solve() {
}int main() { ios::sync_with_stdio(false); cin.tie(nullptr), cout.tie(nullptr); freopen("A.in", "r", stdin); // freopen("A.out", "w", stdout); int T = 1; // cin >> T; while(T--) solve();}```
### 快读
```cpp#include<iostream>#include<cstdio>#include<vector>using namespace std;namespace INPUT{ char buf[1<<20],*p1,*p2; char buf[1 << 20], *p1, *p2; #define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)}using namespace INPUT;template<typename T>inline T read(){ T x=0,p=1; char ch=gc(); for(;ch<'0'||ch>'9';ch=gc()) if(ch=='-') p=-1; for(;ch>='0'&&ch<='9';ch=gc()) x=(x<<3)+(x<<1)+(ch^48); return x*p; T x = 0, p = 1; char ch = gc(); for(; ch < '0' || ch > '9'; ch = gc()) if(ch == '-') p = -1; for(;ch >= '0' && ch <= '9'; ch = gc()) x = (x<<3) + (x<<1) + (ch^48); return x * p;}void solve(){ // ...}int main(){ freopen("A.in","r",stdin); freopen("A.out","w",stdout); int T=read<int>(); freopen("A.in", "r", stdin); freopen("A.out", "w", stdout); int T = read<int>(); while(T--) solve();}```
---
# 随机 / 生成 / 校验工具
### Python:生成与校验
```python# check.py# check.py: 用于检查输出是否满足某些序列条件(示例)inFile = open("A.in", "r")outFile = open("A.out", "r")
n = int(inFile.readline())20 行未改动 open("A.ans", "w").write("True")```
```python# 简单数据生成器import random
random.randint(l, r)random.choice(list)random.sample(list, k)random.shuffle(list)
f = open("data.in", "w")
with open("data.in", "w") as f: f.write("...\n") print("...", file = f)```
```pythonimport random
def gen(n, m): print(n, m) for _ in range(n): print(random.randint(1, 1000), end=' ')3 行未改动 gen(10, 5)```
```pythonp = list(range(1, n+1)) #生成 permutationrandom.shuffle(p)import random
random.randint(l, r)random.choice(list)random.sample(list, k)random.shuffle(list)
# f = open("data.in", "w")with open("data.in", "w") as f: f.write("...\n") print("...", file = f)# f.close()```---
对于 $G = (V, E) $ 有最小生成树 $T = (V, E')$ ,那么 $G' = (V \cup V_{new}, E \cup V_{new})$ 的最小生成树的边集 $E_{T'} \cap (E \setminus E') = \empty$ ,也就是说加入新点可在原最小生成树上做# 数据结构 DSU / BIT / multiset / fenwick
`python中可以直接使用 pow(x, k, mod) ,不需要导入任何库`## 带权并查集
```cpp// 带权并查集(a[x] = a[y] + d; 模 M)struct DSU { // 带权并查集struct DSU { std::vector<size_t> pa, size, dist;
explicit DSU(size_t size_) : pa(size_), size(size_, 1), dist(size_) { std::iota(pa.begin(), pa.end(), 0);29 行未改动 }};```
---
## 二维树状数组(Fenwick)
```cppstruct fenwick{ //二维树状数组struct fenwick{ // 二维树状数组 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)) c[i][j] += v; }};```
---
` #define debug(a) cout<<#a<<"="<<a<<endl; `## multiset 常见用法与效率提示
* 查找某值:`s.find(val)` — 推荐用于判断存在性(**不要**用 `count` 在 multiset 上查元素的存在性:`multiset::count()` 的复杂度为 `O(k + log n)`,其中 `k` 为该值出现的次数)。* 删除:
```cppstd::map<int, std::string> mp = {{1, "a"}, {2, "b"}, {3, "c"}}; // 反向迭代mapfor (auto&& [k, v] : std::views::reverse(std::views::all(map))) { ... }for (auto&& [k, v] : mp | rv::all | rv::reverse) std::cout << k << " " << v << "\n";```对于长度分别为 $l_1, l_2, \dots, l_m$ 的 $m$ 根小木棍,这 $m$ 根小木棍能拼成一个多边形当且仅当 $m \geq 3$ 且 $\sum_{i=1}^{m} l_i > 2 \times \max_{i=1}^{m} l_i$。 * `s.erase(val)` 删除所有等值元素(C++11 以后返回删除个数) * `s.erase(it)` 删除迭代器 * `s.erase(s.find(val))` 删除单个点* 最小/最大:
* `*s.begin()` 最小值 * `*prev(s.end())` 最大值
---
`Measure-Command {A.exe}` powershell 测程序运行时间# 图论与最小生成树 (MST) / 桥
## 桥(割边)的性质
```cppfor (auto i : views::iota(1, n + 1)) {}```### 1 → n 路径与桥的关系
首先,我们将所有位于 **任意一条从 $1$ 到 $n$ 的路径上的边**的集合记作 $A$。接着,找出图中的所有 **桥(割边)**,将这些边的集合记作 $B$。然后,任选一条从 $1$ 到 $n$ 的简单路径,将路径上的边的集合记作 $P$。那么:$ B \cap P = A$
$ O(1) $ 计算区间2进制第 $k$ 位为 $1$ 的整数个数
> 对图 $G=(V,E)$,若 $T=(V,E')$ 是 $G$ 的一棵最小生成树,加入若干新点 $V_{new}$ 并连接若干边后,新图 $G'=(V\cup V_{new}, E\cup E_{new})$ 的最小生成树中,**不会使用原图中不在 $T$ 中的边**。>> 即:$E_{T'} \cap (E \setminus E') = \empty$。 >> 结论(简洁):也就是说加入新点可在原最小生成树上做
---
# 数论与位运算技巧
## 异或前缀性质($1 \oplus 2 \oplus \dots \oplus n$)
> 结论:>> * 若 $n \bmod 4 = 0$,则 $1 \oplus \dots \oplus n = n$。> * 若 $n \bmod 4 = 1$,则 $1 \oplus \dots \oplus n = 1$。> * 若 $n \bmod 4 = 2$,则 $1 \oplus \dots \oplus n = n+1$。> * 若 $n \bmod 4 = 3$,则 $1 \oplus \dots \oplus n = 0$。
## $k^2 \bmod 3$ 性质
> 任意平方数关于模 3 的结果只可能是 0 或 1($k^2 \equiv 0\ \text{或}\ 1 \pmod 3$)。> 推论:任意平方数可表示为若干个 3 的和,或若干个 3 加上一个偶数(用于构造题目证明时)。
## 计数某一位为 1 的快速方法($O(1)$ 计算区间)
```pythondef count_up_to(x, k): """计算 [0, x] 中二进制第 k 位为 1 的整数个数""" if x < 0:6 行未改动
def query_range(l, r, k): """查询 [l, r] 中二进制第 k 位为 1 的整数个数""" return count_up_to(r, k) - count_up_to(l - 1, k)
# 示例测试print(query_range(0, 7, 1)) # 在 0..7 中第 1 位为 1 的个数print(query_range(1, 1e18, 50)) # 大数计算```
---
# 距离变换:曼哈顿与切比雪夫(常用技巧)
* 曼哈顿距离:$dis(A, B) = |x_1 - x_2| + |y_1 - y_2|$* 切比雪夫距离:$dis(A, B) = \max(|x_1 - x_2|, |y_1 - y_2|)$
> 转换技巧:>> * 将 $(x,y) \mapsto (x+y, x-y)$,则原坐标系中的 **曼哈顿距离** 等于新坐标系中的 **切比雪夫距离**。>>* 将 $(x,y) \mapsto \left(\dfrac{x+y}{2},\dfrac{x-y}{2}\right)$,则原坐标系中的 **切比雪夫距离** 等于新坐标系中的 **曼哈顿距离**。
---
# 哈希与模数表
| 类型 | 模数 (mod) | 常用基数 (base) | 说明 || ------- | ------------------------- | ------------------- | -------------- || 单模数常用 | 1,000,000,007 (1e9+7) | 131, 137, 911382323 | 经典,OJ 通用 || 单模数常用 | 1,000,000,009 (1e9+9) | 131, 233, 911382323 | 常和 1e9+7 搭配 || 单模数常用 | 998,244,353 | 61, 107, 131, 233 | NTT 质数,代码里常见 || 双模数组合 | (1e9+7, 1e9+9) | (131, 137) | 最经典的双模哈希 || 双模数组合 | (998244353, 1e9+7) | (233, 911382323) | 抗碰撞性更高 || 64位自然溢出 | 2^64 (unsigned long long) | 随机奇数 \~ 1e5..1e9 | 无需取模,溢出即模 2^64 |
---
# C++20 ranges / STL / 小技巧
## 内存占用估算技巧计算空间,所有变量定义之前`bool Be;` 之后`bool Ed;`, 然后输出:`cout << ((&Be - &Ed) >> 20) << endl;` 就是使用变量的总空间,单位为 MB (可能cout的时候需要调换Be,Ed的位置,原因:大端小端)
## Python 技巧
python中可以直接使用 `pow(x, k, mod)` ,不需要导入任何库
## views
```cpp// ranges::partition_point的使用// check 在 range 内需要满足单调性, 先 true 后 false,所以有时可能得反转 check 返回值,需结合题目。int n = 5;std::vector<int> v{1, 3, 4, 2, 6};auto odd = [&](int x) { return x % 2 == 1;};for (auto i : views::iota(1, n + 1)) {}
auto p = std::ranges::partition_point(v, odd);std::cout << *p << '\n';// p 是 v[2] 的迭代器, output v[2] 的内容 4// 需注意这里如果 v 全是奇数,则会返回 v.end()
auto check = [&](int idx) { return v[idx] % 2 == 1;};int bound = *std::ranges::partition_point(std::ranges::iota_view(0, n), check);std::cout << bound << '\n';// bound = 2,对应第一个下标// 注意 iota_view 是一个 O(1) 的虚拟范围, 所以 iota_view(0, 10^9) 是 ok 的,可以用来二分答案// 由于 iota_view 区间是左闭右开, 使用时最好传入 iota_view(l, r + 1)// 二分答案再也不用担心 l r 调整错```
* `iota_view(0, 10^9)` 是虚拟范围,**O(1)** 表示无需构造实际容器,适合用于二分答案。* `partition_point` 要求 `check` 在范围内单调(先 `true` 后 `false`),必要时反转返回值。
```cpp#include <iostream>#include <random>using namespace std;// 用随机设备作为种子,保证每次运行不一样random_device rd; mt19937 gen(rd()); std::map<int, std::string> mp = {{1, "a"}, {2, "b"}, {3, "c"}}; // 反向迭代mapfor (auto&& [k, v] : std::views::reverse(std::views::all(map))) { ... }for (auto&& [k, v] : mp | rv::all | rv::reverse) std::cout << k << " " << v << "\n";```
// 或者用固定种子,保证结果可复现mt19937 gen2(42); uniform_int_distribution<int> dist(1, 6); // [1,6] 区间cout << dist(gen) << endl; // 模拟掷骰子## 生成下一个排列(字典序)
```cpp#include <algorithm>bool next_permutation(iterator start, iterator end);```
* 复杂度:**`O(n)`**(单次)
---## 常用 debug 宏
```cpp#define debug(a) cout<<#a<<"="<<a<<endl;```
## unordered_map pair 哈希
```cppstruct PairHash { size_t operator()(const std::pair<int,int>& p) const noexcept { return std::hash<long long>()(((long long)p.first << 32) ^ p.second); }};std::unordered_map<std::pair<int, int>, ll, PairHash> count;```
注意自己实现的hashMap性能不行,尽量不要用,用`std::unordered_map<int, std::unordered_map<int, ll> > ;`更好> ⚠️ 注意:自实现 hashmap 在性能上可能不如嵌套 `std::unordered_map<int, std::unordered_map<int, ll>>`,后者在很多场景更稳定。
---
# 常见数学结论(快查)
---* 素数计数函数:$\pi(n) \sim \dfrac{n}{\ln n}$。 * 多边形成立条件(给定边长能否构成多边形):
$$ w \in [1, B - 1], r = \lceil {\frac {B^2} {W}} \rceil \Rightarrow \text {r is diff}$$ > 若有 $m \ge 3$ 根边长 $l_1,\dots,l_m$,当且仅当 $\sum_{i=1}^{m} l_i > 2\max_i l_i$。
---
| 类型 | 模数 (mod) | 常用基数 (base) | 说明 || ------- | ------------------------- | ------------------- | -------------- || 单模数常用 | 1,000,000,007 (1e9+7) | 131, 137, 911382323 | 经典,OJ 通用 || 单模数常用 | 1,000,000,009 (1e9+9) | 131, 233, 911382323 | 常和 1e9+7 搭配 || 单模数常用 | 998,244,353 | 61, 107, 131, 233 | NTT 质数,代码里常见 || 双模数组合 | (1e9+7, 1e9+9) | (131, 137) | 最经典的双模哈希 || 双模数组合 | (998244353, 1e9+7) | (233, 911382323) | 抗碰撞性更高 || 64位自然溢出 | 2^64 (unsigned long long) | 随机奇数 \~ 1e5..1e9 | 无需取模,溢出即模 2^64 |# 代码片段速查(零散但常用)
---### C++ 随机数(可复现 / 不可复现)
首先,我们将所有位于 **任意一条从 $1$ 到 $n$ 的路径上的边**的集合记作 $A$。```cpp#include <iostream>#include <random>using namespace std;// 用随机设备作为种子random_device rd; mt19937 gen(rd());
接着,找出图中的所有 **桥(割边)**,将这些边的集合记作 $B$。// 或者用固定种子mt19937 gen2(42); uniform_int_distribution<int> dist(1, 6); // [1,6] 区间cout << dist(gen) << endl; // 模拟掷骰子```
然后,任选一条从 $1$ 到 $n$ 的简单路径,将路径上的边的集合记作 $P$。### pair 哈希
那么:$$ B \cap P = A$$```cppstruct PairHash { size_t operator()(const std::pair<int,int>& p) const noexcept { return std::hash<long long>()(((long long)p.first << 32) ^ p.second); }};```
---### 清空容器(swap trick)
$$\text{若存在函数 }f(x) \text{ 使得 } \forall x \in Z , f(x) \in Z$$$$\text{则有 } {\lceil f(x) \rceil}={\lceil f(\lceil x \rceil) \rceil},{\lfloor f(x) \rfloor}={\lfloor f(\lfloor x \rfloor) \rfloor}$$```cpptemplate<typename T>void clear(T& v){ T().swap(v); }```
---
$ f(i)=preA[i]+preB[z−i] $ 是单峰的($A[i],B[i] > 0 $)# 实用命令
## 测时PowerShell:`Measure-Command {A.exe}` 测程序运行时间(PowerShell 专用)。
---
$ n=2^k ( k \geq 2 ) $ 的时候 $1 \oplus \dots \oplus (n-1) = 0$# 返回目录
- 如果 $n \pmod 4 = 0$,则 $1 \oplus \dots \oplus n = n$。- 如果 $n \pmod 4 = 1$,则 $1 \oplus \dots \oplus n = 1$。- 如果 $n \pmod 4 = 2$,则 $1 \oplus \dots \oplus n = n+1$。- 如果 $n \pmod 4 = 3$,则 $1 \oplus \dots \oplus n = 0$。* [回到顶部](#常用-acm-算法竞赛笔记与模板整理版)
---
$$ O ( \sum_{d = 1} ^m \frac {1} {d} ) = O (log m) $$# AI持续维护Prompt
---### ✅ Prompt 1(推荐长期使用)
```text你是 ACM 算法竞赛 Markdown 笔记的结构维护助手。
1. 清空(queue等)下面是我当前笔记的【完整多层目录结构】,请你严格基于该目录来判断我新增内容的插入位置。
```cpptemplate<typename T>void clear(T& v){T().swap(v);}```【目录结构】(粘贴当前 md 的完整多层目录,包括一级 / 二级 / 三级)
2. 可重集multiset的使用【我新增的内容】(粘贴新的算法、结论、模板或技巧)
```cppmultiset::find(val)//查值multiset::erase(val)//删值multiset::erase(it)//删迭代器multiset::erase(find(val))//删点(*multiset::begin())//min_val(*prev(multiset::end()))//max_val```请你按以下格式输出,并且【每一层都要写全】:
```cpppair<ll,ll> solve(vector<ll>& a,ll w){//一段序列中匹配一对数对和中大于w的 for(auto v:a) s.insert(v); ll res=0,Max=0; while(s.size()>=2){ auto l=s.begin(); auto it=s.lower_bound(w-(*l)); if(l==it) it++; if(it==s.end()) Max=max(Max,(*l)),s.erase(l); else res++,s.erase(l),s.erase(it); } while(!s.empty()) Max=max(Max,*(s.begin())),s.erase(s.begin()); return MP(res,Max);//返回匹配值与剩余最大值}```1️⃣ 推荐插入路径(从一级到最深层):- 一级标题:- 二级标题:- 三级标题(若无则写“无”):- 四级标题(若无则写“无”):
3. 加法操作和乘法操作复合的pushdown2️⃣ 是否需要新建标题:- 新建层级:(二级 / 三级 / 四级 / 不需要)- 原因说明:
3️⃣ 若存在多个可选位置:- 给出所有候选路径- 指出最推荐的一条,并说明理由
```cppvoid pushMu(int x,ll v){ if(!x) return ; LazyS[x]*=v; LazyMu[x]*=v; val[x]*=v;}void pushS(int x,ll v){ if(!x) return ; if(LazyMu[x]!=1){ pushMu(lc[x],LazyMu[x]),pushMu(rc[x],LazyMu[x]); LazyMu[x]=1; } LazyS[x]+=v; val[x]+=v;}void pushdown(int x){//先乘上在加上 if(LazyMu[x]!=1){ pushMu(lc[x],LazyMu[x]),pushMu(rc[x],LazyMu[x]); LazyMu[x]=1; } if(LazyS[x]){ pushS(lc[x],LazyS[x]),pushS(rc[x],LazyS[x]); LazyS[x]=0; }}4️⃣ 若内容与现有笔记有重叠:- 指出应合并的具体小节- 或说明为何应独立成新小节```
4. prev---
```cpptemplate< class BidirIt >BidirIt prev( BidirIt it, typename std::iterator_traits<BidirIt>::difference_type n = 1 );### ✅ Prompt 2(高级维护用)
Return the n_th predecessor (or -nth successor if n is negative) of iterator it.``````text在完成本次插入位置判断后,请你基于我当前的 ACM Markdown 笔记结构,生成一个【可长期复用的 Prompt 模板】。
5. 生成给定序列的下一个字典序排列 $ O(n) $```cpp#include <algorithm>bool next_permutation(iterator start, iterator end);要求该 Prompt:1️⃣ 适用于 ACM / ICPC / CCPC 算法竞赛笔记2️⃣ 能基于【多层目录结构】判断插入位置3️⃣ 要求输出完整路径(一级到最深层)4️⃣ 能判断是否需要新建二级 / 三级 / 四级标题5️⃣ 输出结果必须结构化、可直接执行
template< class BidirIt, class Compare >bool next_permutation( BidirIt first, BidirIt last, Compare comp );请直接输出 Prompt 正文,不要解释,不要举例。```
---
# 返回目录
* [回到顶部](#常用-acm-算法竞赛笔记与模板整理版)