├── .gitignore ├── chapter-1 ├── exec │ └── lowbit.cpp ├── 5-24-template.md └── 5-17-template.md ├── chapter-4 ├── 7-6-template.md ├── 6-21-template.md └── 7-5-template.md ├── chapter-3 ├── 6-08-template.md ├── 6-02-template.md ├── 6-15-template.md ├── 6-07-template.md └── 6-14-template.md ├── README.md ├── chapter-2 └── 5-25-template.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | -------------------------------------------------------------------------------- /chapter-1/exec/lowbit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | /** 6 | * 位运算常用模版: 7 | * 1. n 的二进制中第 K 位是几? 8 | * - 先把第 K 位移动到最后一位:n >> k 9 | * - 看个位是几:n >> k & 1 10 | * 2. lowbit:返回 x 最后一位 1 (树状数组的依赖操作) 11 | * - x & (-x) 12 | * - (-x) 是 x 的补码 -> (-x = ~x + 1) [x取反 + 1] 13 | * 作用: 14 | * 1. 可以统计一个数里面有多少个1 15 | */ 16 | int lowbit(int x) { 17 | return x & (-x); 18 | } 19 | 20 | int n; 21 | int main() { 22 | cin >> n; 23 | while (n--) { 24 | int x; 25 | cin >> x; 26 | 27 | int res = 0; 28 | while (x != 0) { 29 | x -= lowbit(x); 30 | res++; 31 | } 32 | 33 | cout << res << " "; 34 | } 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /chapter-1/5-24-template.md: -------------------------------------------------------------------------------- 1 | # 第三讲 2 | 3 | ## 位运算 4 | 5 | - 求n的第k位数字: 6 | 7 | ```c++ 8 | n >> k & 1 9 | ``` 10 | 11 | - 返回n的最后一位1: 12 | 13 | ```c++ 14 | lowbit(n) = n & -n 15 | ``` 16 | 17 | ## 双指针 18 | 19 | ```c++ 20 | for (int i = 0, j = 0; i < n; i ++ ) { 21 | while (j < i && check(i, j)) j ++ ; 22 | 23 | // 具体问题的逻辑 24 | } 25 | ``` 26 | 27 | 常见问题分类: 28 | 29 | - 对于一个序列,用两个指针维护一段区间 30 | - 对于两个序列,维护某种次序,比如归并排序中合并两个有序序列的操作 31 | 32 | ## 离散化 33 | 34 | ```c++ 35 | vector alls; // 存储所有待离散化的值 36 | sort(alls.begin(), alls.end()); // 将所有值排序 37 | alls.erase(unique(alls.begin(), alls.end()), alls.end()); // 去掉重复元素 38 | 39 | // 二分求出x对应的离散化的值 40 | int find(int x) { 41 | int l = 0, r = alls.size() - 1; 42 | while (l < r) { 43 | int mid = l + r >> 1; 44 | if (alls[mid] >= x) r = mid; 45 | else l = mid + 1; 46 | } 47 | return r + 1; 48 | } 49 | ``` 50 | 51 | ## 区间合并 52 | 53 | ```c++ 54 | // 将所有存在交集的区间合并 55 | void merge(vector &segs) { 56 | vector res; 57 | 58 | sort(segs.begin(), segs.end()); 59 | 60 | int st = -2e9, ed = -2e9; 61 | for (auto seg : segs) 62 | if (ed < seg.first) { 63 | if (st != -2e9) res.push_back({st, ed}); 64 | st = seg.first, ed = seg.second; 65 | } else 66 | ed = max(ed, seg.second); 67 | 68 | if (st != -2e9) res.push_back({st, ed}); 69 | 70 | segs = res; 71 | } 72 | ``` 73 | 74 | -------------------------------------------------------------------------------- /chapter-4/7-6-template.md: -------------------------------------------------------------------------------- 1 | # 第十三讲 2 | 3 | ## NIM游戏 4 | 5 | > 给定N堆物品,第i堆物品有Ai个。两名玩家轮流行动,每次可以任选一堆,取走任意多个物品,可把一堆取光,但不能不取。取走最后一件物品者获胜。两人都采取最优策略,问先手是否必胜。 6 | > 我们把这种游戏称为NIM博弈。把游戏过程中面临的状态称为局面。整局游戏第一个行动的称为先手,第二个行动的称为后手。若在某一局面下无论采取何种行动,都会输掉游戏,则称该局面必败。 7 | > 所谓采取最优策略是指,若在某一局面下存在某种行动,使得行动后对面面临必败局面,则优先采取该行动。同时,这样的局面被称为必胜。我们讨论的博弈问题一般都只考虑理想情况,即两人均无失误,都采取最优策略行动时游戏的结果。 8 | > NIM博弈不存在平局,只有先手必胜和先手必败两种情况。 9 | > 10 | > 定理: NIM博弈先手必胜,当且仅当 A1 ^ A2 ^ ... ^ An != 0 11 | 12 | ## 公平组合游戏ICG 13 | 14 | 若一个游戏满足: 15 | 1. 由两名玩家交替行动; 16 | 17 | 2. 在游戏进程的任意时刻,可以执行的合法行动与轮到哪名玩家无关; 18 | 19 | 3. 不能行动的玩家判负; 20 | 21 | NIM博弈属于公平组合游戏,但城建的棋类游戏,比如围棋,就不是公平组合游戏。因为围棋交战双方分别只能落黑子和白子,胜负判定也比较复杂,不满足条件2和条件3。 22 | 23 | 24 | ## 有向图游戏 25 | 26 | 给定一个有向无环图,图中有一个唯一的起点,在起点上放有一枚棋子。两名玩家交替地把这枚棋子沿有向边进行移动,每次可以移动一步,无法移动者判负。该游戏被称为有向图游戏。 27 | 28 | 任何一个公平组合游戏都可以转化为有向图游戏。具体方法是,把每个局面看成图中的一个节点,并且从每个局面向沿着合法行动能够到达的下一个局面连有向边。 29 | 30 | ## Mex运算 31 | 32 | 设S表示一个非负整数集合。定义mex(S)为求出不属于集合S的最小非负整数的运算,即: 33 | `mex(S) = min{x}, x属于自然数,且x不属于S` 34 | 35 | ## SG函数 36 | 37 | 在有向图游戏中,对于每个节点x,设从x出发共有k条有向边,分别到达节点y1, y2, ..., yk,定义SG(x)为x的后继节点y1, y2, ..., yk 的SG函数值构成的集合再执行mex(S)运算的结果,即: 38 | `SG(x) = mex({SG(y1), SG(y2), ..., SG(yk)})` 39 | 特别地,整个有向图游戏G的SG函数值被定义为有向图游戏起点s的SG函数值,即`SG(G) = SG(s)`。 40 | 41 | ## 有向图游戏的和 42 | 43 | 设G1, G2, ..., Gm 是m个有向图游戏。定义有向图游戏G,它的行动规则是任选某个有向图游戏Gi,并在Gi上行动一步。G被称为有向图游戏G1, G2, ..., Gm的和。 44 | 有向图游戏的和的SG函数值等于它包含的各个子游戏SG函数值的异或和,即: 45 | `SG(G) = SG(G1) ^ SG(G2) ^ ... ^ SG(Gm)` 46 | 47 | **定理** 48 | 49 | 1. 有向图游戏的某个局面必胜,当且仅当该局面对应节点的SG函数值大于0。 50 | 2. 有向图游戏的某个局面必败,当且仅当该局面对应节点的SG函数值等于0。 -------------------------------------------------------------------------------- /chapter-3/6-08-template.md: -------------------------------------------------------------------------------- 1 | # 第七讲 2 | 3 | ## 树与图 4 | 5 | ### 存储 6 | 7 | > 树是一种特殊的图,与图的存储方式相同。 8 | > 对于无向图中的边ab,存储两条有向边a->b, b->a。 9 | > 因此我们可以只考虑有向图的存储。 10 | 11 | - **邻接矩阵:** 12 | 13 | ```c++ 14 | g[a][b] 存储边a->b 15 | ``` 16 | 17 | - **邻接表:** 18 | 19 | ```c++ 20 | // 对于每个点k,开一个单链表,存储k所有可以走到的点。h[k]存储这个单链表的头结点 21 | int h[N], e[N], ne[N], idx; 22 | 23 | // 添加一条边a->b 24 | void add(int a, int b) { 25 | e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ; 26 | } 27 | ``` 28 | 29 | ### 遍历 30 | 31 | - **深度优先遍历** 32 | 33 | ```c++ 34 | int dfs(int u) { 35 | st[u] = true; // st[u] 表示点u已经被遍历过 36 | 37 | for (int i = h[u]; i != -1; i = ne[i]) 38 | { 39 | int j = e[i]; 40 | if (!st[j]) dfs(j); 41 | } 42 | } 43 | ``` 44 | 45 | - **宽度优先遍历** 46 | 47 | ```c++ 48 | queue q; 49 | st[1] = true; // 表示1号点已经被遍历过 50 | q.push(1); 51 | 52 | while (q.size()) { 53 | int t = q.front(); 54 | q.pop(); 55 | 56 | for (int i = h[t]; i != -1; i = ne[i]) { 57 | int j = e[i]; 58 | if (!s[j]) { 59 | st[j] = true; // 表示点j已经被遍历过 60 | q.push(j); 61 | } 62 | } 63 | } 64 | ``` 65 | 66 | ## 拓扑排序 67 | 68 | ```c++ 69 | bool topsort() { 70 | int hh = 0, tt = -1; 71 | 72 | // d[i] 存储点i的入度 73 | for (int i = 1; i <= n; i ++ ) 74 | if (!d[i]) 75 | q[ ++ tt] = i; 76 | 77 | while (hh <= tt) { 78 | int t = q[hh ++ ]; 79 | 80 | for (int i = h[t]; i != -1; i = ne[i]) { 81 | int j = e[i]; 82 | if (-- d[j] == 0) 83 | q[ ++ tt] = j; 84 | } 85 | } 86 | 87 | // 如果所有点都入队了,说明存在拓扑序列;否则不存在拓扑序列。 88 | return tt == n - 1; 89 | } 90 | ``` 91 | 92 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # algorithm-basic 2 | > **算法模板** **From** [https://www.acwing.com/activity/content/11/]() 3 | 4 | ```diff 5 | ! 非官方整理 6 | ``` 7 | 8 | ## chapter-1 9 | 10 | > **Content:** 11 | > 12 | > - [经典算法](https://github.com/hanxuanliang/algorithm-basic/blob/master/chapter-1/5-17-template.md#%E7%BB%8F%E5%85%B8%E6%8E%92%E5%BA%8F) 13 | > - [二分](https://github.com/hanxuanliang/algorithm-basic/blob/master/chapter-1/5-17-template.md#%E4%BA%8C%E5%88%86) 14 | > - [高精度](https://github.com/hanxuanliang/algorithm-basic/blob/master/chapter-1/5-17-template.md#%E9%AB%98%E7%B2%BE%E5%BA%A6%E9%97%AE%E9%A2%98) 15 | > - [前缀和和差分](https://github.com/hanxuanliang/algorithm-basic/blob/master/chapter-1/5-17-template.md#%E5%89%8D%E7%BC%80%E5%92%8C) 16 | > - [位运算](https://github.com/hanxuanliang/algorithm-basic/blob/master/chapter-1/5-24-template.md#%E4%BD%8D%E8%BF%90%E7%AE%97) 17 | > - [双指针](https://github.com/hanxuanliang/algorithm-basic/blob/master/chapter-1/5-24-template.md#%E5%8F%8C%E6%8C%87%E9%92%88) 18 | > - [离散化](https://github.com/hanxuanliang/algorithm-basic/blob/master/chapter-1/5-24-template.md#%E7%A6%BB%E6%95%A3%E5%8C%96) 19 | > - [区间合并](https://github.com/hanxuanliang/algorithm-basic/blob/master/chapter-1/5-24-template.md#%E5%8C%BA%E9%97%B4%E5%90%88%E5%B9%B6) 20 | 21 | ## 更多推荐 22 | 23 | - [@extrovert]() 算法刷题题解 24 | 25 | 传送门:[https://github.com/pkuzengqi/Algorithm_and_More]() 26 | 27 | ## 感谢 28 | 29 | 感谢 [yxc]() 站长 [熊博士]()管理员 30 | 31 | :punch: 出品自 **[Acwing]()©** 32 | 33 | -------------------------------------------------------------------------------- /chapter-2/5-25-template.md: -------------------------------------------------------------------------------- 1 | # 第4讲 2 | 3 | ## 单链表 4 | 5 | > ```c++ 6 | > // head存储链表头,e[]存储节点的值,ne[]存储节点的next指针,idx表示当前用到了哪个节点 7 | > int head, e[N], ne[N], idx; 8 | > ``` 9 | 10 | ### 初始化 11 | 12 | ```c++ 13 | // 初始化 14 | void init() { 15 | head = -1; 16 | idx = 0; 17 | } 18 | ``` 19 | 20 | ### 插入 21 | 22 | ```c++ 23 | // 在链表头插入一个数a 24 | void insert(int a) { 25 | e[idx] = a, ne[idx] = head, head = idx ++ ; 26 | } 27 | ``` 28 | 29 | ### 删除 30 | 31 | ```c++ 32 | // 将头结点删除,需要保证头结点存在 33 | void remove() 34 | { 35 | head = ne[head]; 36 | } 37 | ``` 38 | 39 | ## 双链表 40 | 41 | > ```c++ 42 | > // e[]表示节点的值,l[]表示节点的左指针,r[]表示节点的右指针,idx表示当前用到了哪个节点 43 | > int e[N], l[N], r[N], idx; 44 | > ``` 45 | 46 | ### 初始化 47 | 48 | ```c++ 49 | // 初始化 50 | void init() { 51 | //0是左端点,1是右端点 52 | r[0] = 1, l[1] = 0; 53 | idx = 2; 54 | } 55 | ``` 56 | 57 | ### 插入 58 | 59 | ```c++ 60 | // 在节点a的右边插入一个数x 61 | void insert(int a, int x) { 62 | e[idx] = x; 63 | l[idx] = a, r[idx] = r[a]; 64 | l[r[a]] = idx, r[a] = idx ++ ; 65 | } 66 | ``` 67 | 68 | ### 删除 69 | 70 | ```c++ 71 | // 删除节点a 72 | void remove(int a) { 73 | l[r[a]] = l[a]; 74 | r[l[a]] = r[a]; 75 | } 76 | ``` 77 | 78 | ## 栈 79 | 80 | ```c++ 81 | // tt表示栈顶 82 | int stk[N], tt = 0; 83 | 84 | // 向栈顶插入一个数 85 | stk[ ++ tt] = x; 86 | 87 | // 从栈顶弹出一个数 88 | tt -- ; 89 | 90 | // 栈顶的值 91 | stk[tt]; 92 | 93 | // 判断栈是否为空 94 | if (tt > 0) { 95 | 96 | } 97 | ``` 98 | 99 | ## 队列 100 | 101 | ```c++ 102 | // hh 表示队头,tt表示队尾 103 | int q[N], hh = 0, tt = -1; 104 | 105 | // 向队尾插入一个数 106 | q[ ++ tt] = x; 107 | 108 | // 从队头弹出一个数 109 | hh ++ ; 110 | 111 | // 队头的值 112 | q[hh]; 113 | 114 | // 判断队列是否为空 115 | if (hh <= tt) { 116 | 117 | } 118 | ``` 119 | 120 | ## 单调栈 121 | 122 | > 常见模型:找出每个数左边离它最近的比它大/小的数 123 | 124 | ```c++ 125 | int tt = 0; 126 | for (int i = 1; i <= n; i ++ ) { 127 | while (tt && check(q[tt], i)) tt -- ; 128 | stk[ ++ tt] = i; 129 | } 130 | ``` 131 | 132 | ## 单调队列 133 | 134 | > 常见模型:找出滑动窗口中的最大值/最小值 135 | 136 | ```c++ 137 | int hh = 0, tt = -1; 138 | for (int i = 0; i < n; i ++ ) { 139 | while (hh <= tt && check_out(q[hh])) hh ++ ; // 判断队头是否滑出窗口 140 | while (hh <= tt && check(q[tt], i)) tt -- ; 141 | q[ ++ tt] = i; 142 | } 143 | ``` 144 | 145 | ## KMP 146 | 147 | - **求Next数组:** 148 | 149 | ```c++ 150 | // s[]是模式串,p[]是模板串, n是s的长度,m是p的长度 151 | for (int i = 2, j = 0; i <= m; i ++ ) { 152 | while (j && p[i] != p[j + 1]) j = ne[j]; 153 | if (p[i] == p[j + 1]) j ++ ; 154 | ne[i] = j; 155 | } 156 | ``` 157 | 158 | - **匹配:** 159 | 160 | ```c++ 161 | for (int i = 1, j = 0; i <= n; i ++ ) { 162 | while (j && s[i] != p[j + 1]) j = ne[j]; 163 | if (s[i] == p[j + 1]) j ++ ; 164 | if (j == m) 165 | { 166 | j = ne[j]; 167 | // 匹配成功后的逻辑 168 | } 169 | } 170 | ``` 171 | 172 | -------------------------------------------------------------------------------- /chapter-3/6-02-template.md: -------------------------------------------------------------------------------- 1 | # 第五讲 2 | 3 | ## Trie 树 4 | 5 | ```c++ 6 | int son[N][26], cnt[N], idx; 7 | // 0号点既是根节点,又是空节点 8 | // son[][]存储树中每个节点的子节点 9 | // cnt[]存储以每个节点结尾的单词数量 10 | 11 | // 插入一个字符串 12 | void insert(char *str) { 13 | int p = 0; 14 | for (int i = 0; str[i]; i ++ ) { 15 | int u = str[i] - 'a'; 16 | if (!son[p][u]) son[p][u] = ++ idx; 17 | p = son[p][u]; 18 | } 19 | cnt[p] ++ ; 20 | } 21 | 22 | // 查询字符串出现的次数 23 | int query(char *str) { 24 | int p = 0; 25 | for (int i = 0; str[i]; i ++ ) { 26 | int u = str[i] - 'a'; 27 | if (!son[p][u]) return 0; 28 | p = son[p][u]; 29 | } 30 | return cnt[p]; 31 | } 32 | ``` 33 | 34 | ## 并查集 35 | 36 | - **朴素并查集:** 37 | 38 | ```c++ 39 | int p[N]; //存储每个点的祖宗节点 40 | 41 | // 返回x的祖宗节点 42 | int find(int x) { 43 | if (p[x] != x) p[x] = find(p[x]); 44 | return p[x]; 45 | } 46 | 47 | // 初始化,假定节点编号是1~n 48 | for (int i = 1; i <= n; i ++ ) p[i] = i; 49 | 50 | // 合并a和b所在的两个集合: 51 | p[find(a)] = find(b); 52 | ``` 53 | 54 | - **维护size的并查集:** 55 | 56 | ```c++ 57 | int p[N], size[N]; 58 | //p[]存储每个点的祖宗节点, size[]只有祖宗节点的有意义,表示祖宗节点所在集合中的点的数量 59 | 60 | // 返回x的祖宗节点 61 | int find(int x) { 62 | if (p[x] != x) p[x] = find(p[x]); 63 | return p[x]; 64 | } 65 | 66 | // 初始化,假定节点编号是1~n 67 | for (int i = 1; i <= n; i ++ ) { 68 | p[i] = i; 69 | size[i] = 1; 70 | } 71 | 72 | // 合并a和b所在的两个集合: 73 | p[find(a)] = find(b); 74 | size[b] += size[a]; 75 | 76 | ``` 77 | 78 | - **维护到祖宗节点距离的并查集:** 79 | 80 | ```c++ 81 | int p[N], d[N]; 82 | //p[]存储每个点的祖宗节点, d[x]存储x到p[x]的距离 83 | 84 | // 返回x的祖宗节点 85 | int find(int x) { 86 | if (p[x] != x) 87 | { 88 | int u = find(p[x]); 89 | d[x] += d[p[x]]; 90 | p[x] = u; 91 | } 92 | return p[x]; 93 | } 94 | 95 | // 初始化,假定节点编号是1~n 96 | for (int i = 1; i <= n; i ++ ) { 97 | p[i] = i; 98 | d[I] = 0; 99 | } 100 | 101 | // 合并a和b所在的两个集合: 102 | p[find(a)] = find(b); 103 | d[find(a)] = distance; // 根据具体问题,初始化find(a)的偏移量 104 | ``` 105 | 106 | ## 堆 107 | 108 | ```c++ 109 | // h[N]存储堆中的值, h[1]是堆顶,x的左儿子是2x, 右儿子是2x + 1 110 | // ph[k]存储第k个插入的点在堆中的位置 111 | // hp[k]存储堆中下标是k的点是第几个插入的 112 | int h[N], ph[N], hp[N], size; 113 | 114 | // 交换两个点,及其映射关系 115 | void heap_swap(int a, int b) { 116 | swap(ph[hp[a]],ph[hp[b]]); 117 | swap(hp[a], hp[b]); 118 | swap(h[a], h[b]); 119 | } 120 | 121 | void down(int u) { 122 | int t = u; 123 | if (u * 2 <= size && h[u * 2] < h[t]) t = u * 2; 124 | if (u * 2 + 1 <= size && h[u * 2 + 1] < h[t]) t = u * 2 + 1; 125 | if (u != t) 126 | { 127 | heap_swap(u, t); 128 | down(t); 129 | } 130 | } 131 | 132 | void up(int u) { 133 | while (u / 2 && h[u] < h[u / 2]) 134 | { 135 | heap_swap(u, u / 2); 136 | u >>= 1; 137 | } 138 | } 139 | 140 | // O(n)建堆 141 | for (int i = n / 2; i; i -- ) down(i); 142 | ``` 143 | 144 | -------------------------------------------------------------------------------- /chapter-3/6-15-template.md: -------------------------------------------------------------------------------- 1 | # 第九讲 2 | 3 | ## prim算法 4 | 5 | ```c++ 6 | int n; // n表示点数 7 | int g[N][N]; // 邻接矩阵,存储所有边 8 | int dist[N]; // 存储其他点到当前最小生成树的距离 9 | bool st[N]; // 存储每个点是否已经在生成树中 10 | 11 | 12 | // 如果图不连通,则返回INF(值是0x3f3f3f3f), 否则返回最小生成树的树边权重之和 13 | int prim() { 14 | memset(dist, 0x3f, sizeof dist); 15 | 16 | int res = 0; 17 | for (int i = 0; i < n; i ++ ) { 18 | int t = -1; 19 | for (int j = 1; j <= n; j ++ ) 20 | if (!st[j] && (t == -1 || dist[t] > dist[j])) 21 | t = j; 22 | 23 | if (i && dist[t] == INF) return INF; 24 | 25 | if (i) res += dist[t]; 26 | st[t] = true; 27 | 28 | for (int j = 1; j <= n; j ++ ) dist[j] = min(dist[j], g[t][j]); 29 | } 30 | 31 | return res; 32 | } 33 | ``` 34 | 35 | ## Kruskal算法 36 | 37 | ```c++ 38 | int n, m; // n是点数,m是边数 39 | int p[N]; // 并查集的父节点数组 40 | 41 | // 存储边 42 | struct Edge { 43 | int a, b, w; 44 | bool operator< (const Edge &W)const { 45 | return w < W.w; 46 | } 47 | } edges[M]; 48 | 49 | // 并查集核心操作 50 | int find(int x) { 51 | if (p[x] != x) p[x] = find(p[x]); 52 | return p[x]; 53 | } 54 | 55 | int kruskal() { 56 | sort(edges, edges + m); 57 | 58 | for (int i = 1; i <= n; i ++ ) p[i] = i; // 初始化并查集 59 | 60 | int res = 0, cnt = 0; 61 | for (int i = 0; i < m; i ++ ) { 62 | int a = edges[i].a, b = edges[i].b, w = edges[i].w; 63 | 64 | a = find(a), b = find(b); 65 | // 如果两个连通块不连通,则将这两个连通块合并 66 | if (a != b) { 67 | p[a] = b; 68 | res += w; 69 | cnt ++ ; 70 | } 71 | } 72 | 73 | if (cnt < n - 1) return INF; 74 | return res; 75 | } 76 | ``` 77 | 78 | ## 染色法判别二分图 79 | 80 | ```c++ 81 | int n; // n表示点数 82 | int h[N], e[M], ne[M], idx; // 邻接表存储图 83 | int color[N]; // 表示每个点的颜色,-1表示为染色,0表示白色,1表示黑色 84 | 85 | // 参数:u表示当前节点,father表示当前节点的父节点(防止向树根遍历),c表示当前点的颜色 86 | bool dfs(int u, int father, int c) { 87 | color[u] = c; 88 | for (int i = h[u]; i != -1; i = ne[i]) { 89 | int j = e[i]; 90 | if (color[j] == -1) { 91 | if (!dfs(j, u, !c)) return false; 92 | } 93 | else if (color[j] == c) return false; 94 | } 95 | 96 | return true; 97 | } 98 | 99 | bool check() { 100 | memset(color, -1, sizeof color); 101 | bool flag = true; 102 | for (int i = 1; i <= n; i ++ ) 103 | if (color[i] == -1) 104 | if (!dfs(i, -1, 0)) { 105 | flag = false; 106 | break; 107 | } 108 | return flag; 109 | } 110 | 111 | ``` 112 | 113 | ## 匈牙利算法 114 | 115 | ```c++ 116 | int n; // n表示点数 117 | int h[N], e[M], ne[M], idx; // 邻接表存储所有边 118 | int match[N]; // 存储每个点当前匹配的点 119 | bool st[N]; // 表示每个点是否已经被遍历过 120 | 121 | bool find(int x) { 122 | for (int i = h[x]; i != -1; i = ne[i]) { 123 | int j = e[i]; 124 | if (!st[j]) { 125 | st[j] = true; 126 | if (match[j] == 0 || find(match[j])) { 127 | match[j] = x; 128 | return true; 129 | } 130 | } 131 | } 132 | return false; 133 | } 134 | 135 | // 求最大匹配数 136 | int res = 0; 137 | for (int i = 1; i <= n; i ++ ) { 138 | memset(st, false, sizeof st); 139 | if (find(i)) res ++ ; 140 | } 141 | ``` 142 | 143 | -------------------------------------------------------------------------------- /chapter-4/6-21-template.md: -------------------------------------------------------------------------------- 1 | 第十讲 2 | 3 | ## 试除法判定质数 4 | 5 | ```c++ 6 | bool is_prime(int x) { 7 | if (x < 2) return false; 8 | for (int i = 2; i <= x / i; i ++ ) 9 | if (x % i == 0) 10 | return false; 11 | return true; 12 | } 13 | ``` 14 | 15 | ## 试除法分解质因数 16 | 17 | ```c++ 18 | void divide(int x) { 19 | for (int i = 2; i <= x / i; i ++ ) 20 | if (x % i == 0) { 21 | int s = 0; 22 | while (x % i == 0) x /= i, s ++ ; 23 | cout << i << ' ' << s << endl; 24 | } 25 | if (x > 1) cout << x << ' ' << 1 << endl; 26 | cout << endl; 27 | } 28 | ``` 29 | 30 | ## 朴素筛法求素数 31 | 32 | ```c++ 33 | int primes[N], cnt; // primes[]存储所有素数 34 | bool st[N]; // st[x]存储x是否被筛掉 35 | 36 | void get_primes(int n) { 37 | for (int i = 2; i <= n; i ++ ) { 38 | if (st[i]) continue; 39 | primes[cnt ++ ] = i; 40 | for (int j = i; j <= n; j += i) 41 | st[j] = true; 42 | } 43 | } 44 | ``` 45 | 46 | ## 线性筛法求素数 47 | 48 | ```c++ 49 | int primes[N], cnt; // primes[]存储所有素数 50 | bool st[N]; // st[x]存储x是否被筛掉 51 | 52 | void get_primes(int n) { 53 | for (int i = 2; i <= n; i ++ ) { 54 | if (!st[i]) primes[cnt ++ ] = i; 55 | for (int j = 0; primes[j] <= n / i; j ++ ) { 56 | st[primes[j] * i] = true; 57 | if (i % primes[j] == 0) break; 58 | } 59 | } 60 | } 61 | ``` 62 | 63 | ## 试除法求所有约数 64 | 65 | ```c++ 66 | vector get_divisors(int x) { 67 | vector res; 68 | for (int i = 1; i <= x / i; i ++ ) 69 | if (x % i == 0) { 70 | res.push_back(i); 71 | if (i != x / i) res.push_back(x / i); 72 | } 73 | sort(res.begin(), res.end()); 74 | return res; 75 | } 76 | ``` 77 | 78 | ## 约数个数和约数之和 79 | 80 | > 如果 `N = p1^c1 * p2^c2 * ... *pk^ck` 81 | > 约数个数: `(c1 + 1) * (c2 + 1) * ... * (ck + 1)` 82 | > 约数之和:` (p1^0 + p1^1 + ... + p1^c1) * ... * (pk^0 + pk^1 + ... + pk^ck)` 83 | 84 | ## 欧几里得算法 85 | 86 | ```c++ 87 | int gcd(int a, int b) { 88 | return b ? gcd(b, a % b) : a; 89 | } 90 | ``` 91 | 92 | ## 求欧拉函数 93 | 94 | ```c++ 95 | int phi(int x) { 96 | int res = x; 97 | for (int i = 2; i <= x / i; i ++ ) 98 | if (x % i == 0) { 99 | res = res / i * (i - 1); 100 | while (x % i == 0) x /= i; 101 | } 102 | if (x > 1) res = res / x * (x - 1); 103 | 104 | return res; 105 | } 106 | 107 | ``` 108 | 109 | ## 筛法求欧拉函数 110 | 111 | ```c++ 112 | int primes[N], cnt; // primes[]存储所有素数 113 | int euler[N]; // 存储每个数的欧拉函数 114 | bool st[N]; // st[x]存储x是否被筛掉 115 | 116 | 117 | void get_eulers(int n) { 118 | euler[1] = 1; 119 | for (int i = 2; i <= n; i ++ ) { 120 | if (!st[i]) { 121 | primes[cnt ++ ] = i; 122 | euler[i] = i - 1; 123 | } 124 | for (int j = 0; primes[j] <= n / i; j ++ ) { 125 | int t = primes[j] * i; 126 | st[t] = true; 127 | if (i % primes[j] == 0) { 128 | euler[t] = euler[i] * primes[j]; 129 | break; 130 | } 131 | euler[t] = euler[i] * (primes[j] - 1); 132 | } 133 | } 134 | } 135 | ``` 136 | 137 | ## 快速幂 138 | 139 | > 求 `m^k mod p`,时间复杂度 `O(logk)`。 140 | 141 | ```c++ 142 | int qmi(int m, int k, int p) { 143 | int res = 1, t = m; 144 | while (k) { 145 | if (k&1) res = res * t % p; 146 | t = t * t % p; 147 | k >>= 1; 148 | } 149 | return res; 150 | } 151 | ``` 152 | 153 | ## 扩展欧几里得算法 154 | 155 | ```c++ 156 | // 求x, y,使得ax + by = gcd(a, b) 157 | int exgcd(int a, int b, int &x, int &y) { 158 | if (!b) { 159 | x = 1; y = 0; 160 | return a; 161 | } 162 | int d = exgcd(b, a % b, y, x); 163 | y -= (a/b) * x; 164 | return d; 165 | } 166 | ``` 167 | 168 | -------------------------------------------------------------------------------- /chapter-3/6-07-template.md: -------------------------------------------------------------------------------- 1 | # 第六讲 2 | 3 | ## Hash 4 | 5 | - **一般Hash:** 6 | 7 | > **(1) 拉链法** 8 | 9 | ```c++ 10 | int h[N], e[N], ne[N], idx; 11 | 12 | // 向哈希表中插入一个数 13 | void insert(int x) { 14 | int k = (x % N + N) % N; 15 | e[idx] = x; 16 | ne[idx] = h[k]; 17 | h[k] = idx ++ ; 18 | } 19 | 20 | // 在哈希表中查询某个数是否存在 21 | bool find(int x) { 22 | int k = (x % N + N) % N; 23 | for (int i = h[k]; i != -1; i = ne[i]) 24 | if (e[i] == x) 25 | return true; 26 | 27 | return false; 28 | } 29 | ``` 30 | 31 | > **(2) 开放寻址法** 32 | 33 | ```c++ 34 | int h[N]; 35 | 36 | // 如果x在哈希表中,返回x的下标;如果x不在哈希表中,返回x应该插入的位置 37 | int find(int x) { 38 | int t = (x % N + N) % N; 39 | while (h[t] != null && h[t] != x) 40 | { 41 | t ++ ; 42 | if (t == N) t = 0; 43 | } 44 | return t; 45 | } 46 | ``` 47 | 48 | > **字符串哈希** 49 | > 50 | > > 核心思想:将字符串看成P进制数,P的经验值是131或13331,取这两个值的冲突概率低 51 | > > 小技巧:取模的数用2^64,这样直接用unsigned long long存储,溢出的结果就是取模的结果 52 | 53 | ```c++ 54 | typedef unsigned long long ULL; 55 | ULL h[N], p[N]; // h[k]存储字符串前k个字母的哈希值, p[k]存储 P^k mod 2^64 56 | 57 | // 初始化 58 | p[0] = 1; 59 | for (int i = 1; i <= n; i ++ ) { 60 | h[i] = h[i - 1] * P + str[i]; 61 | p[i] = p[i - 1] * P; 62 | } 63 | 64 | // 计算子串 str[l ~ r] 的哈希值 65 | ULL get(int l, int r) { 66 | return h[r] - h[l - 1] * p[r - l + 1]; 67 | } 68 | ``` 69 | 70 | ## STL简介 71 | 72 | > **vector, 变长数组,倍增的思想** 73 | 74 | ```c++ 75 | size() 返回元素个数 76 | empty() 返回是否为空 77 | clear() 清空 78 | front()/back() 79 | push_back()/pop_back() 80 | begin()/end() 81 | [] 82 | 支持比较运算,按字典序 83 | ``` 84 | 85 | 86 | > **pair** 87 | 88 | ```c++ 89 | first, 第一个元素 90 | second, 第二个元素 91 | 支持比较运算,以first为第一关键字,以second为第二关键字(字典序) 92 | ``` 93 | 94 | > **string,字符串** 95 | 96 | ```c++ 97 | szie()/length() 返回字符串长度 98 | empty() 99 | clear() 100 | substr(起始下标,(子串长度)) 返回子串 101 | c_str() 返回字符串所在字符数组的起始地址 102 | ``` 103 | 104 | > **queue, 队列** 105 | 106 | ```c++ 107 | size() 108 | push() 向队尾插入一个元素 109 | front() 返回队头元素 110 | back() 返回队尾元素 111 | pop() 弹出队头元素 112 | ``` 113 | 114 | > **priority_queue, 优先队列,默认是大根堆** 115 | 116 | ```c++ 117 | push() 插入一个元素 118 | top() 返回堆顶元素 119 | pop() 弹出堆顶元素 120 | 定义成小根堆的方式:priority_queue, greater> q; 121 | ``` 122 | 123 | > **stack, 栈** 124 | 125 | ```c++ 126 | size() 127 | empty() 128 | push() 向栈顶插入一个元素 129 | top() 返回栈顶元素 130 | pop() 弹出栈顶元素 131 | ``` 132 | 133 | > **deque, 双端队列** 134 | 135 | ```c++ 136 | size() 137 | empty() 138 | clear() 139 | front()/back() 140 | push_back()/pop_back() 141 | push_front()/pop_front() 142 | begin()/end() 143 | [] 144 | ``` 145 | 146 | > **set, map, multiset, multimap, 基于平衡二叉树(红黑树),动态维护有序序列** 147 | 148 | ```c++ 149 | size() 150 | empty() 151 | clear() 152 | begin()/end() 153 | ++, -- 返回前驱和后继,时间复杂度 O(logn) 154 | ``` 155 | 156 | - **set/multiset** 157 | 158 | ```c++ 159 | insert() 插入一个数 160 | find() 查找一个数 161 | count() 返回某一个数的个数 162 | erase() 163 | (1) 输入是一个数x,删除所有x O(k + logn) 164 | (2) 输入一个迭代器,删除这个迭代器 165 | lower_bound()/upper_bound() 166 | lower_bound(x) 返回大于等于x的最小的数的迭代器 167 | upper_bound(x) 返回大于x的最小的数的迭代器 168 | ``` 169 | 170 | - **map/multimap** 171 | 172 | ```c++ 173 | insert() 插入的数是一个pair 174 | erase() 输入的参数是pair或者迭代器 175 | find() 176 | [] 时间复杂度是 O(logn) 177 | lower_bound()/upper_bound() 178 | ``` 179 | 180 | > **unordered_set, unordered_map, unordered_multiset, unordered_multimap, 哈希表** 181 | 182 | ```c++ 183 | 和上面类似,增删改查的时间复杂度是 O(1) 184 | 不支持 lower_bound()/upper_bound(), 迭代器的++,-- 185 | ``` 186 | 187 | > **bitset, 圧位** 188 | 189 | ```c++ 190 | bitset<10000> s; 191 | ~, &, |, ^ 192 | >>, << 193 | ==, != 194 | [] 195 | 196 | count() 返回有多少个1 197 | 198 | any() 判断是否至少有一个1 199 | none() 判断是否全为0 200 | 201 | set() 把所有位置成1 202 | set(k, v) 将第k位变成v 203 | reset() 把所有位变成0 204 | flip() 等价于~ 205 | flip(k) 把第k位取反 206 | ``` 207 | 208 | -------------------------------------------------------------------------------- /chapter-4/7-5-template.md: -------------------------------------------------------------------------------- 1 | # 第十二讲 2 | 3 | ## 高斯消元 4 | 5 | ```c++ 6 | // a[N][N]是增广矩阵 7 | int gauss() { 8 | int c, r; 9 | for (c = 0, r = 0; c < n; c ++ ) { 10 | int t = r; 11 | for (int i = r; i < n; i ++ ) // 找到绝对值最大的行 12 | if (fabs(a[i][c]) > fabs(a[t][c])) 13 | t = i; 14 | 15 | if (fabs(a[t][c]) < eps) continue; 16 | 17 | for (int i = c; i <= n; i ++ ) swap(a[t][i], a[r][i]); // 将绝对值最大的行换到最顶端 18 | for (int i = n; i >= c; i -- ) a[r][i] /= a[r][c]; // 将当前上的首位变成1 19 | for (int i = r + 1; i < n; i ++ ) // 用当前行将下面所有的列消成0 20 | if (fabs(a[i][c]) > eps) 21 | for (int j = n; j >= c; j -- ) 22 | a[i][j] -= a[r][j] * a[i][c]; 23 | 24 | r ++ ; 25 | } 26 | 27 | if (r < n) { 28 | for (int i = r; i < n; i ++ ) 29 | if (fabs(a[i][n]) > eps) 30 | return 2; // 无解 31 | return 1; // 有无穷多组解 32 | } 33 | 34 | for (int i = n - 1; i >= 0; i -- ) 35 | for (int j = i + 1; j < n; j ++ ) 36 | a[i][n] -= a[i][j] * a[j][n]; 37 | 38 | return 0; // 有唯一解 39 | } 40 | ``` 41 | 42 | ## 递归法求组合数 43 | 44 | ```c++ 45 | // c[a][b] 表示从a个苹果中选b个的方案数 46 | for (int i = 0; i < N; i ++ ) 47 | for (int j = 0; j <= i; j ++ ) 48 | if (!j) c[i][j] = 1; 49 | else c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod; 50 | ``` 51 | 52 | ## 通过预处理逆元的方式求组合数 53 | 54 | 首先预处理出所有阶乘取模的余数fact[N],以及所有阶乘取模的逆元infact[N] 55 | 如果取模的数是质数,可以用费马小定理求逆元 56 | 57 | ```c++ 58 | // 快速幂模板 59 | int qmi(int a, int k, int p) { 60 | int res = 1; 61 | while (k) { 62 | if (k & 1) res = (LL)res * a % p; 63 | a = (LL)a * a % p; 64 | k >>= 1; 65 | } 66 | return res; 67 | } 68 | // 预处理阶乘的余数和阶乘逆元的余数 69 | fact[0] = infact[0] = 1; 70 | for (int i = 1; i < N; i ++ ) { 71 | fact[i] = (LL)fact[i - 1] * i % mod; 72 | infact[i] = (LL)infact[i - 1] * qmi(i, mod - 2, mod) % mod; 73 | } 74 | ``` 75 | 76 | ## Lucas定理 77 | 78 | > 若p是质数,则对于任意整数 `1 <= m <= n`,有: 79 | > `C(n, m) = C(n % p, m % p) * C(n / p, m / p) (mod p)` 80 | 81 | ```c++ 82 | // 快速幂模板 83 | int qmi(int a, int k) { 84 | int res = 1; 85 | while (k) { 86 | if (k & 1) res = (LL)res * a % p; 87 | a = (LL)a * a % p; 88 | k >>= 1; 89 | } 90 | return res; 91 | } 92 | 93 | // 通过定理求组合数C(a, b) 94 | int C(int a, int b) { 95 | int res = 1; 96 | for (int i = 1, j = a; i <= b; i ++, j -- ) { 97 | res = (LL)res * j % p; 98 | res = (LL)res * qmi(i, p - 2) % p; 99 | } 100 | return res; 101 | } 102 | 103 | int lucas(LL a, LL b) { 104 | if (a < p && b < p) return C(a, b); 105 | return (LL)C(a % p, b % p) * lucas(a / p, b / p) % p; 106 | } 107 | ``` 108 | 109 | ## 分解质因数法求组合数 110 | 111 | > 当我们需要求出组合数的真实值,而非对某个数的余数时,分解质因数的方式比较好用: 112 | > 1. 筛法求出范围内的所有质数 113 | > 2. 通过` C(a, b) = a! / b! / (a - b)! `这个公式求出每个质因子的次数。 n! 中p的次数是 `n / p + n / p^2 + n / p^3 + ...` 114 | > 3. 用高精度乘法将所有质因子相乘 115 | 116 | ```c++ 117 | int primes[N], cnt; // 存储所有质数 118 | int sum[N]; // 存储每个质数的次数 119 | bool st[N]; // 存储每个数是否已被筛掉 120 | 121 | // 线性筛法求素数 122 | void get_primes(int n){ 123 | for (int i = 2; i <= n; i ++ ) 124 | { 125 | if (!st[i]) primes[cnt ++ ] = i; 126 | for (int j = 0; primes[j] <= n / i; j ++ ) 127 | { 128 | st[primes[j] * i] = true; 129 | if (i % primes[j] == 0) break; 130 | } 131 | } 132 | } 133 | 134 | // 求n!中的次数 135 | int get(int n, int p) { 136 | int res = 0; 137 | while (n) 138 | { 139 | res += n / p; 140 | n /= p; 141 | } 142 | return res; 143 | } 144 | 145 | // 高精度乘低精度模板 146 | vector mul(vector a, int b) { 147 | vector c; 148 | int t = 0; 149 | for (int i = 0; i < a.size(); i ++ ) 150 | { 151 | t += a[i] * b; 152 | c.push_back(t % 10); 153 | t /= 10; 154 | } 155 | 156 | while (t) 157 | { 158 | c.push_back(t % 10); 159 | t /= 10; 160 | } 161 | 162 | return c; 163 | } 164 | 165 | get_primes(a); // 预处理范围内的所有质数 166 | 167 | // 求每个质因数的次数 168 | for (int i = 0; i < cnt; i ++ ) { 169 | int p = primes[i]; 170 | sum[i] = get(a, p) - get(b, p) - get(a - b, p); 171 | } 172 | 173 | vector res; 174 | res.push_back(1); 175 | 176 | // 用高精度乘法将所有质因子相乘 177 | for (int i = 0; i < cnt; i ++ ) 178 | for (int j = 0; j < sum[i]; j ++ ) 179 | res = mul(res, primes[i]); 180 | ``` 181 | 182 | ## 卡特兰数 183 | 184 | > 给定n个0和n个1,它们按照某种顺序排成长度为2n的序列,满足任意前缀中0的个数都不少于1的个数的序列的数量为: `Cat(n) = C(2n, n) / (n + 1)` -------------------------------------------------------------------------------- /chapter-1/5-17-template.md: -------------------------------------------------------------------------------- 1 | # 第一讲 2 | 3 | ## 经典排序 4 | 5 | ### 快速排序算法模板 6 | 7 | ```c++ 8 | void quick_sort(int q[], int l, int r) { 9 | if (l >= r) return; 10 | 11 | int i = l - 1, j = r + 1, x = q[l]; 12 | while (i < j) { 13 | do i ++ ; while (q[i] < x); 14 | do j -- ; while (q[j] > x); 15 | if (i < j) swap(q[i], q[j]); 16 | else break; 17 | } 18 | quick_sort(q, l, j), quick_sort(q, j + 1, r); 19 | } 20 | ``` 21 | 22 | ### 归并排序算法模板 23 | 24 | ```c++ 25 | void merge_sort(int q[], int l, int r) { 26 | if (l >= r) return; 27 | 28 | int mid = l + r >> 1; 29 | merge_sort(q, l, mid); 30 | merge_sort(q, mid + 1, r); 31 | 32 | int k = 0, i = l, j = mid + 1; 33 | while (i <= mid && j <= r) 34 | if (q[i] < q[j]) tmp[k ++ ] = q[i ++ ]; 35 | else tmp[k ++ ] = q[j ++ ]; 36 | 37 | while (i <= mid) tmp[k ++ ] = q[i ++ ]; 38 | while (j <= r) tmp[k ++ ] = q[j ++ ]; 39 | 40 | for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = tmp[j]; 41 | } 42 | ``` 43 | 44 | ## 二分 45 | 46 | ### 整数二分算法模板 47 | 48 | ```c++ 49 | // 检查x是否满足某种性质 50 | bool check(int x) { 51 | /* ... */ 52 | } 53 | ``` 54 | 55 | ```c++ 56 | // 区间[l, r]被划分成[l, mid]和[mid + 1, r]时使用: 57 | int bsearch_1(int l, int r) { 58 | while (l < r) { 59 | int mid = l + r >> 1; 60 | if (check(mid)) r = mid; // check()判断mid是否满足性质 61 | else l = mid + 1; 62 | } 63 | return l; 64 | } 65 | ``` 66 | 67 | ```C++ 68 | // 区间[l, r]被划分成[l, mid - 1]和[mid, r]时使用: 69 | int bsearch_2(int l, int r) { 70 | while (l < r) { 71 | int mid = l + r + 1 >> 1; 72 | if (check(mid)) l = mid; 73 | else r = mid - 1; 74 | } 75 | return l; 76 | } 77 | ``` 78 | 79 | ### 浮点数二分算法模板 80 | 81 | ```c++ 82 | bool check(double x) {/* ... */} // 检查x是否满足某种性质 83 | 84 | double bsearch_3(double l, double r) 85 | { 86 | const double eps = 1e-6; // eps 表示精度,取决于题目对精度的要求 87 | while (r - l > eps) 88 | { 89 | double mid = (l + r) / 2; 90 | if (check(mid)) r = mid; 91 | else l = mid; 92 | } 93 | return l; 94 | } 95 | ``` 96 | ## 高精度问题 97 | 98 | ### 高精度加法 99 | 100 | > `C = A + B, A >= 0, B >= 0` 101 | 102 | ```c++ 103 | vector add(vector &A, vector &B) { 104 | if (A.size() < B.size()) return add(B, A); 105 | 106 | vector C; 107 | int t = 0; 108 | for (int i = 0; i < A.size(); i ++ ) { 109 | t += A[i]; 110 | if (i < B.size()) t += B[i]; 111 | C.push_back(t % 10); 112 | t /= 10; 113 | } 114 | 115 | if (t) C.push_back(t); 116 | return C; 117 | } 118 | ``` 119 | 120 | ### 高精度减法 121 | 122 | > `C = A - B, 满足A >= B, A >= 0, B >= 0` 123 | 124 | ```c++ 125 | vector sub(vector &A, vector &B) { 126 | vector C; 127 | for (int i = 0, t = 0; i < A.size(); i ++ ) { 128 | t = A[i] - t; 129 | if (i < B.size()) t -= B[i]; 130 | C.push_back((t + 10) % 10); 131 | if (t < 0) t = 1; 132 | else t = 0; 133 | } 134 | 135 | while (C.size() > 1 && C.back() == 0) C.pop_back(); 136 | return C; 137 | } 138 | ``` 139 | 140 | ### 高精度乘低精度 141 | 142 | > `C = A * b, A >= 0, b > 0` 143 | 144 | ```c++ 145 | vector mul(vector &A, int b) { 146 | vector C; 147 | int t = 0; 148 | for (int i = 0; i < A.size() || t; i ++ ) { 149 | if (i < A.size()) t += A[i] * b; 150 | C.push_back(t % 10); 151 | t /= 10; 152 | } 153 | 154 | return C; 155 | } 156 | ``` 157 | 158 | ### 高精度除以低精度 159 | 160 | > `A / b = C ... r, A >= 0, b > 0` 161 | 162 | ```c++ 163 | vector div(vector &A, int b, int &r) { 164 | vector C; 165 | r = 0; 166 | for (int i = A.size() - 1; i >= 0; i -- ) 167 | { 168 | r = r * 10 + A[i]; 169 | C.push_back(r / b); 170 | r %= b; 171 | } 172 | reverse(C.begin(), C.end()); 173 | while (C.size() > 1 && C.back() == 0) C.pop_back(); 174 | return C; 175 | } 176 | ``` 177 | 178 | ## 前缀和 179 | 180 | ### 一维前缀和 181 | 182 | ```c++ 183 | S[i] = a[1] + a[2] + ... a[i] 184 | 185 | a[l] + ... + a[r] = S[r] - S[l - 1] 186 | ``` 187 | 188 | ### 二维前缀和 189 | 190 | ```C++ 191 | S[i, j] = 第i行j列格子左上部分所有元素的和 192 | 193 | 以(x1, y1)为左上角,(x2, y2)为右下角的子矩阵的和为: 194 | S[x2, y2] - S[x1 - 1, y2] - S[x2, y1 - 1] + S[x1 - 1, y1 - 1] 195 | ``` 196 | 197 | ## 差分 198 | 199 | ### 一维差分 200 | 201 | ```c++ 202 | B[i] = a[i] - a[i - 1] 203 | 204 | 给区间[l, r]中的每个数加上c:B[l] += c, B[r + 1] -= c 205 | ``` 206 | 207 | ### 二维差分 208 | 209 | ```C++ 210 | 给以(x1, y1)为左上角,(x2, y2)为右下角的子矩阵中的所有元素加上c: 211 | 212 | S[x1, y1] += c, S[x2 + 1, y1] -= c, S[x1, y2 + 1] -= c, S[x2 + 1, y2 + 1] += c 213 | ``` 214 | 215 | -------------------------------------------------------------------------------- /chapter-3/6-14-template.md: -------------------------------------------------------------------------------- 1 | # 第八讲 2 | 3 | ## 朴素dijkstra算法 4 | 5 | ```c++ 6 | int g[N][N]; // 存储每条边 7 | int dist[N]; // 存储1号点到每个点的最短距离 8 | bool st[N]; // 存储每个点的最短路是否已经确定 9 | 10 | // 求1号点到n号点的最短路,如果不存在则返回-1 11 | int dijkstra() { 12 | memset(dist, 0x3f, sizeof dist); 13 | dist[1] = 0; 14 | 15 | for (int i = 0; i < n - 1; i ++ ) { 16 | int t = -1; // 在还未确定最短路的点中,寻找距离最小的点 17 | for (int j = 1; j <= n; j ++ ) 18 | if (!st[j] && (t == -1 || dist[t] > dist[j])) 19 | t = j; 20 | 21 | // 用t更新其他点的距离 22 | for (int j = 1; j <= n; j ++ ) 23 | dist[j] = min(dist[j], dist[t] + g[t][j]); 24 | 25 | st[t] = true; 26 | } 27 | 28 | if (dist[n] == 0x3f3f3f3f) return -1; 29 | return dist[n]; 30 | } 31 | 32 | ``` 33 | 34 | ## 堆优化版dijkstra 35 | 36 | ```c++ 37 | typedef pair PII; 38 | 39 | int n; // 点的数量 40 | int h[N], w[N], e[N], ne[N], idx; // 邻接表存储所有边 41 | int dist[N]; // 存储所有点到1号点的距离 42 | bool st[N]; // 存储每个点的最短距离是否已确定 43 | 44 | // 求1号点到n号点的最短距离,如果不存在,则返回-1 45 | int dijkstra() { 46 | memset(dist, 0x3f, sizeof dist); 47 | dist[1] = 0; 48 | priority_queue, greater> heap; 49 | heap.push({0, 1}); // first存储距离,second存储节点编号 50 | 51 | while (heap.size()) { 52 | auto t = heap.top(); 53 | heap.pop(); 54 | 55 | int ver = t.second, distance = t.first; 56 | 57 | if (st[ver]) continue; 58 | st[ver] = true; 59 | 60 | for (int i = h[ver]; i != -1; i = ne[i]) { 61 | int j = e[i]; 62 | if (dist[j] > distance + w[i]) { 63 | dist[j] = distance + w[i]; 64 | heap.push({dist[j], j}); 65 | } 66 | } 67 | } 68 | 69 | if (dist[n] == 0x3f3f3f3f) return -1; 70 | return dist[n]; 71 | } 72 | ``` 73 | 74 | ## Bellman-Ford算法 75 | 76 | ```c++ 77 | int n, m; // n表示点数,m表示边数 78 | int dist[N]; // dist[x]存储1到x的最短路距离 79 | 80 | // 边,a表示出点,b表示入点,w表示边的权重 81 | struct Edge { 82 | int a, b, w; 83 | } edges[M]; 84 | 85 | // 求1到n的最短路距离,如果无法从1走到n,则返回-1。 86 | int bellman_ford() { 87 | memset(dist, 0x3f, sizeof dist); 88 | dist[1] = 0; 89 | 90 | // 如果第n次迭代仍然会松弛三角不等式,就说明存在一条长度是n+1的最短路径,由抽屉原理,路径中至少存在两个相同的点,说明图中存在负权回路。 91 | for (int i = 0; i < n; i ++ ) { 92 | for (int j = 0; j < m; j ++ ) { 93 | int a = edges[j].a, b = edges[j].b, w = edges[j].w; 94 | if (dist[b] > dist[a] + w) 95 | dist[b] = dist[a] + w; 96 | } 97 | } 98 | 99 | if (dist[n] == 0x3f3f3f3f) return -1; 100 | return dist[n]; 101 | } 102 | ``` 103 | 104 | ## spfa 算法 105 | 106 | > **队列优化的Bellman-Ford算法** 107 | 108 | ```c++ 109 | int n; // 总点数 110 | int h[N], w[N], e[N], ne[N], idx; // 邻接表存储所有边 111 | int dist[N]; // 存储每个点到1号点的最短距离 112 | bool st[N]; // 存储每个点是否在队列中 113 | 114 | // 求1号点到n号点的最短路距离,如果从1号点无法走到n号点则返回-1 115 | int spfa() { 116 | memset(dist, 0x3f, sizeof dist); 117 | dist[1] = 0; 118 | 119 | queue q; 120 | q.push(1); 121 | st[1] = true; 122 | 123 | while (q.size()) { 124 | auto t = q.front(); 125 | q.pop(); 126 | 127 | st[t] = false; 128 | 129 | for (int i = h[t]; i != -1; i = ne[i]) { 130 | int j = e[i]; 131 | if (dist[j] > dist[t] + w[i]) { 132 | dist[j] = dist[t] + w[i]; 133 | // 如果队列中已存在j,则不需要将j重复插入 134 | if (!st[j]) { 135 | q.push(j); 136 | st[j] = true; 137 | } 138 | } 139 | } 140 | } 141 | 142 | if (dist[n] == 0x3f3f3f3f) return -1; 143 | return dist[n]; 144 | } 145 | ``` 146 | 147 | ## spfa判断图中是否存在负环 148 | 149 | ```c++ 150 | int n; // 总点数 151 | int h[N], w[N], e[N], ne[N], idx; // 邻接表存储所有边 152 | int dist[N], cnt[N]; // dist[x]存储1号点到x的最短距离,cnt[x]存储1到x的最短路中经过的点数 153 | bool st[N]; // 存储每个点是否在队列中 154 | 155 | // 如果存在负环,则返回true,否则返回false。 156 | bool spfa() { 157 | // 不需要初始化dist数组 158 | // 原理:如果某条最短路径上有n个点(除了自己),那么加上自己之后一共有n+1个点,由抽屉原理一定有两个点相同,所以存在环。 159 | 160 | queue q; 161 | for (int i = 1; i <= n; i ++ ) { 162 | q.push(i); 163 | st[i] = true; 164 | } 165 | 166 | while (q.size()) { 167 | auto t = q.front(); 168 | q.pop(); 169 | 170 | st[t] = false; 171 | 172 | for (int i = h[t]; i != -1; i = ne[i]) { 173 | int j = e[i]; 174 | if (dist[j] > dist[t] + w[i]) { 175 | dist[j] = dist[t] + w[i]; 176 | cnt[j] = cnt[t] + 1; 177 | // 如果从1号点到x的最短路中包含至少n个点(不包括自己),则说明存在环 178 | if (cnt[j] >= n) return true; 179 | if (!st[j]) { 180 | q.push(j); 181 | st[j] = true; 182 | } 183 | } 184 | } 185 | } 186 | 187 | return false; 188 | } 189 | ``` 190 | 191 | ## floyd算法 192 | 193 | **初始化:** 194 | 195 | ```c++ 196 | for (int i = 1; i <= n; i ++ ) 197 | for (int j = 1; j <= n; j ++ ) 198 | if (i == j) d[i][j] = 0; 199 | else d[i][j] = INF; 200 | ``` 201 | 202 | ```c++ 203 | // 算法结束后,d[a][b]表示a到b的最短距离 204 | void floyd() { 205 | for (int k = 1; k <= n; k ++ ) 206 | for (int i = 1; i <= n; i ++ ) 207 | for (int j = 1; j <= n; j ++ ) 208 | d[i][j] = min(d[i][j], d[i][k] + d[k][j]); 209 | } 210 | ``` 211 | 212 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------