写在前面
本篇博客主要用于本人的ICPC比赛用模板整理,方便查阅。
如有网友发现哪里写的不好、哪里可以改进,欢迎提出。
持续更新中…
常用C++STL(模板)合集
注意:C++STL全部需要使用命名空间std
万能(误)算法头文件(部分)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 #include <algorithm> using namespace std ; int main () { iterator begin, end; T i, x, a, b; sort(begin, end, <cmp>); next_permutation(begin, end); prev_permutation(begin, end); set_union(begin(a), end(a), begin(b), end(b), begin(c)); set_intersection(begin(a), end(a), begin(b), end(b), begin(c)); set_difference(begin(a), end(a), begin(b), end(b), begin(c)); unique(begin, end); merge(begin(a), end(a), begin(b), end(b), begin(c), cmp); lower_bound(begin, end, x); upper_bound(begin, end, x); find(begin, end, x); binary_search(begin, end, x) min(a, b); max(a, b); fill(begin, end, x); swap(a, b); return 0 ; }
动态数组(vector)、双向链表(list)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 #include <vector> #include <list> using namespace std ;int main () { T i; unsigned int n, x; bool flag; iterator it; vector <T> v; v.push_back(i); v[x]; v.begin(); v.end(); n = v.size(); v.pop_back(); v.erase(it); v.insert(x, i); v.clear(); flag = v.empty(); list <T> li; li.push_front(i); li.push_back(i); li.pop_front(i); li.pop_back(i); li.erase(it); li.insert(x, i); li.begin(); li.end(); n = li.size(); li.remove(i); li.unique(); li.reverse(); li.clear(); return 0 ; }
普通队列、双端队列、优先队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 #include <queue> // 队列头文件 #include <deque> // 双端队列头文件 using namespace std ;int main () { T i; unsigned int n, x; bool flag; queue <T> q, tmp_q; q.push(i); q.pop(); i = q.front(); i = q.back(); n = q,size(); flag = q.empty(); q.swap(tmp_q); priority_queue <T> pq; pq.push(i); pq.pop(); i = pq.top(); n = q,size(); flag = q.empty(); q.swap(tmp_q); deque <T> dq; dq.push_back(i); dq.push_front(i); dq.front(); dq.back(); dq.pop_front(); dq.pop_back(); dq.begin(); dq.end(); dq[x]; n = dq.size(); flag = dq.empty(); dq.insert(x, i); return 0 ; }
栈
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <stack> using namespace std ;int main () { T i; unsigned int n; bool flag; stack <T> st; st.push(i); st.pop(); i = st.top(); flag = st.empty(); n = st.size(); return 0 ; }
pair(成组)、set(有序元素序列)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #include <set> #include <pair> using namespace std ;int main () { T i; T1 t1; T2 t2; iterator it; unsigned int n; bool flag; pair <T1, T2> p; p = make_pair (t1, t2); p.first; p.second; set <int > st; st.insert(i); st.begin(); st.end(); st.erase(it); st.erase(i); st.equal_range(i); flag = st.empty(); n = st.size(); st.clear(); multiset <int > mst; mst.erase(i); return 0 ; }
1 2 3 4 5 6 7 struct CMP { bool operator () (const int & a, const int & b) const { return a > b; } }; multiset <int , CMP> mst;
map(映射)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <map> using namespace std ;int main () { T1 t1; T2 t2; map <T1, T2> mp; mp[t1] = t2; mp[t1]; return 0 ; }
一些C++的功能/特性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include <bits/stdc++.h> // 标准库头文件 using namespace std ;int main () { __int128 a; cin .tie(0 ); cout .tie(0 ); ios::sync_with_stdio(false ); auto x; std ::set <int > st; std ::for (auto i:st); int i; std ::set <int > st; st.emplace(i); std ::vector <int > vc; vc.emplace_back(i); return 0 ; }
强大的pb_ds库
这部分并不是标准库STL,是扩展模板库。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 #include <bits/stdc++.h> #include <bits/extc++.h> // 扩展库头文件 using namespace __gnu_pbds;using namespace __gnu_cxx;int main () { cc_hash_table<string , int > mp1; gp_hash_table<string , int > mp2; priority_queue <int , std ::greater<int >, TAG> pq; priority_queue <int > pq1, pq2; pq1.join(pq2); pq1.begin(); pq1.end(); tree < int , null_type, std ::less<>, rb_tree_tag, tree_order_statistics_node_update > t, tre; int i, k; t.insert(i); t.erase(i); t.order_of_key(i); t.find_by_order(k); t.join(tre); t.split(i, tre); rope<char > str; return 0 ; }
数据结构部分
单调队列
单调栈
可以O ( n ) O(n) O ( n ) 地解决一些区间长度与区间最值关系问题。
例如:求n n n 个数中max [ L , R ] ∈ n { min i ∈ [ L , R ] { a i } ⋅ ( R − L + 1 ) } \displaystyle\max_{[L, R] \in n}\{\min_{i\in[L, R]}\{a_i\} \cdot (R-L+1)\} [ L , R ] ∈ n max { i ∈ [ L , R ] min { a i } ⋅ ( R − L + 1 ) }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 #define ll long long const int MAX_N = 2e6 + 10 ;struct data { ll a, id; }a[MAX_N]; stack <data> st;int main () { ll n, ans = 0 ; data last; scanf ("%d" , &n); for (int i = 1 ; i <= n; ++i) { scanf ("%d" , &a[i].a); a[i].id = i; if (st.empty()) st.push(a[i]); else { while (!st.empty() && st.top().a > a[i].a) { last = st.top(); st.pop(); if (st.empty()) ans = max((i - 1 ) * last.a, ans); else ans = max((i - st.top().id - 1 ) * last.a, ans); } st.push(a[i]); } } while (!st.empty()) { last = st.top(); st.pop(); if (st.empty()) ans = max(n * last.a, ans); else ans = max((n - st.top().id) * last.a, ans); } printf ("%lld\n" , ans); return 0 ; }
归并排序、逆序对数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 #define mm (l + r) >> 1 #define lson l, mid #define rson mid + 1, r const int MAX_N = 1e5 + 10 ;int a[MAX_N], tmp[MAX_N];void m_sort (int l, int r, int &p) { if (l == r) return ; int mid = mm; m_sort(lson, p), m_sort(rson, p); int i = l, j = mid + 1 , k = l; while (i <= mid && j <= r) { if (a[i] <= a[j]) tmp[k++] = a[i++]; else { tmp[k++] = a[j++]; p += mid - i + 1 ; } } while (i <= mid) tmp[k++] = a[i++]; while (j <= r) tmp[k++] = a[j++]; for (i = l; i <= r; ++i) a[i] = tmp[i]; }
线段树/树状数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 #include <bits/stdc++.h> using namespace std ;#define ll long long #define lowbit(x) (x & -x) #define mm (l + r) >> 1 #define lson l, mid, p << 1 #define rson mid + 1, r, p << 1|1 const int MAX_N = 200000 + 10 ; ll sum[MAX_N], tree[MAX_N << 2 ], lazy[MAX_N << 2 ], a[MAX_N]; inline void push_up (int p) { tree[p] = tree[p << 1 ] + tree[p << 1 |1 ]; } inline void push_down (int l, int r, int p) { if (lazy[p]) { int mid = mm; tree[p << 1 ] += (mid - l + 1 ) * lazy[p]; tree[p << 1 |1 ] += (r - mid) * lazy[p]; lazy[p << 1 ] += lazy[p]; lazy[p << 1 |1 ] += lazy[p]; lazy[p] = 0 ; } } void build (int l, int r, int p) { if (l == r) { tree[p] = a[l]; lazy[p] = 0 ; return ; } int mid = mm; build(lson), build(rson); push_up(p); } ll query (int l, int r, int p, int L, int R) { if (L <= l && r <= R) return tree[p]; int mid = mm; ll ret = 0 ; push_down(l, r, p); if (L <= mid) ret += query(l, mid, p << 1 , L, R); if (R > mid) ret += query(mid + 1 , r, p << 1 |1 , L, R); return ret; } void update (int l, int r, int p, int L, int R, int s) { if (L <= l && r <= R) { tree[p] += (r - l + 1 ) * s; lazy[p] += s; return ; } int mid = mm; push_down(l, r, p); if (L <= mid) update(l, mid, p << 1 , L, R, s); if (R > mid) update(mid + 1 , r, p << 1 | 1 , L, R, s); tree[p] = tree[p << 1 ] + tree[p << 1 |1 ]; } ll ask (int x) { ll ret = 0 ; for (; x; x -= lowbit(x)) ret += sum[x]; return ret; } ll get_sum (int l, int r) { return ask(r) - ask(l - 1 ); } void change (int n, int x, ll s) { for (; x <= n; x += lowbit(x)) sum[x] += s; }
可持久化线段树(主席树)
主席树本质上是n棵权值线段树,本质上不可修改,套上树状数组后可以支持单点修改(待更新)
朴素版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 #include <bits/stdc++.h> using namespace std ;#define ll long long #define mm (l + r) >> 1 #define lson l, mid #define rson mid + 1, r const int MAX_N = (int )1e5 + 10 ;struct node { int ls, rs; ll sum; }tree[MAX_N * 40 ]; int rt[MAX_N], CNT, a[MAX_N], p[MAX_N];vector <int > vt;int disc (int n) { for (int i = 1 ; i <= n; ++ i) vt.push_back(a[i]); sort(vt.begin(), vt.end()); unique(vt.begin(), vt.end()); for (int i = 1 ; i <= n; ++ i) p[i] = lower_bound(vt.begin(), vt.end(), a[i]) - vt.begin() + 1 ; } int build (int l, int r) { int pos = ++ CNT; if (l == r) return pos; int mid = mm; tree[pos].ls = build(lson); tree[pos].rs = build(rson); return pos; } inline void push_up (int pos) { tree[pos].sum = tree[ tree[pos].ls ].sum + tree[ tree[pos].rs ].sum; } int update (int last, int l, int r, int k) { int pos = ++ CNT; if (l == r) { tree[pos].sum = tree[last].sum + 1 ; return pos; } int mid = mm; tree[pos].ls = tree[last].ls, tree[pos].rs = tree[last].rs; if (k <= mid) tree[pos].ls = update(tree[last].ls, lson, k); else tree[pos].rs = update(tree[last].rs, rson, k); push_up(pos); return pos; } int query (int posL, int posR, int l, int r, int k) { if (l == r) return l; int cnt = (int )(tree[ tree[posR].ls ].sum - tree[ tree[posL].ls ].sum); int mid = mm; if (k <= cnt) return query(tree[posL].ls, tree[posR].ls, lson, k); else return query(tree[posL].rs, tree[posR].rs, rson, k - cnt); } void init (int n) { CNT = 0 ; build(1 , n); for (int i = 1 ; i <= n*40 ; ++ i) tree[i].sum = tree[i].ls = tree[i].rs = 0 ; vt.clear(); } int main () { int n, q, i, l, r, k; while (~ scanf ("%d %d" , &n, &q)) { init(n); for (i = 1 ; i <= n; ++ i) scanf ("%d" , &a[i]); disc(n); for (i = 1 ; i <= n; ++ i) rt[i] = update(rt[i - 1 ], 1 , n, p[i]); while (q --) { scanf ("%d %d %d" , &l, &r, &k); printf ("%d\n" , vt[query(rt[l - 1 ], rt[r], 1 , n, k) - 1 ]); } } return 0 ; }
简约版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 #include <bits/stdc++.h> using namespace std ;const int MAX_N = 1e5 + 10 ;#define ll long long #define mm (l + r) >> 1 #define lson l, mid #define rson mid + 1, r struct node { int ls, rs; int sum; void copy (const node tmp) { ls = tmp.ls; rs = tmp.rs; sum = tmp.sum; } }tree[MAX_N * 40 ]; int CNT, rt[MAX_N];ll a[MAX_N]; void init (int n) { CNT = 0 ; for (int i = 1 ; i <= n*40 ; ++i) tree[i].sum = tree[i].ls = tree[i].rs = 0 ; for (int i = 0 ; i <= n; ++i) rt[i] = 0 ; } inline void push_up (int pos) { tree[pos].sum = tree[ tree[pos].ls ].sum + tree[ tree[pos].rs ].sum; } void update (int &pos, int pre, ll l, ll r, ll val) { pos = ++CNT; tree[pos].copy(tree[pre]); if (l == r) { ++tree[pos].sum; return ; } ll mid = mm; if (val <= mid) update(tree[pos].ls, tree[pre].ls, lson, val); else update(tree[pos].rs, tree[pre].rs, rson, val); push_up(pos); } int query (int posL, int posR, ll l, ll r, int val) { if (l == r) return l; int cnt = (int )(tree[ tree[posR].ls ].sum - tree[ tree[posL].ls ].sum); ll mid = mm; if (val <= cnt) return query(tree[posL].ls, tree[posR].ls, lson, val); else return query(tree[posL].rs, tree[posR].rs, rson, val - cnt); }
归并树(划分树)
本质上是把归并排序和二叉树思想结合,可以解决部分主席树可以解决的东西,但不能回滚和修改。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 #include <bits/stdc++.h> using namespace std ;#define mm (l + r) >> 1 #define lson l, mid, dep + 1 #define rson mid + 1, r, dep + 1 const int MAX_N = 1e5 + 10 ;int a[MAX_N], tree[32 ][MAX_N];void build (int l, int r, int dep) { if (l > r) return ; if (l == r) { tree[dep][l] = a[l]; return ; } int mid = mm, i = l, j = mid + 1 , k = l; build(lson), build(rson); while (i <= mid && j <= r) { if (tree[dep + 1 ][i] <= tree[dep + 1 ][j]) tree[dep][k ++] = tree[dep + 1 ][i ++]; else tree[dep][k ++] = tree[dep + 1 ][j ++]; } while (i <= mid) tree[dep][k ++] = tree[dep + 1 ][i ++]; while (j <= r) tree[dep][k ++] = tree[dep + 1 ][j ++]; return ; } int query (int l, int r, int dep, int ql, int qr, int key) { if (qr < l || r < ql) return 0 ; if (ql <= l && r <= qr) return lower_bound(&tree[dep][l], &tree[dep][r] + 1 , key) - &tree[dep][l]; int mid = mm, ret = 0 ; if (qr > mid) ret += query(rson, ql, qr, key); if (ql <= mid) ret += query(lson, ql, qr, key); return ret; } int main () { int n, m, i, ql, qr, k, l, r, mid, tot; while (~scanf ("%d %d" , &n, &m)) { for (i = 1 ; i <= n; ++i) scanf ("%d" , &a[i]); build(1 , n, 1 ); while (m --) { scanf ("%d %d %d" , &ql, &qr, &k); l = 1 , r = n + 1 , mid = mm; while (l + 1 < r) { mid = mm; tot = query(1 , n, 1 , ql, qr, tree[1 ][mid]); if (tot <= k - 1 ) l = mid; else r = mid; } printf ("%d\n" , tree[1 ][l]); } } return 0 ; }
ST表(倍增)求区间最值
一维
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 const int MAX_N = 1e5 + 10 ;int dp[MAX_N][20 ], vm[MAX_N];void init_RMQ (int n, int b[]) { vm[0 ] = -1 ; for (int i = 1 ; i <= n; ++i) { vm[i] = ((i & (i-1 )) == 0 ) ? vm[i - 1 ]+1 : vm[i - 1 ]; dp[i][0 ] = b[i]; } for (int j = 1 ; j <= vm[n]; ++j) for (int i = 1 ; i + (1 <<j) - 1 <= n; ++i) dp[i][j] = max(dp[i][j - 1 ], dp[i + (1 <<(j-1 )) ][j - 1 ]); } int RMQ (int l, int r) { int k = vm[r - l + 1 ]; return max(dp[l][k], dp[r - (1 <<k) + 1 ][k]); }
二维
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 const int MAX_N = 310 ;int val[MAX_N][MAX_N];int dp[MAX_N][MAX_N][9 ][9 ];int vm[MAX_N]; void init_VM () { vm[0 ] = -1 ; for (int i = 1 ; i < MAX_N; ++i) vm[i] = ((i & (i-1 )) == 0 ) ? vm[i - 1 ]+1 : vm[i - 1 ]; } void init_RMQ (int n, int m) { for (int i = 1 ; i <= n; ++i) for (int j = 1 ; j <= m; ++j) dp[i][j][0 ][0 ] = val[i][j]; for (int ii = 0 ; ii <= vm[n]; ++ii) for (int jj = 0 ; jj <= vm[m]; ++jj) if (ii + jj) for (int i = 1 ; i + (1 <<ii) - 1 <= n; ++i) for (int j = 1 ; j + (1 <<jj) - 1 <= m; ++j) { if (ii) dp[i][j][ii][jj] = max(dp[i][j][ii - 1 ][jj], dp[i + (1 <<(ii-1 )) ][j][ii - 1 ][jj]); else dp[i][j][ii][jj] = max(dp[i][j][ii][jj - 1 ], dp[i][j + (1 <<(jj-1 )) ][ii][jj - 1 ]); } } int RMQ (int x1, int y1, int x2, int y2) { int k1 = vm[x2 - x1 + 1 ]; int k2 = vm[y2 - y1 + 1 ]; x2 = x2 - (1 <<k1) + 1 ; y2 = y2 - (1 <<k2) + 1 ; return max( max(dp[x1][y1][k1][k2], dp[x1][y2][k1][k2]), max(dp[x2][y1][k1][k2], dp[x2][y2][k1][k2]) ); }
字典树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 struct Kx_Trie { static const int MAX_N = 1010 ; static const int MAX_M = 26 ; static const int Tfirst = 'a' ; int CNT; struct node { int son[MAX_M], sum; bool flag; char c; void init () { sum = flag = c = 0 ; memset (son, 0 , sizeof (son)); } }tree[MAX_N]; void init () { CNT = 0 ; tree[0 ].init(); } void insert (char * str) { int rt, nxt; for (rt = 0 ; *str; rt = nxt, ++str) { nxt = tree[rt].son[*str - Tfirst]; if (nxt == 0 ) { nxt = tree[rt].son[*str - Tfirst] = ++CNT; tree[CNT].init(); tree[CNT].c = *str; } ++tree[nxt].sum; } tree[rt].flag = true ; } void erase (char * str) { int rt = 0 ; for (; *str; ++str) { --tree[rt].sum; rt = tree[rt].son[*str - Tfirst]; } --tree[rt].sum; tree[rt].flag = false ; } bool search (char * str) { int rt = 0 ; for (; *str; ++str) { rt = tree[rt].son[*str - Tfirst]; if (!rt) return false ; } return tree[rt].flag; } int prefix (char *str) { int rt, len; for (rt = len = 0 ; *str; ++str, ++len) { rt = tree[rt].son[*str - Tfirst]; if (!rt || !tree[rt].sum) break ; } return len; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 struct Ls_Rb_Trie { static const int MAX_N = 1010 ; int top; struct node { char c; int l, r, sum; bool flag; void init () { l = r = sum = flag = c = 0 ; } }tree[MAX_N]; void init () { top = 0 ; memset (tree, 0 , sizeof (tree)); } bool search (char * str) { int rt; for (rt = 0 ; *str; ++str) { for (rt = tree[rt].l; rt; rt = tree[rt].r) { if (tree[rt].c == *str) break ; } if (!rt || !tree[rt].sum) return false ; } return tree[rt].flag; } void insert (char * str) { int i, rt; for (rt = 0 ; *str; ++str, rt = i) { for (i = tree[rt].l; i; i = tree[i].r) if (tree[i].c == *str) break ; if (i == 0 ) { tree[rt].l = i = ++top; tree[top].init(); tree[top].r = tree[rt].l; tree[top].c = *str; } ++tree[i].sum; } tree[rt].flag = true ; } void erase (char * str) { int rt; for (rt = 0 ; *str; ++str) { for (rt = tree[rt].l; rt; rt = tree[rt].r) { if (tree[rt].c == *str) break ; } --tree[rt].sum; } tree[rt].flag = 0 ; } int prefix (char * str) { int rt = 0 , lv; for (lv = 0 ; *str; ++str, ++lv) { for (rt = tree[rt].l; rt; rt = tree[rt].r) if (tree[rt].c == *str) break ; if (rt == 0 || !tree[rt].sum) break ; } return lv; } };
树链剖分
点权
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 const int MAX_N = 5e4 + 10 ;struct node { int to, go; }edge[MAX_N << 1 ]; int head[MAX_N], tot, pos;int top[MAX_N]; int fa[MAX_N]; int deep[MAX_N]; int num[MAX_N]; int p[MAX_N]; int fp[MAX_N]; int son[MAX_N]; void init () { tot = 0 ; memset (head, -1 , sizeof (head)); pos = 1 ; memset (son, -1 , sizeof (son)); } void add_edge (int u, int v) { edge[tot].to = v, edge[tot].go = head[u], head[u] = tot++; } void dfs (int u, int pre, int dep) { deep[u] = dep; fa[u] = pre; num[u] = 1 ; for (int i = head[u]; i != -1 ; i = edge[i].go) { int v = edge[i].to; if (v != pre) { dfs(v, u, dep+1 ); num[u] += num[v]; if (son[u] == -1 || num[v] > num[son[u]]) son[u] = v; } } } void get_pos (int u, int sp) { top[u] = sp; p[u] = pos++; fp[p[u]] = u; if (son[u] == -1 ) return ; get_pos(son[u], sp); for (int i = head[u]; i != -1 ; i = edge[i].go) { int v = edge[i].to; if (v != son[u] && v != fa[u]) get_pos(v, v); } } int c[MAX_N];int n;inline int lowbit (int x) { return x & (-x); } int get_sum (int i) { int s = 0 ; while (i > 0 ) { s += c[i]; i -= lowbit(i); } return s; } void add (int i, int val) { while (i <= n) { c[i] += val; i += lowbit(i); } } void update (int u, int v, int val) { int f1 = top[u], f2 = top[v]; while (f1 != f2) { if (deep[f1] < deep[f2]) { swap(f1, f2); swap(u, v); } add(p[f1], val); add(p[u]+1 , -val); u = fa[f1]; f1 = top[u]; } if (deep[u] > deep[v]) swap(u, v); add(p[u], val); add(p[v]+1 , -val); } int a[MAX_N];int main () { int m, q; while (~ scanf ("%d %d %d" , &n, &m, &q)) { int u, v, k; char op[10 ]; init(); for (int i = 1 ; i <= n; ++i) scanf ("%d" , &a[i]); while (m--) { scanf ("%d %d" , &u, &v); add_edge(u, v); add_edge(v, u); } dfs(1 , 0 , 0 ); get_pos(1 , 1 ); memset (c, 0 , sizeof (c)); for (int i = 1 ; i <= n; ++i) { add(p[i], a[i]); add(p[i]+1 , -a[i]); } while (q--) { scanf ("%s" , op); if (op[0 ] == 'Q' ) { scanf ("%d" , &u); printf ("%d\n" , get_sum(p[u])); } else { scanf ("%d %d %d" , &u, &v, &k); if (op[0 ] == 'D' ) k = -k; update(u, v, k); } } } return 0 ; }
边权
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 #define mm (l + r) >> 1 #define lson l, mid, p << 1 #define rson mid + 1, r, p << 1|1 const int MAX_N = 1e5 + 10 ;struct node { int to, go; }edge[MAX_N << 1 ]; int head[MAX_N], tot, pos; int top[MAX_N]; int fa[MAX_N]; int deep[MAX_N]; int num[MAX_N]; int p[MAX_N]; int fp[MAX_N]; int son[MAX_N]; void init () { tot = 0 ; memset (head, -1 , sizeof (head)); pos = 1 ; memset (son, -1 , sizeof (son)); } void add_edge (int u, int v) { edge[tot].to = v, edge[tot].go = head[u], head[u] = tot++; } void dfs (int u, int pre, int dep) { deep[u] = dep; fa[u] = pre; num[u] = 1 ; for (int i = head[u]; i != -1 ; i = edge[i].go) { int v = edge[i].to; if (v != pre) { dfs(v, u, dep+1 ); num[u] += num[v]; if (son[u] == -1 || num[v] > num[son[u]]) son[u] = v; } } } void get_pos (int u, int sp) { top[u] = sp; p[u] = pos++; fp[p[u]] = u; if (son[u] == -1 ) return ; get_pos(son[u], sp); for (int i = head[u]; i != -1 ; i = edge[i].go) { int v = edge[i].to; if (v != son[u] && v != fa[u]) get_pos(v, v); } } int tree[MAX_N << 2 ];inline void push_up (int p) { tree[p] = max(tree[p << 1 ], tree[p << 1 |1 ]); } void build (int l, int r, int p) { if (l == r) { tree[p] = 0 ; return ; } int mid = mm; build(lson), build(rson); } void update (int l, int r, int p, int k, int val) { if (l == r && r == k) { tree[p] = val; return ; } int mid = mm; if (k <= mid) update(lson, k, val); else update(rson, k, val); push_up(p); } int query (int l, int r, int p, int L, int R) { if (L <= l && r <= R) return tree[p]; int mid = mm, ret = INT_MIN; if (L <= mid) ret = max(ret, query(lson, L, R)); if (R > mid) ret = max(ret, query(rson, L, R)); return ret; } int find (int u, int v) { int f1 = top[u], f2 = top[v]; int tmp = 0 ; while (f1 != f2) { if (deep[f1] < deep[f2]) { swap(f1, f2); swap(u, v); } tmp = max(tmp, query(1 , pos, 1 , p[f1], p[u])); u = fa[f1], f1 = top[u]; } if (u == v) return tmp; if (deep[u] > deep[v]) swap(u, v); return max(tmp, query(1 , pos, 1 , p[ son[u] ], p[v])); } int G[MAX_N][3 ];int main () { int T, n, u, v; char op[10 ]; scanf ("%d" , &T); while (T --) { init(); scanf ("%d" , &n); for (int i = 1 ; i < n; ++i) { scanf ("%d %d %d" , &G[i][0 ], &G[i][1 ], &G[i][2 ]); add_edge(G[i][0 ], G[i][1 ]); add_edge(G[i][1 ], G[i][0 ]); } dfs(1 , 0 , 0 ); get_pos(1 , 1 ); build(1 , pos, 1 ); for (int i = 1 ; i < n; ++i) { if (deep[ G[i][0 ] ] > deep[ G[i][1 ] ]) swap(G[i][0 ], G[i][1 ]); update(1 , pos, 1 , p[ G[i][1 ] ], G[i][2 ]); } while (scanf ("%s" , op)) { if (op[0 ] == 'D' ) break ; scanf ("%d %d" , &u, &v); if (op[0 ] == 'Q' ) printf ("%d\n" , find(u, v)); else update(1 , pos, 1 , p[ G[u][1 ] ], v); } } return 0 ; }
并查集
普通并查集
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 const int MAX_N = 1e5 + 10 ;int f[MAX_N];void init (int n) { for (int i = 0 ; i <= n; ++i) f[i] = i; } int find (int x) { return f[x] == x ? x : f[x] = find(f[x]); } bool merge (int x, int y) { x = find(x), y = find(y); if (x == y) return false ; f[y] = x; return true ; }
带权并查集
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 const int MAX_N = 1e5 + 10 ;const int MOD = 3 ; int f[MAX_N], p[MAX_N]; void init (int n) { for (int i = 0 ; i <= n; ++i) f[i] = i, p[i] = 0 ; } int find (int x) { int tmp = f[x]; if (f[x] != x) { f[x] = find(f[x]); p[x] = (p[x] + p[tmp]) % MOD; } return f[x]; } void merge (int x, int y, int s) { int fx = find(x), fy = find(y); if (fx != fy) { f[fy] = fx; p[fy] = (p[x] - p[y] + s + MOD) % MOD; } } bool solve (int x, int y, int ask, int n) { int fx = find(x), fy = find(y); bool flag = true ; if (x > n || y > n || (ask == 1 && x == y)) flag = false ; else if (fx == fy) flag = ((p[y] - p[x] + MOD) % MOD == ask); return flag; }
数论部分
一些基础的公式、定理
组合数公式:C n m = C n − 1 m − 1 + C n − 1 m C_n^m = C_{n-1}^{m-1} + C_{n-1}^m C n m = C n − 1 m − 1 + C n − 1 m ,即杨辉三角,可用在O ( n 2 ) O(n^2) O ( n 2 ) 下求出所有组合数
Lucas定理:C n m = C n / p m / p ∗ C n % p m % p m o d p C_n^m = C_{n/p}^{m/p} * C_{n\%p}^{m\%p} \mod p C n m = C n / p m / p ∗ C n % p m % p m o d p ,要求p p p 是质数
错排公式:a n = ( n − 1 ) ∗ ( a n − 1 + a n − 2 ) a_n = (n-1) * (a_{n-1} + a_{n-2}) a n = ( n − 1 ) ∗ ( a n − 1 + a n − 2 )
欧拉定理:若g c d ( a , n ) = 1 gcd(a,n) = 1 g c d ( a , n ) = 1 ,则有a ϕ ( n ) ≡ 1 ( m o d n ) a^{\phi(n)} \equiv 1 \pmod n a ϕ ( n ) ≡ 1 ( m o d n ) ,其中ϕ ( n ) \phi(n) ϕ ( n ) 是欧拉函数。
费马小定理:若g c d ( a , p ) = 1 gcd(a, p) = 1 g c d ( a , p ) = 1 ,则有a p − 1 ≡ 1 ( m o d p ) a^{p-1} \equiv 1 \pmod p a p − 1 ≡ 1 ( m o d p )
费马大定理:当n > 2 n > 2 n > 2 时,x n + y n = z n x^n + y^n = z^n x n + y n = z n 没有正整数解
威尔逊定理:当且仅当p p p 是素数时,有( p − 1 ) ! ≡ 1 ( m o d p ) (p-1)! \equiv 1 \pmod p ( p − 1 ) ! ≡ 1 ( m o d p )
快速幂:对于任意正整数a , n a,n a , n ,满足a n = { ( a n / 2 ) 2 n是偶数 a ∗ ( a n / 2 ) 2 n是奇数 a^n = \begin{cases} {(a^{n/2})}^2 &\text{n是偶数} \\ a * (a^{n/2})^2 &\text{n是奇数} \end{cases} a n = { ( a n / 2 ) 2 a ∗ ( a n / 2 ) 2 n 是偶数 n 是奇数
平方和公式:∑ x = 1 n x 2 = ( 2 ∗ n + 1 ) ∗ ( n + 1 ) ∗ n / 6 \sum_{x=1}^n x^2 = (2*n + 1) * (n + 1) * n / 6 ∑ x = 1 n x 2 = ( 2 ∗ n + 1 ) ∗ ( n + 1 ) ∗ n / 6
等比数列求和:S n = a 1 ∗ ( 1 − q n ) / ( 1 − q ) S_n = a_1 * (1-q^n) / (1-q) S n = a 1 ∗ ( 1 − q n ) / ( 1 − q )
素数间隔定理:对于大质数p n p_n p n 和p n − 1 p_{n-1} p n − 1 之间间隔不超过log 2 p n \log_2p_n log 2 p n
待更新……
因数、余数、质数基础
埃氏素数筛法
1 2 3 4 5 6 7 8 9 10 11 12 13 const int MAX_N = 1e5 + 10 ;int CNT, prime[MAX_N];bool vis[MAX_N];void make_prime () { CNT = 0 ; for (int i = 2 ; i < MAX_N; ++i) { if (!vis[i]) { prime[++CNT] = i; for (int j = 2 ; j * i < MAX_N; ++j) vis[i*j] = true ; } } }
欧拉函数
对于任意正整数n n n ,欧拉函数是[ 1 , n ] [1,n] [ 1 , n ] 中与n n n 互质的数的个数,通常写作φ ( n ) \varphi(n) φ ( n ) 。特别地,φ ( 1 ) = 1 \varphi(1) = 1 φ ( 1 ) = 1 。
通式为:φ ( x ) = x ∏ i = 1 n ( 1 − 1 p i ) \varphi(x) = x \displaystyle\prod_{i=1}^{n} (1 - \frac{1}{p_i}) φ ( x ) = x i = 1 ∏ n ( 1 − p i 1 ) ,其中p 1 , p 2 , … , p n p_1, p_2, \dots, p_n p 1 , p 2 , … , p n 为n n n 的所有质因子。
求解单个数字其欧拉函数:
1 2 3 4 5 6 7 8 9 10 11 int phi (int n) { int ans = n; for (int i = 2 ; i * i <= n; ++i) { if (n % i == 0 ) { ans -= ans / i; while (n % i == 0 ) n /= i; } } if (n > 1 ) ans -= ans / n; return ans; }
打表求欧拉函数:
1 2 3 4 5 6 7 8 9 10 11 12 const int MAX_N = 1e5 + 10 ;int phi[MAX_N];void euler () { for (int i = 2 ; i < MAX_N; ++i) { if (!phi[i]) { for (int j = i; j < MAX_N; j += i) { if (!phi[j]) phi[j] = j; phi[j] = phi[j] / i * (i-1 ); } } } }
线性筛素数、欧拉函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 const int MAX_N = 1e6 + 10 ;int CNT, prime[MAX_N], phi[MAX_N];bool vis[MAX_N];void make_prime_phi () { CNT = 0 ; memset (vis, false , sizeof (vis)); for (int i = 2 ; i < MAX_N; ++i) { if (!vis[i]) { prime[++CNT] = i; phi[i] = i-1 ; } for (int j = 1 ; j <= CNT && i*prime[j] < MAX_N; ++j) { vis[ i*prime[j] ] = true ; if (i % prime[j] == 0 ) { phi[ i*prime[j] ] = phi[i] * prime[j]; break ; } else phi[ i*prime[j] ] = phi[i] * (prime[j]-1 ); } } }
欧拉函数的一些性质:
若g c d ( n , m ) = 1 gcd(n, m) = 1 g c d ( n , m ) = 1 ,则φ ( n m ) = φ ( n ) φ ( m ) \varphi(nm) = \varphi(n) \varphi(m) φ ( n m ) = φ ( n ) φ ( m )
当n > 2 n>2 n > 2 时,所有的φ ( n ) \varphi(n) φ ( n ) 都是偶数
当n n n 为奇数时,有φ ( 2 n ) = φ ( n ) \varphi(2n) = \varphi(n) φ ( 2 n ) = φ ( n )
∑ g c d ( i , n ) = 1 n i = n ∗ φ ( n ) / 2 \displaystyle\sum_{gcd(i, n) = 1}^{n}{i} = n * \varphi(n) / 2 g c d ( i , n ) = 1 ∑ n i = n ∗ φ ( n ) / 2
∑ d ∣ n φ ( d ) = n \displaystyle\sum_{d|n} \varphi(d) = n d ∣ n ∑ φ ( d ) = n
欧几里得定理求a、b最大公因数、最小公倍数
1 2 3 4 5 6 int gcd (int a, int b) { return b ? gcd(b, a % b) : a; } int lcm (int a, int b) { return a / gcd(a, b) * b; }
扩展欧几里得
求一组整数特解( x , y ) (x, y) ( x , y ) ,满足a x + b y = g c d ( a , b ) ax + by = gcd(a, b) a x + b y = g c d ( a , b ) ,其中a a a 和b b b 已知。
易知上述方程可转化为b x ′ + ( a % b ) y ′ = g c d ( b , a % b ) = g c d ( a , b ) bx' + (a \% b)y' = gcd(b, a \% b) = gcd(a, b) b x ′ + ( a % b ) y ′ = g c d ( b , a % b ) = g c d ( a , b )
则有a x + b y = b x ′ + ( a % b ) y ′ ax + by = bx' + (a \% b)y' a x + b y = b x ′ + ( a % b ) y ′ ,整理后得
a x + b y = a y ′ + b ( x ′ − ⌊ a b ⌋ y ′ ) ax + by = ay' + b(x' - \lfloor{\frac{a}{b}}\rfloor y')
a x + b y = a y ′ + b ( x ′ − ⌊ b a ⌋ y ′ )
得出解:x = y ′ , y = x ′ − ⌊ a b ⌋ y ′ x = y', y = x' - \lfloor{\frac{a}{b}}\rfloor y' x = y ′ , y = x ′ − ⌊ b a ⌋ y ′ ,其中当递归到b = 0 b = 0 b = 0 时,可得一组特解x = 1 , y = 0 x = 1, y = 0 x = 1 , y = 0
1 2 3 4 5 6 7 8 9 10 int ex_gcd (int a, int b, int &x, int &y) { if (!b) { x = 1 , y = 0 ; return a; } int d = ex_gcd(b, a%b, x, y); int t = x; x = y, y = t - a / b * y; return d; }
得到一组特解( x 1 , y 1 ) (x_1, y_1) ( x 1 , y 1 ) 后,方程a x + b y = g c d ( a , b ) ax + by = gcd(a, b) a x + b y = g c d ( a , b ) 的通解为:x = x 1 + k ∗ ( b / d ) , y = y 1 + k ∗ ( a / d ) x = x_1 + k * (b/d), y = y_1 + k * (a / d) x = x 1 + k ∗ ( b / d ) , y = y 1 + k ∗ ( a / d ) ,其中k k k 为任意整数。a x + b y = c ∗ g c d ( a , b ) ax + by = c*gcd(a, b) a x + b y = c ∗ g c d ( a , b ) (c c c 为任意正整数)的通解为:x = c ∗ x 1 + k ∗ ( b / d ) , y = c ∗ y 1 + k ∗ ( a / d ) x = c * x_1 + k * (b/d), y = c * y_1 + k * (a / d) x = c ∗ x 1 + k ∗ ( b / d ) , y = c ∗ y 1 + k ∗ ( a / d )
线性同余方程
形如:a x ≡ b ( m o d p ) ax \equiv b \pmod p a x ≡ b ( m o d p ) 的方程,称为线性同余方程,有如下两个定理:
设d = g c d ( a , p ) d = gcd(a, p) d = g c d ( a , p ) ,当d ∣ b d|b d ∣ b 时,方程恰有且好有d d d 个模n n n 不同余的解,否则方程无解。
若x 0 x_0 x 0 是方程任一解,则该方程通解为x i = ( x 0 + k ∗ ( p / d ) ) % n x_i = (x_0 + k * (p / d)) \% n x i = ( x 0 + k ∗ ( p / d ) ) % n ,其中k = 0 , 1 , 2 , … , d − 1 k = 0, 1, 2, \dots, d-1 k = 0 , 1 , 2 , … , d − 1 。
注意:扩展欧几里得求出a x − p y = g c d ( a , p ) ax-py=gcd(a,p) a x − p y = g c d ( a , p ) 的一组解后,并不一定是原同余方程的解。
特别地,设t = n / d t = n / d t = n / d ,若求出一特解x x x ,则该方程的最小正整数解为x % t x \% t x % t ,这里的模运算右对齐。
模线性方程组求解(中国剩余定理)
对于模线性方程组如:
{ x ≡ a 1 ( m o d m 1 ) x ≡ a 2 ( m o d m 2 ) … x ≡ a n ( m o d m n ) \begin{cases} {x \equiv a_1 \pmod{m_1}} \\ {x \equiv a_2 \pmod{m_2}} \\ \dots \\ {x \equiv a_n \pmod{m_n}}\end{cases}
⎩ ⎪ ⎪ ⎪ ⎨ ⎪ ⎪ ⎪ ⎧ x ≡ a 1 ( m o d m 1 ) x ≡ a 2 ( m o d m 2 ) … x ≡ a n ( m o d m n )
假设整数m 1 , m 2 , … , m n m_1, m_2, \dots, m_n m 1 , m 2 , … , m n 两两互质,通解可以构造如下:
设M = ∏ i = 1 n m i M = \displaystyle\prod_{i=1}^{n} m_i M = i = 1 ∏ n m i ,并设M i = M / m i M_i = M / m_i M i = M / m i ,t i = M i − 1 t_i = M_i^{-1} t i = M i − 1 ,其中M i − 1 M_i^{-1} M i − 1 表示M i M_i M i 模m i m_i m i 意义下的倒数,即M i t i ≡ 1 ( m o d m i ) M_it_i \equiv 1 \pmod{m_i} M i t i ≡ 1 ( m o d m i ) 。
方程组通解为:x = ∑ i = 1 n a i t i M i + k M x = \displaystyle\sum_{i = 1}^{n} {a_it_iM_i + kM} x = i = 1 ∑ n a i t i M i + k M ,k k k 为任意整数。
求最小正整数解:
1 2 3 4 5 6 7 8 9 10 11 int crt (int r[], int m[], int n) { int M = 1 , ans = 0 , x, y, Mi; for (int i = 1 ; i <= n; ++i) M *= m[i]; for (int i = 1 ; i <= n; ++i) { Mi = M / m[i]; ex_gcd(Mi, m[i], x, y); ans = (ans + r[i] * x * Mi) % M; } while (ans < 0 ) ans += M; return ans; }
若数m 1 , m 2 , … , m n m_1, m_2, \dots, m_n m 1 , m 2 , … , m n 不一定互质,求最小正整数解:
1 2 3 4 5 6 7 8 9 10 11 12 int ex_crt (int m[], int r[], int n) { int M = m[1 ], R = r[1 ], d, x, y; for (int i = 2 ; i <= n; ++i) { d = ex_gcd(M, m[i], x, y); if ((R - r[i]) % d) return -1 ; x = (R - r[i]) / d * x % m[i]; R -= M * x, M = M / d * m[i]; R %= M; } R = (R % M + M) % M; return R; }
乘法逆元
在可模运算的数据集合内,定义任意一个a a a ,若存在一个e e e ,满足:
a × e ≡ e × a ≡ a ( m o d p ) a \times e \equiv e \times a \equiv a \pmod p
a × e ≡ e × a ≡ a ( m o d p )
则称e e e 为该种数据的在模p p p 意义下的幺元 。若存在一个b b b ,满足:
a × b ≡ b × a ≡ e ( m o d p ) a \times b \equiv b \times a \equiv e \pmod p
a × b ≡ b × a ≡ e ( m o d p )
则称b b b 为a a a 在模p p p 意义下的逆元 ,通常写作i n v ( a ) inv(a) i n v ( a ) 或a − 1 a^{-1} a − 1 ,
由上述可知,在正整数集内,1 1 1 就是一个幺元(p p p 可取任意值)。
扩展欧几里得求逆元:
即求同余方程a x ≡ 1 ( m o d p ) ax \equiv 1 \pmod p a x ≡ 1 ( m o d p ) 的最小正整数解,前提是g c d ( a , p ) = 1 gcd(a, p) = 1 g c d ( a , p ) = 1 。
1 2 3 4 5 6 const int MOD = 1e9 + 7 ;int inv (int a) { int x, y; ex_gcd(a, MOD, x, y); return (x % MOD + MOD) % MOD; }
费马小定理求逆元:
根据a p − 1 m o d p = 1 a^{p-1} \mod p = 1 a p − 1 m o d p = 1 得a − 1 ≡ a p − 2 ( m o d p ) a^{-1} \equiv a^{p-2} \pmod p a − 1 ≡ a p − 2 ( m o d p ) ,前提是p p p 为质数且a a a 不是p p p 的倍数。
1 2 3 4 5 6 7 8 9 10 11 12 13 const int MOD = 1e9 + 7 ;int qmod (int n, int a) { int tmp = 1 ; if (n) { tmp = qmod(n >> 1 , a); tmp = tmp * tmp % MOD; if (n & 1 ) tmp = tmp * a % MOD; } return tmp; } int inv (int a) { return qmod(MOD - 2 , a); }
线性递推逆元:
前提是模数为一个奇质数。
1 2 3 4 5 6 7 8 const int MAX_N = 1e5 + 10 ;const int MOD = 1e9 + 7 ;int inv[MAX_N]; void make_inv () { inv[1 ] = 1 ; for (int i = 2 ; i < MOD && i < MAX_N; ++i) inv[i] = (MOD - MOD / i) * inv[MOD % i] % MOD; }
二次剩余
若x 2 ≡ n ( m o d p ) x^2 \equiv n \pmod p x 2 ≡ n ( m o d p ) 有解,则称n n n 是模p p p 的二次剩余。常用于模意义下的开方,即n ≡ x ( m o d p ) \sqrt{n} \equiv x \pmod p n ≡ x ( m o d p )
引入一个概念,勒让德符号:
( a p ) = { 0 , a ≡ 0 ( m o d p ) 1 , ∃ x 2 ≡ a ( m o d p ) − 1 , ∀ x 2 ≢ a ( m o d p ) \left(\frac{a}{p}\right) = \begin{cases} 0, &{a \equiv 0 \pmod p} \\ 1, &{\exists x^2 \equiv a \pmod p} \\ -1, & {\forall x^2 \not\equiv a \pmod p} \end{cases}
( p a ) = ⎩ ⎪ ⎨ ⎪ ⎧ 0 , 1 , − 1 , a ≡ 0 ( m o d p ) ∃ x 2 ≡ a ( m o d p ) ∀ x 2 ≡ a ( m o d p )
又有欧拉准则(前提为p p p 是奇质数):
( a p ) = ± 1 ≡ a p − 1 2 ( m o d p ) \left(\frac{a}{p}\right) = \pm1 \equiv a^{\frac{p-1}{2}} \pmod p
( p a ) = ± 1 ≡ a 2 p − 1 ( m o d p )
可以利用上述欧拉准则进行求解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 #define ll long long struct Point { ll x, y, w; Point(int a = 0 , int b = 0 , int c = 0 ) { x = a, y = b, w = c; } }; Point mul (Point a, Point b, ll MOD) { Point ans; ans.x = (a.x * b.x % MOD + a.y * b.y % MOD * a.w % MOD) % MOD; ans.y = (a.x * b.y % MOD + a.y * b.x % MOD) % MOD; ans.w = a.w; return ans; } Point qmod (ll n, Point a, ll MOD) { Point ans = Point(1 , 0 , a.w); for (; n; n >>= 1 , a = mul(a, a, MOD)) if (n & 1 ) ans = mul(ans, a, MOD); return ans; } ll qmod (ll n, ll a, ll MOD) { ll ans = 1LL ; for (; n; n >>= 1 , a = a * a % MOD) if (n & 1 ) ans = ans * a % MOD; return ans; } ll lgd (ll a, ll p) { ll ans = qmod((p - 1 ) >> 1 , a, p); if (ans + 1 == p) return -1 ; return ans; } ll solve (ll b, ll p) { if (!b || p == 2 ) return b; if (lgd(b, p) == -1 ) return -1 ; ll w, a; do { a = rand() % p; w = a * a - b; w = (w % p + p) % p; } while (lgd(w, p) != -1 ); Point ans, tmp = Point(a, 1 , w); ans = qmod((p + 1 ) >> 1 , tmp, p); return ans.x; }
普通分解质因数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 const int MAX_N = 100 + 10 ;int factor[MAX_N][2 ], fatcnt;int get_factors (int x) { fatcnt = 0 ; for (int i = 1 ; prime[i] * prime[i] <= x; ++i) { factor[fatcnt][1 ] = 0 ; if (x % prime[i] == 0 ) { factor[++fatcnt][0 ] = prime[i]; while (x % prime[i] == 0 ) { ++factor[fatcnt][1 ]; x /= prime[i]; } } } if (x > 1 ) { factor[++fatcnt][0 ] = x; factor[fatcnt][1 ] = 1 ; } return fatcnt; }
约数的和取余
求A B A^B A B 所有因子的和取模MOD,这里有一个计算1 + p + p 2 + ⋯ + p n 1 + p + p^2 + \dots + p^n 1 + p + p 2 + ⋯ + p n 的算法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ll qmod (ll a, ll n, ll MOD) { ll ans = 1 ; for (; n; n >>= 1 , a = a*a % MOD) if (n & 1 ) ans = ans*a % MOD; return ans; } ll sum (ll p, ll n, ll MOD) { if (p == 0 ) return 0 ; if (n == 0 ) return 1 ; if (n & 1 ) return (1 + qmod(p, n / 2 + 1 , MOD)) % MOD * sum(p, n / 2 , MOD) % MOD; return ((1 + qmod(p, n / 2 + 1 , MOD)) % MOD * sum(p, n / 2 , MOD) % MOD + qmod(p, n / 2 , MOD) % MOD) % MOD; } ll solve (ll A, ll B, ll MOD) { get_factors(A); ll ans = 1 ; for (int i = 1 ; i <= fatcnt; ++i) ans = ans * sum(factor[i][0 ], factor[i][1 ]*B, MOD) % MOD; return ans; }
组合数相关
一些定理
∑ m = 0 n C n m = 2 n \displaystyle\sum_{m=0}^{n} C_n^m = 2^n m = 0 ∑ n C n m = 2 n
奇数项和 = 偶数项和 = 2 n − 1 2^{n-1} 2 n − 1
k ∗ C n k = n ∗ C n − 1 k − 1 k * C_n^k = n * C_{n-1}^{k-1} k ∗ C n k = n ∗ C n − 1 k − 1
预处理组合数
1 2 3 4 5 6 7 8 9 10 const int MAX_N = 1010 ;const int MOD = 1e9 + 7 ;int C[MAX_N][MAX_N];void make_C () { for (int i = 0 ; i < MAX_N; ++i) C[i][0 ] = C[i][i] = 1 ; for (int i = 2 ; i < MAX_N; ++i) for (int j = 1 ; j < i; ++j) C[i][j] = (C[i - 1 ][j - 1 ] + C[i-1 ][j]) % MOD; }
求单个组合数
1 2 3 4 5 6 7 8 9 10 const int MAX_N = 1e5 + 10 ;const int MOD = 1e9 + 7 ;int fac[MAX_N], inv[MAX_N]; void cal (int n, int m) { if (n < m) return 0 ; if (n - m < m) m = n - m; return fac[n] * inv[m] % MOD * inv[ n-m ] % MOD; }
卢卡斯定理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #define ll long long ll inv (ll a, ll p) { return qmod(p-2 , a, p); } ll cal (ll a, ll b, ll p) { if (a < b) return 0 ; if (b > a-b) b = a-b; ll fz = 1 , fm = 1 ; for (ll i = 0 ; i < b; ++i) { fz = fz * (a-i) % p; fm = fm * (i+1 ) % p; } return fz * inv(fm, p) % p; } ll lucas (ll a, ll b, ll p) { if (b == 0 || a == b) return 1 ; return cal(a % p, b % p, p) * lucas(a / p, b / p, p) % p; }
斯特林数
第一类斯特林数:形如[ n m ] \left[\begin{matrix} {n} \\ {m} \end{matrix}\right] [ n m ] 或者s ( n , m ) s(n, m) s ( n , m ) ,表示将n n n 个不同元素分成m m m 组,每组是一个环 的方案数。由于是一个环,所以( 1 , 2 , 3 , 4 , 5 ) (1, 2, 3, 4, 5) ( 1 , 2 , 3 , 4 , 5 ) 和( 5 , 4 , 3 , 2 , 1 ) (5, 4, 3, 2, 1) ( 5 , 4 , 3 , 2 , 1 ) 其实是同一种方案。其中又分无符号斯特林数s u s_{u} s u 和有符号斯特林数s s s_{s} s s
第一类斯特林数又有如下性质:
s u ( n , 0 ) = 0 n s_{u}(n, 0) = 0^n s u ( n , 0 ) = 0 n
s u ( n , n ) = s u ( n , 1 ) = 1 s_{u}(n, n) = s_{u}(n, 1) = 1 s u ( n , n ) = s u ( n , 1 ) = 1
s u ( n , n − 1 ) = C n 2 s_{u}(n, n-1) = C_n^2 s u ( n , n − 1 ) = C n 2
s u ( n , 2 ) = ( n − 1 ) ⋅ ∑ i = 1 n − 1 1 i s_{u}(n, 2) = (n-1) \cdot \displaystyle\sum_{i=1}^{n-1} {\frac{1}{i}} s u ( n , 2 ) = ( n − 1 ) ⋅ i = 1 ∑ n − 1 i 1
s u ( n , n − 2 ) = 2 ⋅ C n 3 + 3 ⋅ C n 4 s_{u}(n, n-2) = 2 \cdot C_n^3 + 3 \cdot C_n^4 s u ( n , n − 2 ) = 2 ⋅ C n 3 + 3 ⋅ C n 4
∑ k = 0 n s u ( n , k ) = n ! \displaystyle\sum_{k=0}^{n}{s_{u}(n, k)} = n! k = 0 ∑ n s u ( n , k ) = n !
s u ( n + 1 , m ) = s u ( n , m − 1 ) + n ⋅ s u ( n , m ) s_{u}(n+1, m) = s_{u}(n, m-1) + n \cdot s_{u}(n, m) s u ( n + 1 , m ) = s u ( n , m − 1 ) + n ⋅ s u ( n , m )
s s ( n , m ) = ( − 1 ) n + m s u ( n , m ) s_{s}(n, m) = {(-1)}^{n+m}s_{u}(n, m) s s ( n , m ) = ( − 1 ) n + m s u ( n , m )
∑ k = 0 n s s ( n , k ) = 0 n \displaystyle\sum_{k=0}^{n}{s_{s}(n, k)} = 0^n k = 0 ∑ n s s ( n , k ) = 0 n ,注意0 0 = 1 0^0 = 1 0 0 = 1
代码实现第一类斯特林数:
1 2 3 4 5 6 7 8 9 10 11 #define ll long long const int MAX_N = 2000 + 10 ;const int MOD = 1e9 + 7 ;ll S[MAX_N][MAX_N]; void make_Stirling_1 () { memset (S, 0LL , sizeof (S)); S[0 ][0 ] = S[1 ][1 ] = 1LL ; for (int i = 2 ; i < MAX_N; ++i) for (int j = 1 ; j <= i; ++j) S[i][j] = (S[i-1 ][j-1 ] + (i-1 ) * S[i-1 ][j] % MOD) % MOD; }
第二类斯特林数:形如{ n m } \left\{\begin{matrix} {n} \\ {m}\end{matrix}\right\} { n m } 或者S ( n , m ) S(n, m) S ( n , m ) ,表示将n n n 个不同元素拆分成m m m 个集合的方案数。
则有如下性质:
前三个性质与第一类相同
S ( n , 2 ) = 2 n − 1 − 1 S(n, 2) = 2^{n-1} - 1 S ( n , 2 ) = 2 n − 1 − 1
S ( n , n − 1 ) = C n 2 S(n, n-1) = C_n^2 S ( n , n − 1 ) = C n 2
S ( n , n − 2 ) = C n 3 + 3 ⋅ C n 4 S(n, n-2) = C_n^3 + 3 \cdot C_n^4 S ( n , n − 2 ) = C n 3 + 3 ⋅ C n 4
S ( n , n − 3 ) = C n 4 + 10 ⋅ C n 5 + 15 ⋅ C n 6 S(n, n-3) = C_n^4 + 10 \cdot C_n^5 + 15 \cdot C_n^6 S ( n , n − 3 ) = C n 4 + 1 0 ⋅ C n 5 + 1 5 ⋅ C n 6
S ( n , 3 ) = 1 2 ( 3 n − 1 + 1 ) − 2 n − 1 S(n, 3) = \frac{1}{2}(3^{n-1} + 1) - 2^{n-1} S ( n , 3 ) = 2 1 ( 3 n − 1 + 1 ) − 2 n − 1
∑ k = 0 n S ( n , k ) = B n \displaystyle\sum_{k=0}^{n}{S(n, k)} = B_n k = 0 ∑ n S ( n , k ) = B n ,B n B_n B n 指的是Bell数
S ( n , m ) = 1 m ! k = 0 m ( − 1 ) k C m k ( m − k ) n S(n, m) = \frac{1}{m!} \displaystyle_{k=0}^{m} {(-1)}^{k}C_m^k {(m-k)}^n S ( n , m ) = m ! 1 k = 0 m ( − 1 ) k C m k ( m − k ) n
S ( n + 1 , m ) = S ( n , m − 1 ) + m ⋅ S ( n , m ) S(n+1, m) = S(n, m-1) + m \cdot S(n, m) S ( n + 1 , m ) = S ( n , m − 1 ) + m ⋅ S ( n , m )
代码实现第二类斯特林数:
1 2 3 4 5 6 7 8 9 10 11 #define ll long long const int MAX_N = 2000 + 10 ;const int MOD = 1e9 + 7 ;ll S[MAX_N][MAX_N]; void make_Stirling_2 () { memset (S, 0LL , sizeof (S)); S[0 ][0 ] = S[1 ][1 ] = 1LL ; for (int i = 2 ; i < MAX_N; ++i) for (int j = 1 ; j <= i; ++j) S[i][j] = (S[i-1 ][j-1 ] + j * S[i-1 ][j] % MOD) % MOD; }
Miller_Rabin 快速大素数测试
可以测试2 63 2^{63} 2 6 3 (甚至更高)以下的数是否是素数(但可能是伪素数)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #define ull unsigned long long const int S = 4 ; ull mulit_mod (ull n, ull a, ull MOD) { a %= MOD, n %= MOD; ull ans = 0 ; for (; n; n >>= 1 , a = (a + a) % MOD) if (n & 1 ) ans = (ans + a) % MOD; return ans; } ull pow_mod (ull n, ull a, ull MOD) { ull ans = 1 ; for (; n; n >>= 1 , a = mulit_mod(a, a, MOD)) if (n & 1 ) ans = mulit_mod(ans, a, MOD); return ans; } bool Miller_Rabin (ull n, ull a) { ull d = n-1 , s = 0 , t; while (!(d&1 )) d >>= 1 , ++s; t = pow_mod(d, a, n); if (t == 1 || t == -1 ) return true ; for (int i = 0 ; i < s; ++i) { if (t == n-1 ) return true ; t = mulit_mod(t, t, n); } return false ; } bool is_prime (ull n) { if (n < 2 ) return false ; if (n == 2 ) return true ; if ((n&1 ) == 0 ) return false ; srand(time(NULL )); for (int i = 0 ; i < S; ++i) { ull a = rand() % (n-1 ) + 1 ; if (a != 1 && n % a == 0 ) return false ; if (!Miller_Rabin(n, a)) return false ; } return true ; }
Pollard_rho大数分解质因数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 ll factor[100 ]; int fatcnt; ll gcd (ll a, ll b) { ll t; while (b) t = a, a = b, b = t%b; return a < 0 ? -a : a; } ll Pollard_rho (ll x, ll c) { ll i = 1 , k = 2 ; srand(time(NULL )); ll x0 = rand() % x; ll y = x0; while (true ) { ++i; x0 = (mulit_mod(x0, x0, x) + c) % x; ll d = gcd(y - x0, x); if (d != 1 && d != x) return d; if (y == x0) return x; if (i == k) {y = x0, k += k;} } } void find_fac (ll n, ll k) { if (n == 1 ) return ; if (is_prime(n)) { factor[++fatcnt] = n; return ; } ll p = n; int c = k; while (p >= n) p = Pollard_rho(p, c--); find_fac(p, k); find_fac(n / p, k); }
欧拉降幂公式
a b ≡ { a b % φ ( p ) , gcd ( a , p ) = 1 a b , gcd ( a , p ) ≠ 1 , b < φ ( p ) a b % φ ( p ) + φ ( p ) , gcd ( a , p ) ≠ 1 , b ≥ φ ( p ) ( m o d p ) a^b \equiv \begin{cases} a^{b \% \varphi(p)}, &{\gcd(a, p) = 1} \\ a^b, &{\gcd(a, p) \neq 1, b < \varphi(p)} \\ a^{b \% \varphi(p) + \varphi(p)}, &{\gcd(a, p) \neq 1, b \geq \varphi(p)} \end{cases} \pmod p
a b ≡ ⎩ ⎪ ⎨ ⎪ ⎧ a b % φ ( p ) , a b , a b % φ ( p ) + φ ( p ) , g cd( a , p ) = 1 g cd( a , p ) = 1 , b < φ ( p ) g cd( a , p ) = 1 , b ≥ φ ( p ) ( m o d p )
利用欧拉降幂求
a a a ⋅ ⋅ ⋅ a ⏟ n m o d p {\underbrace{a^{a^{a^{\sdot^{\sdot^{\sdot^{a}}}}}}}_n} \mod p
n a a a ⋅ ⋅ ⋅ a m o d p
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 #define ll long long ll qmod (ll a, ll n, ll MOD) { ll ans = 1 ; for (; n; n >>= 1 , a = a*a % MOD) if (n & 1 ) ans = ans*a % MOD; return ans; } ll get_log (ll x, ll a) { if (x < 1 ) return -1 ; return 1 + get_log(log (x)/log (a), a); } ll gcd (ll a, ll b) { return b ? gcd(b, a%b) : a; } ll f (ll a, ll n, ll p) { if (a == 1 || n == 0 ) return 1 %p; if (p == 1 ) return 0 ; if (n == 1 ) return a % p; if (gcd(a, p) == 1 ) { return qmod(a, f(a, n-1 , phi[p]), p); } else { ll k = get_log(phi[p], a); if (k <= n-1 ) return qmod(a, f(a, n-1 , phi[p]) + phi[p], p); else return qmod(a, f(a, n-1 , phi[p]), p); } }
BSGS大步小步算法
Baby-Step Giant-Step算法求解a x ≡ b ( m o d n ) a^x \equiv b \pmod n a x ≡ b ( m o d n ) ,求一个x ∈ [ 0 , n ) x \in {[0, n)} x ∈ [ 0 , n ) ,对于a , b , n a, b, n a , b , n 没有特殊要求。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #define ll long long const int MOD = 76543 ; int head[MOD], top;struct node { int hs, id, go; node() {} node(int a, int b, int c) { hs = a, id = b, go = c; } }a[MOD]; void insert (int x, int y) { int k = x%MOD; a[++top] = node(x, y, head[k]); head[k] = top; } int find (int x) { int k = x%MOD; for (int i = head[k]; i != -1 ; i = a[i].go) if (a[i].hs == x) return a[i].id; return -1 ; } int BSGS (int a, int b, int n) { memset (head, -1 , sizeof (head)); top = 0 ; if (b == 1 ) return 0 ; int m = sqrt (1.0 * n), j; ll x = 1 , p = 1 ; for (int i = 0 ; i < m; ++i, p = p*a % n) insert(p*b % n, i); for (ll i = m; ; i += m) { if ((j = find(x = x*p % n)) != -1 ) return i-j; if (i > n) break ; } return -1 ; }
莫比乌斯函数、反演
莫比乌斯函数:
μ ( d ) = { 1 , d = 0 ( − 1 ) k , d = p 1 ⋅ p 2 … p k , ∀ p i ≠ p j 0 , o t h e r s \mu(d) = \begin{cases}
1, & {d = 0} \\
{(-1)}^k, & {d = p_1 \cdot p_2 \dots p_k}, \forall p_i \not = p_j \\
0, & {others}
\end{cases} μ ( d ) = ⎩ ⎪ ⎨ ⎪ ⎧ 1 , ( − 1 ) k , 0 , d = 0 d = p 1 ⋅ p 2 … p k , ∀ p i = p j o t h e r s
有一些这样的性质:
∑ d ∣ n μ ( d ) = { 1 , n = 1 0 , n > 0 \displaystyle\sum_{d|n} {\mu(d)} =
\begin{cases}
1, & n = 1 \\
0, & n > 0
\end{cases} d ∣ n ∑ μ ( d ) = { 1 , 0 , n = 1 n > 0
∑ d ∣ n μ ( d ) d = φ ( n ) n , n ∈ N + \displaystyle\sum_{d|n} {\frac{\mu(d)}{d}} = {\frac{\varphi(n)}{n}} , {n \in N_+}
d ∣ n ∑ d μ ( d ) = n φ ( n ) , n ∈ N +
根据这样的性质便可以线性筛莫比乌斯函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 const int MAX_N = 1e6 + 10 ;bool vis[MAX_N];int CNT, prime[MAX_N], mu[MAX_N];void make_mobius () { memset (vis, false , sizeof (vis)); mu[1 ] = 1 ; CNT = 0 ; for (int i = 2 ; i < MAX_N; ++i) { if (!vis[i]) { prime[++CNT] = i; mu[i] = -1 ; } for (int j = 1 ; j <= CNT && i*prime[j] < MAX_N; ++j) { vis[i*prime[j]] = true ; if (i % prime[j] == 0 ) { mu[i * prime[j]] = 0 ; break ; } else mu[i * prime[j]] = -mu[i]; } } }
莫比乌斯反演:
形式一:
F ( n ) = ∑ d ∣ n f ( d ) ⟺ f ( n ) = ∑ d ∣ n μ ( d ) F ( n d ) F(n) = \displaystyle\sum_{d|n} {f(d)} \iff f(n) = \displaystyle\sum_{d|n} {\mu(d)F(\frac{n}{d})}
F ( n ) = d ∣ n ∑ f ( d ) ⟺ f ( n ) = d ∣ n ∑ μ ( d ) F ( d n )
形式二:
F ( n ) = ∑ n ∣ d f ( d ) ⟺ f ( n ) = ∑ n ∣ d μ ( d n ) F ( d ) F(n) = \displaystyle\sum_{n|d} {f(d)} \iff f(n) = \displaystyle\sum_{n|d} {\mu(\frac{d}{n})F(d)}
F ( n ) = n ∣ d ∑ f ( d ) ⟺ f ( n ) = n ∣ d ∑ μ ( n d ) F ( d )
牛顿迭代法求平方根
C++ 版本,精度有限
1 2 3 4 5 6 7 8 9 10 double sqrt_newton (double n) { const double eps = 1E-15 ; double x = 1 ; while (1 ) { double nx = (x + n / x) / 2 ; if (abs (x - nx) < eps) break ; x = nx; } return x; }
JAVA版本,精度较高
1 2 3 4 5 6 7 8 9 10 11 12 public static BigInteger isqrtNewton (BigInteger n) { BigInteger a = BigInteger.ONE.shiftLeft(n.bitLength() / 2 ); boolean p_dec = false ; for (;;) { BigInteger b = n.divide(a).add(a).shiftRight(1 ); if (a.compareTo(b) == 0 || a.compareTo(b) < 0 && p_dec) break ; p_dec = a.compareTo(b) > 0 ; a = b; } return a; }
高斯消元
线性基
斐波那契数列
通项公式:
F n = ( 1 + 5 2 ) n − ( 1 − 5 2 ) n 5 F_n = \frac{ {\left({ \frac{1 + \sqrt{5}}{2} } \right)}^n - {\left({ \frac{1 - \sqrt{5}}{2} } \right)}^n} {\sqrt{5}}
F n = 5 ( 2 1 + 5 ) n − ( 2 1 − 5 ) n
图论部分
邻接表存图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #define ll long long const ll INF = 1LL << 60 ;const int MAX_N = 1e5 + 10 ; const int MAX_M = 1e6 + 10 ; struct Edge { int to, dis, go; Edge(int a = 0 , int b = 0 , int c = 0 ) { to = a, dis = b, go = c; } }edge[MAX_M]; int head[MAX_N], tot;void add_edge (int u, int v, int dis) { edge[++tot] = Edge(v, dis, head[u]), head[u] = tot; }
Vector伪邻接表存图
1 2 3 4 5 6 7 8 9 10 11 12 const int MAX_N = 1e5 + 10 ;struct node { int to, dis; node() {} node(int a = 0 , int b = 0 ) { to = a, dis = b; } }; vector <node> G[MAX_N];void add_edge (int u, int v, int dis) { G[u].push_back(node(v, dis)); }
Dijkstra单源最短路
时间复杂度O ( n ⋅ log 2 n ) O(n \cdot \log_2n) O ( n ⋅ log 2 n ) ,不可以有负权边
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 #define ll long long struct node { int u; ll dis; node(int a = 0 , ll b = 0 ) { u = a, dis = b; } }; bool operator < (node a, node b) { if (a.dis != b.dis) return a.dis > b.dis; else return a.u > b.u; } bool vis[MAX_N];ll dist[MAX_N]; void Dijkstra (int s, int n) { for (int i = 1 ; i <= n; ++i) dist[i] = INF, vis[i] = false ; priority_queue <node> q; dist[s] = 0 ; q.push(node(s, 0 )); node t; int u, v, i; ll tmp; while (!q.empty()) { t = q.top(); q.pop(); u = t.u; if (vis[u]) continue ; vis[u] = true ; for (i = head[u]; i != -1 ; i = edge[i].go) { v = edge[i].to; tmp = dist[u] + edge[i].dis; if (dist[v] > tmp) { dist[v] = tmp; q.push(node(v, dist[v])); } } } }
SPFA单源最短路
时间复杂度O ( k E ) O(kE) O ( k E ) ,k k k 是点入队次数,E E E 是边数,其时间复杂度不固定,最坏可达到O ( n E ) O(nE) O ( n E ) ,但是可以判断是否有负权环(某个点入队n n n 次),也可以解决负权边问题。
有两种优化:用双端队列、栈代替普通队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #define ll long long bool vis[MAX_N];ll dist[MAX_N]; void SPFA (int s, int n) { for (int i = 1 ; i <= n; ++i) dist[i] = INF, vis[i] = false ; queue <int > q; dist[s] = 0 ; q.push(s); vis[s] = true ; int u, v, i; ll tmp; while (!q.empty()) { u = q.front(); q.pop(); vis[u] = false ; for (i = head[u]; i != -1 ; i = edge[i].go) { v = edge[i].to; tmp = dist[u] + edge[i].dis; if (dist[v] > tmp) { dist[v] = tmp; if (!vis[v]) { vis[v] = true ; q.push(v); } } } } }
Floyd多源最短路
时间复杂度O ( n 3 ) O(n^3) O ( n 3 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 const int MAX_N = 110 ; const int INF = 0x3f3f3f3f ;int G[MAX_N][MAX_N], dist[MAX_N][MAX_N];void floyd (int n) { for (int i = 1 ; i <= n; ++i) for (int j = 1 ; j <= n; ++j) dist[i][j] = INF; for (int k = 1 ; k <= n; ++k) for (int i = 1 ; i <= n; ++i) for (int j = 1 ; j <= n; ++j) { if (G[i][k] && G[k][j]) dist[i][j] = min(dist[i][j], G[i][k] + G[k][j]); if (G[i][j]) dist[i][j] = min(dist[i][j], G[i][j]); } }
最小生成树MST
Kruskal
利用并查集思想,用于解决大部分无向图的最小生成树问题。
时间复杂度大概在O ( m ∗ l o g 2 m + n ∗ α ( n ) ) ) O(m * log_2m + n * \alpha(n))) O ( m ∗ l o g 2 m + n ∗ α ( n ) ) ) 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 bool cmp (Edge x, Edge y) { if (x.dis != y.dis) return x.dis < y.dis; if (x.from != y.from) return x.from < y.from; return x.to < y.to; } int f[MAX_N];int find (int x) { return x == f[x] ? x : f[x] = find(f[x]); } void merge (int x, int y) { x = find(x), y = find(y); if (x != y) f[y] = x; } bool is_merge (int x, int y) { x = find(x), y = find(y); return x == y; } int kruskal (int n, int m) { int k = 0 , ans = 0 ; for (int i = 1 ; i <= n; ++i) f[i] = i; sort(edge + 1 , edge + 1 + m, cmp); for (int i = 1 ; i <= m && k < n-1 ; ++i) { int u = edge[i].from, v = edge[i].to; if (!is_merge(u, v)) { merge(u, v); ans += edge[i].dis; ++k; } } return k == n-1 ? ans : -1 ; }
Prim
将点集分为已访问点V V V 和未访问点E E E ,初始全是未访问点,先将任一点分到已访问点。选择V V V 到E E E 最短的一条边,将E E E 中该点加入V V V ,直到所有点都在V V V 。
用堆优化后时间复杂度为O ( ( n + m ) ∗ l o g 2 n ) O((n+m) * log_2n) O ( ( n + m ) ∗ l o g 2 n ) ,看起来比Kruskal优秀,但实际跑起来不一定。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 struct node { int u, dis; node(int a = 0 , int b = 0 ) { u = a, dis = b; } }; bool operator < (node x, node y) { if (x.dis != y.dis) return x.dis > y.dis; if (x.u != y.u) return x.u > y.u; } bool vis[MAX_N];int dist[MAX_N];void init (int n) { tot = 0 ; for (int i = 0 ; i <= n; ++i) vis[i] = false , head[i] = -1 , dist[i] = inf; } int prim (int n) { int i, u, v, k = 0 , ans = 0 ; node t; priority_queue <node> q; dist[1 ] = 0 ; q.push(node(1 , 0 )); while (k < n && !q.empty()) { t = q.top(); q.pop(); u = t.u; if (vis[u]) continue ; vis[u] = true , ans += t.dis, ++k; for (i = head[u]; i != -1 ; i = edge[i].go) { v = edge[i].to; if (!vis[v] && dist[v] > edge[i].dis) { dist[v] = edge[i].dis; q.push(node(v, dist[v])); } } } return k == n ? ans : -1 ; }
最近公共祖先(LCA)
二分图匹配
网络流
树分治(点分治)
字符串处理部分
KMP
exKMP
博弈论部分
nim博弈
n n n 堆物品,每堆a i a_i a i 个,两个玩家轮流取走任意堆的任意个物品,不可不取,取走最后一个的获胜。
定义N i m S u m = ⨁ i = 1 n a i NimSum = \displaystyle\bigoplus_{i=1}^{n} a_i N i m S u m = i = 1 ⨁ n a i ,当且仅当N i m S u m NimSum N i m S u m 为0 0 0 时,先手必败。
Bash博弈
只有一堆n n n 个物品,两个人轮流从中取物,最多取m m m 个,不可不取,最后取光者为胜。
当且仅当n m o d ( m + 1 ) = 0 n \mod (m+1) = 0 n m o d ( m + 1 ) = 0 时,先手必败。
Wythoff博弈
有两堆各若干个物品,两人轮流从中取物,至少取一堆中若干件物品,或从两堆中同时取相同件物品,最后取完者胜利。
设两堆物品分别为x , y ( x < y ) x,y (x < y) x , y ( x < y ) 个,令z = y − x z = y-x z = y − x ,当且仅当⌊ 5 + 1 2 ⋅ z ⌋ = x \left\lfloor\frac{\sqrt{5} + 1}{2} \cdot z \right\rfloor = x ⌊ 2 5 + 1 ⋅ z ⌋ = x 时,先手必败。
斐波那契博弈
有一堆若干个物品,两人轮流取,先手第一次取若干个,但不能把物品取完,之后每次去的物品数不能超过上一次取的物品数的两倍且至少一件,取走最后一件物品的人获胜。
当且仅当物品总数是斐波那契数时,先手必胜。
环形博弈
若干个物品连成环,每次取1 1 1 个或是相邻的2 2 2 个,取到最后一个的胜利。
当且仅当物品数量小于等于2 2 2 时,先手必胜。
SG函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 //f[N]:可改变当前状态的方式,N为方式的种类,f[N]要在getSG之前先预处理 //SG[]:0~n的SG函数值 //S[]:为x后继状态的集合 int f[N],SG[MAXN],S[MAXN]; void getSG(int n){ int i,j; memset(SG,0,sizeof(SG)); //因为SG[0]始终等于0,所以i从1开始 for(i = 1; i <= n; i++){ //每一次都要将上一状态 的 后继集合 重置 memset(S,0,sizeof(S)); for(j = 0; f[j] <= i && j <= N; j++) S[SG[i-f[j]]] = 1; //将后继状态的SG函数值进行标记 for(j = 0;; j++) if(!S[j]){ //查询当前后继状态SG值中最小的非零值 SG[i] = j; break; } } }
动态规划部分
背包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 const int MAX_N = 1e5 + 10 ; const int MAX_M = 1e5 + 10 ; int N, M, dp[MAX_M]; void ZeroOnePack (int cost, int weight) { for (int i = M; i >= cost; --i) dp[i] = max(dp[i], dp[i-cost] + weight); } void CompletePack (int cost, int weight) { for (int i = cost; i <= M; ++i) dp[i] = max(dp[i], dp[i-cost] + weight); } void MultiplePack (int cost, int weight, int cnt) { if (cost * cnt >= M) CompletePack(cost, weight); else { for (int k = 1 ; k < cnt; cnt -= k, k <<= 1 ) ZeroOnePack(k * cost, k * weight); if (cnt > 0 ) ZeroOnePack(cnt * cost, cnt * weight); } }
区间DP
针对可以将两个、多个部分整合(分解)得到答案的数据,建立转移方程。
f ( i , j ) = m e r g e { f ( i , k ) , f ( k ) } + c o s t f(i, j) = merge\{f(i, k), f(k)\} + cost
f ( i , j ) = m e r g e { f ( i , k ) , f ( k ) } + c o s t
c o s t cost c o s t 指代这段区间合并(分解)所要花费的代价。
计算几何部分
Kuangbin几何模板
二维计算几何
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 const double eps = 1e-8 ;const double inf = 1e20 ;const double pi = acos (-1.0 );const int maxp = 1010 ;int sgn (double x) { if (fabs (x) < eps)return 0 ; if (x < 0 )return -1 ; else return 1 ; } inline double sqr (double x) {return x*x;}struct Point { double x,y; Point(){} Point(double _x,double _y){ x = _x; y = _y; } void input () { scanf ("%lf%lf" ,&x,&y); } void output () { printf ("%.2f %.2f\n" ,x,y); } bool operator == (Point b)const { return sgn(x-b.x) == 0 && sgn(y-b.y) == 0 ; } bool operator < (Point b)const { return sgn(x-b.x)== 0 ?sgn(y-b.y)<0 :x<b.x; } Point operator -(const Point &b)const { return Point(x-b.x,y-b.y); } double operator ^(const Point &b)const { return x*b.y - y*b.x; } double operator *(const Point &b)const { return x*b.x + y*b.y; } double len () { return hypot(x,y); } double len2 () { return x*x + y*y; } double distance (Point p) { return hypot(x-p.x,y-p.y); } Point operator +(const Point &b)const { return Point(x+b.x,y+b.y); } Point operator *(const double &k)const { return Point(x*k,y*k); } Point operator /(const double &k)const { return Point(x/k,y/k); } double rad (Point a,Point b) { Point p = *this ; return fabs (atan2 ( fabs ((a-p)^(b-p)),(a-p)*(b-p) )); } Point trunc (double r) { double l = len(); if (!sgn(l))return *this ; r /= l; return Point(x*r,y*r); } Point rotleft () { return Point(-y,x); } Point rotright () { return Point(y,-x); } Point rotate (Point p,double angle) { Point v = (*this ) - p; double c = cos (angle), s = sin (angle); return Point(p.x + v.x*c - v.y*s,p.y + v.x*s + v.y*c); } }; struct Line { Point s,e; Line(){} Line(Point _s,Point _e){ s = _s; e = _e; } bool operator ==(Line v){ return (s == v.s)&&(e == v.e); } Line(Point p,double angle){ s = p; if (sgn(angle-pi/2 ) == 0 ){ e = (s + Point(0 ,1 )); } else { e = (s + Point(1 ,tan (angle))); } } Line(double a,double b,double c){ if (sgn(a) == 0 ){ s = Point(0 ,-c/b); e = Point(1 ,-c/b); } else if (sgn(b) == 0 ){ s = Point(-c/a,0 ); e = Point(-c/a,1 ); } else { s = Point(0 ,-c/b); e = Point(1 ,(-c-a)/b); } } void input () { s.input(); e.input(); } void adjust () { if (e < s)swap(s,e); } double length () { return s.distance(e); } double angle () { double k = atan2 (e.y-s.y,e.x-s.x); if (sgn(k) < 0 )k += pi; if (sgn(k-pi) == 0 )k -= pi; return k; } int relation (Point p) { int c = sgn((p-s)^(e-s)); if (c < 0 )return 1 ; else if (c > 0 )return 2 ; else return 3 ; } bool pointonseg (Point p) { return sgn((p-s)^(e-s)) == 0 && sgn((p-s)*(p-e)) <= 0 ; } bool parallel (Line v) { return sgn((e-s)^(v.e-v.s)) == 0 ; } int segcrossseg (Line v) { int d1 = sgn((e-s)^(v.s-s)); int d2 = sgn((e-s)^(v.e-s)); int d3 = sgn((v.e-v.s)^(s-v.s)); int d4 = sgn((v.e-v.s)^(e-v.s)); if ( (d1^d2)==-2 && (d3^d4)==-2 )return 2 ; return (d1==0 && sgn((v.s-s)*(v.s-e))<=0 ) || (d2==0 && sgn((v.e-s)*(v.e-e))<=0 ) || (d3==0 && sgn((s-v.s)*(s-v.e))<=0 ) || (d4==0 && sgn((e-v.s)*(e-v.e))<=0 ); } int linecrossseg (Line v) { int d1 = sgn((e-s)^(v.s-s)); int d2 = sgn((e-s)^(v.e-s)); if ((d1^d2)==-2 ) return 2 ; return (d1==0 ||d2==0 ); } int linecrossline (Line v) { if ((*this ).parallel(v)) return v.relation(s)==3 ; return 2 ; } Point crosspoint (Line v) { double a1 = (v.e-v.s)^(s-v.s); double a2 = (v.e-v.s)^(e-v.s); return Point((s.x*a2-e.x*a1)/(a2-a1),(s.y*a2-e.y*a1)/(a2-a1)); } double dispointtoline (Point p) { return fabs ((p-s)^(e-s))/length(); } double dispointtoseg (Point p) { if (sgn((p-s)*(e-s))<0 || sgn((p-e)*(s-e))<0 ) return min(p.distance(s),p.distance(e)); return dispointtoline(p); } double dissegtoseg (Line v) { return min(min(dispointtoseg(v.s),dispointtoseg(v.e)),min(v.dispointtoseg(s),v.dispointtoseg(e))); } Point lineprog (Point p) { return s + ( ((e-s)*((e-s)*(p-s)))/((e-s).len2()) ); } Point symmetrypoint (Point p) { Point q = lineprog(p); return Point(2 *q.x-p.x,2 *q.y-p.y); } }; struct circle { Point p; double r; circle(){} circle(Point _p,double _r){ p = _p; r = _r; } circle(double x,double y,double _r){ p = Point(x,y); r = _r; } circle(Point a,Point b,Point c){ Line u = Line((a+b)/2 ,((a+b)/2 )+((b-a).rotleft())); Line v = Line((b+c)/2 ,((b+c)/2 )+((c-b).rotleft())); p = u.crosspoint(v); r = p.distance(a); } circle(Point a,Point b,Point c,bool t){ Line u,v; double m = atan2 (b.y-a.y,b.x-a.x), n = atan2 (c.y-a.y,c.x-a.x); u.s = a; u.e = u.s + Point(cos ((n+m)/2 ),sin ((n+m)/2 )); v.s = b; m = atan2 (a.y-b.y,a.x-b.x) , n = atan2 (c.y-b.y,c.x-b.x); v.e = v.s + Point(cos ((n+m)/2 ),sin ((n+m)/2 )); p = u.crosspoint(v); r = Line(a,b).dispointtoseg(p); } void input () { p.input(); scanf ("%lf" ,&r); } void output () { printf ("%.2lf %.2lf %.2lf\n" ,p.x,p.y,r); } bool operator == (circle v){ return (p==v.p) && sgn(r-v.r)==0 ; } bool operator < (circle v)const { return ((p<v.p)||((p==v.p)&&sgn(r-v.r)<0 )); } double area () { return pi*r*r; } double circumference () { return 2 *pi*r; } int relation (Point b) { double dst = b.distance(p); if (sgn(dst-r) < 0 )return 2 ; else if (sgn(dst-r)==0 )return 1 ; return 0 ; } int relationseg (Line v) { double dst = v.dispointtoseg(p); if (sgn(dst-r) < 0 )return 2 ; else if (sgn(dst-r) == 0 )return 1 ; return 0 ; } int relationline (Line v) { double dst = v.dispointtoline(p); if (sgn(dst-r) < 0 )return 2 ; else if (sgn(dst-r) == 0 )return 1 ; return 0 ; } int relationcircle (circle v) { double d = p.distance(v.p); if (sgn(d-r-v.r) > 0 )return 5 ; if (sgn(d-r-v.r) == 0 )return 4 ; double l = fabs (r-v.r); if (sgn(d-r-v.r)<0 && sgn(d-l)>0 )return 3 ; if (sgn(d-l)==0 )return 2 ; if (sgn(d-l)<0 )return 1 ; } int pointcrosscircle (circle v,Point &p1,Point &p2) { int rel = relationcircle(v); if (rel == 1 || rel == 5 )return 0 ; double d = p.distance(v.p); double l = (d*d+r*r-v.r*v.r)/(2 *d); double h = sqrt (r*r-l*l); Point tmp = p + (v.p-p).trunc(l); p1 = tmp + ((v.p-p).rotleft().trunc(h)); p2 = tmp + ((v.p-p).rotright().trunc(h)); if (rel == 2 || rel == 4 ) return 1 ; return 2 ; } int pointcrossline (Line v,Point &p1,Point &p2) { if (!(*this ).relationline(v))return 0 ; Point a = v.lineprog(p); double d = v.dispointtoline(p); d = sqrt (r*r-d*d); if (sgn(d) == 0 ){ p1 = a; p2 = a; return 1 ; } p1 = a + (v.e-v.s).trunc(d); p2 = a - (v.e-v.s).trunc(d); return 2 ; } int gercircle (Point a,Point b,double r1,circle &c1,circle &c2) { circle x(a,r1),y(b,r1); int t = x.pointcrosscircle(y,c1.p,c2.p); if (!t)return 0 ; c1.r = c2.r = r; return t; } int getcircle (Line u,Point q,double r1,circle &c1,circle &c2) { double dis = u.dispointtoline(q); if (sgn(dis-r1*2 )>0 )return 0 ; if (sgn(dis) == 0 ){ c1.p = q + ((u.e-u.s).rotleft().trunc(r1)); c2.p = q + ((u.e-u.s).rotright().trunc(r1)); c1.r = c2.r = r1; return 2 ; } Line u1 = Line((u.s + (u.e-u.s).rotleft().trunc(r1)),(u.e + (u.e-u.s).rotleft().trunc(r1))); Line u2 = Line((u.s + (u.e-u.s).rotright().trunc(r1)),(u.e + (u.e-u.s).rotright().trunc(r1))); circle cc = circle(q,r1); Point p1,p2; if (!cc.pointcrossline(u1,p1,p2))cc.pointcrossline(u2,p1,p2); c1 = circle(p1,r1); if (p1 == p2){ c2 = c1; return 1 ; } c2 = circle(p2,r1); return 2 ; } int getcircle (Line u,Line v,double r1,circle &c1,circle &c2,circle &c3,circle &c4) { if (u.parallel(v))return 0 ; Line u1 = Line(u.s + (u.e-u.s).rotleft().trunc(r1),u.e + (u.e-u.s).rotleft().trunc(r1)); Line u2 = Line(u.s + (u.e-u.s).rotright().trunc(r1),u.e + (u.e-u.s).rotright().trunc(r1)); Line v1 = Line(v.s + (v.e-v.s).rotleft().trunc(r1),v.e + (v.e-v.s).rotleft().trunc(r1)); Line v2 = Line(v.s + (v.e-v.s).rotright().trunc(r1),v.e + (v.e-v.s).rotright().trunc(r1)); c1.r = c2.r = c3.r = c4.r = r1; c1.p = u1.crosspoint(v1); c2.p = u1.crosspoint(v2); c3.p = u2.crosspoint(v1); c4.p = u2.crosspoint(v2); return 4 ; } int getcircle (circle cx,circle cy,double r1,circle &c1,circle &c2) { circle x(cx.p,r1+cx.r),y(cy.p,r1+cy.r); int t = x.pointcrosscircle(y,c1.p,c2.p); if (!t)return 0 ; c1.r = c2.r = r1; return t; } int tangentline (Point q,Line &u,Line &v) { int x = relation(q); if (x == 2 )return 0 ; if (x == 1 ){ u = Line(q,q + (q-p).rotleft()); v = u; return 1 ; } double d = p.distance(q); double l = r*r/d; double h = sqrt (r*r-l*l); u = Line(q,p + ((q-p).trunc(l) + (q-p).rotleft().trunc(h))); v = Line(q,p + ((q-p).trunc(l) + (q-p).rotright().trunc(h))); return 2 ; } double areacircle (circle v) { int rel = relationcircle(v); if (rel >= 4 )return 0.0 ; if (rel <= 2 )return min(area(),v.area()); double d = p.distance(v.p); double hf = (r+v.r+d)/2.0 ; double ss = 2 *sqrt (hf*(hf-r)*(hf-v.r)*(hf-d)); double a1 = acos ((r*r+d*d-v.r*v.r)/(2.0 *r*d)); a1 = a1*r*r; double a2 = acos ((v.r*v.r+d*d-r*r)/(2.0 *v.r*d)); a2 = a2*v.r*v.r; return a1+a2-ss; } double areatriangle (Point a,Point b) { if (sgn((p-a)^(p-b)) == 0 )return 0.0 ; Point q[5 ]; int len = 0 ; q[len++] = a; Line l (a,b) ; Point p1,p2; if (pointcrossline(l,q[1 ],q[2 ])==2 ){ if (sgn((a-q[1 ])*(b-q[1 ]))<0 )q[len++] = q[1 ]; if (sgn((a-q[2 ])*(b-q[2 ]))<0 )q[len++] = q[2 ]; } q[len++] = b; if (len == 4 && sgn((q[0 ]-q[1 ])*(q[2 ]-q[1 ]))>0 )swap(q[1 ],q[2 ]); double res = 0 ; for (int i = 0 ;i < len-1 ;i++){ if (relation(q[i])==0 ||relation(q[i+1 ])==0 ){ double arg = p.rad(q[i],q[i+1 ]); res += r*r*arg/2.0 ; } else { res += fabs ((q[i]-p)^(q[i+1 ]-p))/2.0 ; } } return res; } }; struct polygon { int n; Point p[maxp]; Line l[maxp]; void input (int _n) { n = _n; for (int i = 0 ;i < n;i++) p[i].input(); } void add (Point q) { p[n++] = q; } void getline () { for (int i = 0 ;i < n;i++){ l[i] = Line(p[i],p[(i+1 )%n]); } } struct cmp { Point p; cmp(const Point &p0){p = p0;} bool operator () (const Point &aa,const Point &bb) { Point a = aa, b = bb; int d = sgn((a-p)^(b-p)); if (d == 0 ){ return sgn(a.distance(p)-b.distance(p)) < 0 ; } return d > 0 ; } }; void norm () { Point mi = p[0 ]; for (int i = 1 ;i < n;i++)mi = min(mi,p[i]); sort(p,p+n,cmp(mi)); } void getconvex (polygon &convex) { sort(p,p+n); convex.n = n; for (int i = 0 ;i < min(n,2 );i++){ convex.p[i] = p[i]; } if (convex.n == 2 && (convex.p[0 ] == convex.p[1 ]))convex.n--; if (n <= 2 )return ; int &top = convex.n; top = 1 ; for (int i = 2 ;i < n;i++){ while (top && sgn((convex.p[top]-p[i])^(convex.p[top-1 ]-p[i])) <= 0 ) top--; convex.p[++top] = p[i]; } int temp = top; convex.p[++top] = p[n-2 ]; for (int i = n-3 ;i >= 0 ;i--){ while (top != temp && sgn((convex.p[top]-p[i])^(convex.p[top-1 ]-p[i])) <= 0 ) top--; convex.p[++top] = p[i]; } if (convex.n == 2 && (convex.p[0 ] == convex.p[1 ]))convex.n--; convex.norm(); } void Graham (polygon &convex) { norm(); int &top = convex.n; top = 0 ; if (n == 1 ){ top = 1 ; convex.p[0 ] = p[0 ]; return ; } if (n == 2 ){ top = 2 ; convex.p[0 ] = p[0 ]; convex.p[1 ] = p[1 ]; if (convex.p[0 ] == convex.p[1 ])top--; return ; } convex.p[0 ] = p[0 ]; convex.p[1 ] = p[1 ]; top = 2 ; for (int i = 2 ;i < n;i++){ while ( top > 1 && sgn((convex.p[top-1 ]-convex.p[top-2 ])^(p[i]-convex.p[top-2 ])) <= 0 ) top--; convex.p[top++] = p[i]; } if (convex.n == 2 && (convex.p[0 ] == convex.p[1 ]))convex.n--; } bool isconvex () { bool s[2 ]; memset (s,false ,sizeof (s)); for (int i = 0 ;i < n;i++){ int j = (i+1 )%n; int k = (j+1 )%n; s[sgn((p[j]-p[i])^(p[k]-p[i]))+1 ] = true ; if (s[0 ] && s[2 ])return false ; } return true ; } int relationpoint (Point q) { for (int i = 0 ;i < n;i++){ if (p[i] == q)return 3 ; } getline(); for (int i = 0 ;i < n;i++){ if (l[i].pointonseg(q))return 2 ; } int cnt = 0 ; for (int i = 0 ;i < n;i++){ int j = (i+1 )%n; int k = sgn((q-p[j])^(p[i]-p[j])); int u = sgn(p[i].y-q.y); int v = sgn(p[j].y-q.y); if (k > 0 && u < 0 && v >= 0 )cnt++; if (k < 0 && v < 0 && u >= 0 )cnt--; } return cnt != 0 ; } void convexcut (Line u,polygon &po) { int &top = po.n; top = 0 ; for (int i = 0 ;i < n;i++){ int d1 = sgn((u.e-u.s)^(p[i]-u.s)); int d2 = sgn((u.e-u.s)^(p[(i+1 )%n]-u.s)); if (d1 >= 0 )po.p[top++] = p[i]; if (d1*d2 < 0 )po.p[top++] = u.crosspoint(Line(p[i],p[(i+1 )%n])); } } double getcircumference () { double sum = 0 ; for (int i = 0 ;i < n;i++){ sum += p[i].distance(p[(i+1 )%n]); } return sum; } double getarea () { double sum = 0 ; for (int i = 0 ;i < n;i++){ sum += (p[i]^p[(i+1 )%n]); } return fabs (sum)/2 ; } bool getdir () { double sum = 0 ; for (int i = 0 ;i < n;i++) sum += (p[i]^p[(i+1 )%n]); if (sgn(sum) > 0 )return 1 ; return 0 ; } Point getbarycentre () { Point ret (0 ,0 ) ; double area = 0 ; for (int i = 1 ;i < n-1 ;i++){ double tmp = (p[i]-p[0 ])^(p[i+1 ]-p[0 ]); if (sgn(tmp) == 0 )continue ; area += tmp; ret.x += (p[0 ].x+p[i].x+p[i+1 ].x)/3 *tmp; ret.y += (p[0 ].y+p[i].y+p[i+1 ].y)/3 *tmp; } if (sgn(area)) ret = ret/area; return ret; } double areacircle (circle c) { double ans = 0 ; for (int i = 0 ;i < n;i++){ int j = (i+1 )%n; if (sgn( (p[j]-c.p)^(p[i]-c.p) ) >= 0 ) ans += c.areatriangle(p[i],p[j]); else ans -= c.areatriangle(p[i],p[j]); } return fabs (ans); } int relationcircle (circle c) { getline(); int x = 2 ; if (relationpoint(c.p) != 1 )return 0 ; for (int i = 0 ;i < n;i++){ if (c.relationseg(l[i])==2 )return 0 ; if (c.relationseg(l[i])==1 )x = 1 ; } return x; } }; double cross (Point A,Point B,Point C) { return (B-A)^(C-A); } double dot (Point A,Point B,Point C) { return (B-A)*(C-A); } double minRectangleCover (polygon A) { if (A.n < 3 )return 0.0 ; A.p[A.n] = A.p[0 ]; double ans = -1 ; int r = 1 , p = 1 , q; for (int i = 0 ;i < A.n;i++){ while ( sgn( cross(A.p[i],A.p[i+1 ],A.p[r+1 ]) - cross(A.p[i],A.p[i+1 ],A.p[r]) ) >= 0 ) r = (r+1 )%A.n; while (sgn( dot(A.p[i],A.p[i+1 ],A.p[p+1 ]) - dot(A.p[i],A.p[i+1 ],A.p[p]) ) >= 0 ) p = (p+1 )%A.n; if (i == 0 )q = p; while (sgn(dot(A.p[i],A.p[i+1 ],A.p[q+1 ]) - dot(A.p[i],A.p[i+1 ],A.p[q])) <= 0 ) q = (q+1 )%A.n; double d = (A.p[i] - A.p[i+1 ]).len2(); double tmp = cross(A.p[i],A.p[i+1 ],A.p[r]) * (dot(A.p[i],A.p[i+1 ],A.p[p]) - dot(A.p[i],A.p[i+1 ],A.p[q]))/d; if (ans < 0 || ans > tmp)ans = tmp; } return ans; } vector <Point> convexCut (const vector <Point> &ps,Point q1,Point q2) { vector <Point>qs; int n = ps.size(); for (int i = 0 ;i < n;i++){ Point p1 = ps[i], p2 = ps[(i+1 )%n]; int d1 = sgn((q2-q1)^(p1-q1)), d2 = sgn((q2-q1)^(p2-q1)); if (d1 >= 0 ) qs.push_back(p1); if (d1 * d2 < 0 ) qs.push_back(Line(p1,p2).crosspoint(Line(q1,q2))); } return qs; } struct halfplane :public Line{ double angle; halfplane(){} halfplane(Point _s,Point _e){ s = _s; e = _e; } halfplane(Line v){ s = v.s; e = v.e; } void calcangle () { angle = atan2 (e.y-s.y,e.x-s.x); } bool operator <(const halfplane &b)const { return angle < b.angle; } }; struct halfplanes { int n; halfplane hp[maxp]; Point p[maxp]; int que[maxp]; int st,ed; void push (halfplane tmp) { hp[n++] = tmp; } void unique () { int m = 1 ; for (int i = 1 ;i < n;i++){ if (sgn(hp[i].angle-hp[i-1 ].angle) != 0 ) hp[m++] = hp[i]; else if (sgn( (hp[m-1 ].e-hp[m-1 ].s)^(hp[i].s-hp[m-1 ].s) ) > 0 ) hp[m-1 ] = hp[i]; } n = m; } bool halfplaneinsert () { for (int i = 0 ;i < n;i++)hp[i].calcangle(); sort(hp,hp+n); unique(); que[st=0 ] = 0 ; que[ed=1 ] = 1 ; p[1 ] = hp[0 ].crosspoint(hp[1 ]); for (int i = 2 ;i < n;i++){ while (st<ed && sgn((hp[i].e-hp[i].s)^(p[ed]-hp[i].s))<0 )ed--; while (st<ed && sgn((hp[i].e-hp[i].s)^(p[st+1 ]-hp[i].s))<0 )st++; que[++ed] = i; if (hp[i].parallel(hp[que[ed-1 ]]))return false ; p[ed]=hp[i].crosspoint(hp[que[ed-1 ]]); } while (st<ed && sgn((hp[que[st]].e-hp[que[st]].s)^(p[ed]-hp[que[st]].s))<0 )ed--; while (st<ed && sgn((hp[que[ed]].e-hp[que[ed]].s)^(p[st+1 ]-hp[que[ed]].s))<0 )st++; if (st+1 >=ed)return false ; return true ; } void getconvex (polygon &con) { p[st] = hp[que[st]].crosspoint(hp[que[ed]]); con.n = ed-st+1 ; for (int j = st,i = 0 ;j <= ed;i++,j++) con.p[i] = p[j]; } }; const int maxn = 1010 ;struct circles { circle c[maxn]; double ans[maxn]; double pre[maxn]; int n; circles(){} void add (circle cc) { c[n++] = cc; } bool inner (circle x,circle y) { if (x.relationcircle(y) != 1 )return 0 ; return sgn(x.r-y.r)<=0 ?1 :0 ; } void init_or () { bool mark[maxn] = {0 }; int i,j,k=0 ; for (i = 0 ;i < n;i++){ for (j = 0 ;j < n;j++) if (i != j && !mark[j]){ if ( (c[i]==c[j])||inner(c[i],c[j]) )break ; } if (j < n)mark[i] = 1 ; } for (i = 0 ;i < n;i++) if (!mark[i]) c[k++] = c[i]; n = k; } void init_add () { int i,j,k; bool mark[maxn] = {0 }; for (i = 0 ;i < n;i++){ for (j = 0 ;j < n;j++) if (i != j && !mark[j]){ if ( (c[i]==c[j])||inner(c[j],c[i]) )break ; } if (j < n)mark[i] = 1 ; } for (i = 0 ;i < n;i++) if (!mark[i]) c[k++] = c[i]; n = k; } double areaarc (double th,double r) { return 0.5 *r*r*(th-sin (th)); } void getarea () { memset (ans,0 ,sizeof (ans)); vector <pair <double ,int > >v; for (int i = 0 ;i < n;i++){ v.clear(); v.push_back(make_pair (-pi,1 )); v.push_back(make_pair (pi,-1 )); for (int j = 0 ;j < n;j++) if (i != j){ Point q = (c[j].p - c[i].p); double ab = q.len(),ac = c[i].r, bc = c[j].r; if (sgn(ab+ac-bc)<=0 ){ v.push_back(make_pair (-pi,1 )); v.push_back(make_pair (pi,-1 )); continue ; } if (sgn(ab+bc-ac)<=0 )continue ; if (sgn(ab-ac-bc)>0 )continue ; double th = atan2 (q.y,q.x), fai = acos ((ac*ac+ab*ab-bc*bc)/(2.0 *ac*ab)); double a0 = th-fai; if (sgn(a0+pi)<0 )a0+=2 *pi; double a1 = th+fai; if (sgn(a1-pi)>0 )a1-=2 *pi; if (sgn(a0-a1)>0 ){ v.push_back(make_pair (a0,1 )); v.push_back(make_pair (pi,-1 )); v.push_back(make_pair (-pi,1 )); v.push_back(make_pair (a1,-1 )); } else { v.push_back(make_pair (a0,1 )); v.push_back(make_pair (a1,-1 )); } } sort(v.begin(),v.end()); int cur = 0 ; for (int j = 0 ;j < v.size();j++){ if (cur && sgn(v[j].first-pre[cur])){ ans[cur] += areaarc(v[j].first-pre[cur],c[i].r); ans[cur] += 0.5 *(Point(c[i].p.x+c[i].r*cos (pre[cur]),c[i].p.y+c[i].r*sin (pre[cur]))^Point(c[i].p.x+c[i].r*cos (v[j].first),c[i].p.y+c[i].r*sin (v[j].first))); } cur += v[j].second; pre[cur] = v[j].first; } } for (int i = 1 ;i < n;i++) ans[i] -= ans[i+1 ]; } };
三维计算几何
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 const double eps = 1e-8 ;int sgn (double x) { if (fabs (x) < eps)return 0 ; if (x < 0 )return -1 ; else return 1 ; } struct Point3 { double x,y,z; Point3(double _x = 0 ,double _y = 0 ,double _z = 0 ){ x = _x; y = _y; z = _z; } void input () { scanf ("%lf%lf%lf" ,&x,&y,&z); } void output () { scanf ("%.2lf %.2lf %.2lf\n" ,x,y,z); } bool operator ==(const Point3 &b)const { return sgn(x-b.x) == 0 && sgn(y-b.y) == 0 && sgn(z-b.z) == 0 ; } bool operator <(const Point3 &b)const { return sgn(x-b.x)==0 ?(sgn(y-b.y)==0 ?sgn(z-b.z)<0 :y<b.y):x<b.x; } double len () { return sqrt (x*x+y*y+z*z); } double len2 () { return x*x+y*y+z*z; } double distance (const Point3 &b) const { return sqrt ((x-b.x)*(x-b.x)+(y-b.y)*(y-b.y)+(z-b.z)*(z-b.z)); } Point3 operator -(const Point3 &b)const { return Point3(x-b.x,y-b.y,z-b.z); } Point3 operator +(const Point3 &b)const { return Point3(x+b.x,y+b.y,z+b.z); } Point3 operator *(const double &k)const { return Point3(x*k,y*k,z*k); } Point3 operator /(const double &k)const { return Point3(x/k,y/k,z/k); } double operator *(const Point3 &b)const { return x*b.x+y*b.y+z*b.z; } Point3 operator ^(const Point3 &b)const { return Point3(y*b.z-z*b.y,z*b.x-x*b.z,x*b.y-y*b.x); } double rad (Point3 a,Point3 b) { Point3 p = (*this ); return acos ( ( (a-p)*(b-p) )/ (a.distance(p)*b.distance(p)) ); } Point3 trunc (double r) { double l = len(); if (!sgn(l))return *this ; r /= l; return Point3(x*r,y*r,z*r); } }; struct Line3 { Point3 s,e; Line3(){} Line3(Point3 _s,Point3 _e) { s = _s; e = _e; } bool operator ==(const Line3 v) { return (s==v.s)&&(e==v.e); } void input () { s.input(); e.input(); } double length () { return s.distance(e); } double dispointtoline (Point3 p) { return ((e-s)^(p-s)).len()/s.distance(e); } double dispointtoseg (Point3 p) { if (sgn((p-s)*(e-s)) < 0 || sgn((p-e)*(s-e)) < 0 ) return min(p.distance(s),e.distance(p)); return dispointtoline(p); } Point3 lineprog (Point3 p) { return s + ( ((e-s)*((e-s)*(p-s)))/((e-s).len2()) ); } Point3 rotate (Point3 p,double ang) { if (sgn(((s-p)^(e-p)).len()) == 0 )return p; Point3 f1 = (e-s)^(p-s); Point3 f2 = (e-s)^(f1); double len = ((s-p)^(e-p)).len()/s.distance(e); f1 = f1.trunc(len); f2 = f2.trunc(len); Point3 h = p+f2; Point3 pp = h+f1; return h + ((p-h)*cos (ang)) + ((pp-h)*sin (ang)); } bool pointonseg (Point3 p) { return sgn( ((s-p)^(e-p)).len() ) == 0 && sgn((s-p)*(e-p)) == 0 ; } }; struct Plane { Point3 a,b,c,o; Plane(){} Plane(Point3 _a,Point3 _b,Point3 _c) { a = _a; b = _b; c = _c; o = pvec(); } Point3 pvec () { return (b-a)^(c-a); } Plane(double _a,double _b,double _c,double _d) { o = Point3(_a,_b,_c); if (sgn(_a) != 0 ) a = Point3((-_d-_c-_b)/_a,1 ,1 ); else if (sgn(_b) != 0 ) a = Point3(1 ,(-_d-_c-_a)/_b,1 ); else if (sgn(_c) != 0 ) a = Point3(1 ,1 ,(-_d-_a-_b)/_c); } bool pointonplane (Point3 p) { return sgn((p-a)*o) == 0 ; } double angleplane (Plane f) { return acos (o*f.o)/(o.len()*f.o.len()); } int crossline (Line3 u,Point3 &p) { double x = o*(u.e-a); double y = o*(u.s-a); double d = x-y; if (sgn(d) == 0 )return 0 ; p = ((u.s*x)-(u.e*y))/d; return 1 ; } Point3 pointtoplane (Point3 p) { Line3 u = Line3(p,p+o); crossline(u,p); return p; } int crossplane (Plane f,Line3 &u) { Point3 oo = o^f.o; Point3 v = o^oo; double d = fabs (f.o*v); if (sgn(d) == 0 )return 0 ; Point3 q = a + (v*(f.o*(f.a-a))/d); u = Line3(q,q+oo); return 1 ; } };
杂项
竞赛常用快速读入骚操作
在读入/输出大量(一般1 0 7 10^7 1 0 7 量级以上)的数据,cin/cout会耗费大量的时间去同步scanf/printf的缓冲区,当然,有时候甚至scanf/printf也不够用。
关闭iostream同步流
1 2 3 4 std ::ios::sync_with_stdio(false );std ::cin .tie(0 );
普通快速读写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 inline void read_int (int &X) { X = 0 ; int w = 0 ; char ch = 0 ; while (!isdigit (ch)) w |= ch=='-' , ch = getchar(); while ( isdigit (ch)) X = (X<<3 )+ (X<<1 ) + (ch-48 ), ch = getchar(); X = w ? -X : X; } inline void write_int (int x) { static int sta[35 ]; int top = 0 ; do { sta[top++] = x % 10 , x /= 10 ; } while (x); while (top) putchar (sta[--top] + 48 ); }
利用fread快读
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 namespace fastIO {#define BUF_SIZE 100000 bool IOerror = 0 ; inline char nc () { static char buf[BUF_SIZE], *p1 = buf + BUF_SIZE, *pend = buf + BUF_SIZE; if (p1 == pend) { p1 = buf; pend = buf + fread(buf, 1 , BUF_SIZE, stdin ); if (pend == p1) { IOerror = 1 ; return -1 ; } } return *p1++; } inline bool blank (char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' ; } inline void read (int &x) { char ch; while (blank(ch = nc())); if (IOerror) return ; for (x = ch - '0' ; (ch = nc()) >= '0' && ch <= '9' ; x = x * 10 + ch - '0' ); } #undef BUF_SIZE }; using namespace fastIO;
Real FastIO(抄来的)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 namespace fastIO{ #define BUF_SIZE 100000 #define OUT_SIZE 100000 #define ll long long bool IOerror=0 ; inline char nc () { static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE; if (p1==pend){ p1=buf; pend=buf+fread(buf,1 ,BUF_SIZE,stdin ); if (pend==p1){IOerror=1 ;return -1 ;} } return *p1++; } inline bool blank (char ch) {return ch==' ' ||ch=='\n' ||ch=='\r' ||ch=='\t' ;} inline void read (int &x) { bool sign=0 ; char ch=nc(); x=0 ; for (;blank(ch);ch=nc()); if (IOerror)return ; if (ch=='-' )sign=1 ,ch=nc(); for (;ch>='0' &&ch<='9' ;ch=nc())x=x*10 +ch-'0' ; if (sign)x=-x; } inline void read (ll &x) { bool sign=0 ; char ch=nc(); x=0 ; for (;blank(ch);ch=nc()); if (IOerror)return ; if (ch=='-' )sign=1 ,ch=nc(); for (;ch>='0' &&ch<='9' ;ch=nc())x=x*10 +ch-'0' ; if (sign)x=-x; } inline void read (double &x) { bool sign=0 ; char ch=nc(); x=0 ; for (;blank(ch);ch=nc()); if (IOerror)return ; if (ch=='-' )sign=1 ,ch=nc(); for (;ch>='0' &&ch<='9' ;ch=nc())x=x*10 +ch-'0' ; if (ch=='.' ){ double tmp=1 ; ch=nc(); for (;ch>='0' &&ch<='9' ;ch=nc())tmp/=10.0 ,x+=tmp*(ch-'0' ); } if (sign)x=-x; } inline void read (char *s) { char ch=nc(); for (;blank(ch);ch=nc()); if (IOerror)return ; for (;!blank(ch)&&!IOerror;ch=nc())*s++=ch; *s=0 ; } inline void read (char &c) { for (c=nc();blank(c);c=nc()); if (IOerror){c=-1 ;return ;} } struct Ostream_fwrite { char *buf,*p1,*pend; Ostream_fwrite(){buf=new char [BUF_SIZE];p1=buf;pend=buf+BUF_SIZE;} void out (char ch) { if (p1==pend){ fwrite(buf,1 ,BUF_SIZE,stdout );p1=buf; } *p1++=ch; } void print (int x) { static char s[15 ],*s1;s1=s; if (!x)*s1++='0' ;if (x<0 )out('-' ),x=-x; while (x)*s1++=x%10 +'0' ,x/=10 ; while (s1--!=s)out(*s1); } void println (int x) { static char s[15 ],*s1;s1=s; if (!x)*s1++='0' ;if (x<0 )out('-' ),x=-x; while (x)*s1++=x%10 +'0' ,x/=10 ; while (s1--!=s)out(*s1); out('\n' ); } void print (ll x) { static char s[25 ],*s1;s1=s; if (!x)*s1++='0' ;if (x<0 )out('-' ),x=-x; while (x)*s1++=x%10 +'0' ,x/=10 ; while (s1--!=s)out(*s1); } void println (ll x) { static char s[25 ],*s1;s1=s; if (!x)*s1++='0' ;if (x<0 )out('-' ),x=-x; while (x)*s1++=x%10 +'0' ,x/=10 ; while (s1--!=s)out(*s1); out('\n' ); } void print (double x,int y) { static ll mul[]={1 ,10 ,100 ,1000 ,10000 ,100000 ,1000000 ,10000000 ,100000000 , 1000000000 ,10000000000LL ,100000000000LL ,1000000000000LL ,10000000000000LL , 100000000000000LL ,1000000000000000LL ,10000000000000000LL ,100000000000000000LL }; if (x<-1e-12 )out('-' ),x=-x;x*=mul[y]; ll x1=(ll)floor (x); if (x-floor (x)>=0.5 )++x1; ll x2=x1/mul[y],x3=x1-x2*mul[y]; print(x2); if (y>0 ){out('.' ); for (size_t i=1 ;i<y&&x3*mul[i]<mul[y];out('0' ),++i); print(x3);} } void println (double x,int y) {print(x,y);out('\n' );} void print (char *s) {while (*s)out(*s++);} void println (char *s) {while (*s)out(*s++);out('\n' );} void flush () {if (p1!=buf){fwrite(buf,1 ,p1-buf,stdout );p1=buf;}} ~Ostream_fwrite(){flush();} }Ostream; inline void print (int x) {Ostream.print(x);} inline void println (int x) {Ostream.println(x);} inline void print (char x) {Ostream.out(x);} inline void println (char x) {Ostream.out(x);Ostream.out('\n' );} inline void print (ll x) {Ostream.print(x);} inline void println (ll x) {Ostream.println(x);} inline void print (double x,int y) {Ostream.print(x,y);} inline void println (double x,int y) {Ostream.println(x,y);} inline void print (char *s) {Ostream.print(s);} inline void println (char *s) {Ostream.println(s);} inline void println () {Ostream.out('\n' );} inline void flush () {Ostream.flush();} #undef ll #undef OUT_SIZE #undef BUF_SIZE };
C++高精度模板
封装类版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 #define MAXN 9999 #define MAXSIZE 10024 #define DLEN 4 struct Big { int a[MAXSIZE], len; bool flag; Big() { len = 1 ; memset (a, 0 , sizeof a); flag = 0 ; } Big(const int ); Big(const char *); Big(const Big&); Big& operator =(const Big&); Big operator +(const Big&) const ; Big operator -(const Big&) const ; Big operator *(const Big&)const ; Big operator /(const int &) const ; Big operator ^(const int &) const ; int operator %(const int &) const ; bool operator <(const Big&) const ; bool operator <(const int & t) const ; inline void print () ; }; Big::Big(const int b) { int c, d = b; len = 0 ; CLR(a); while (d > MAXN) { c = d - (d / (MAXN + 1 ) * (MAXN + 1 )); d = d / (MAXN + 1 ); a[len++] = c; } a[len++] = d; } Big::Big(const char * s) { int t, k, index, l; CLR(a); l = strlen (s); len = l / DLEN; if (l % DLEN) ++len; index = 0 ; for (int i = l - 1 ; i >= 0 ; i -= DLEN) { t = 0 ; k = i - DLEN + 1 ; if (k < 0 ) k = 0 ; g(j, k, i) t = t * 10 + s[j] - '0' ; a[index++] = t; } } Big::Big(const Big& T) : len(T.len) { CLR(a); f(i, 0 , len) a[i] = T.a[i]; } Big& Big::operator =(const Big& T) { CLR(a); len = T.len; f(i, 0 , len) a[i] = T.a[i]; return *this ; } Big Big::operator +(const Big& T) const { Big t (*this ) ; int big = len; if (T.len > len) big = T.len; f(i, 0 , big) { t.a[i] += T.a[i]; if (t.a[i] > MAXN) { ++t.a[i + 1 ]; t.a[i] -= MAXN + 1 ; } } if (t.a[big]) t.len = big + 1 ; else t.len = big; return t; } Big Big::operator -(const Big& T) const { int big; bool ctf; Big t1, t2; if (*this < T) { t1 = T; t2 = *this ; ctf = 1 ; } else { t1 = *this ; t2 = T; ctf = 0 ; } big = t1.len; int j = 0 ; f(i, 0 , big) { if (t1.a[i] < t2.a[i]) { j = i + 1 ; while (t1.a[j] == 0 ) ++j; --t1.a[j--]; while (j > i) t1.a[j--] += MAXN; t1.a[i] += MAXN + 1 - t2.a[i]; } else t1.a[i] -= t2.a[i]; } t1.len = big; while (t1.len > 1 && t1.a[t1.len - 1 ] == 0 ) { --t1.len; --big; } if (ctf) t1.a[big - 1 ] = -t1.a[big - 1 ]; return t1; } Big Big::operator *(const Big& T) const { Big res; int up; int te, tee; f(i, 0 , len) { up = 0 ; f(j, 0 , T.len) { te = a[i] * T.a[j] + res.a[i + j] + up; if (te > MAXN) { tee = te - te / (MAXN + 1 ) * (MAXN + 1 ); up = te / (MAXN + 1 ); res.a[i + j] = tee; } else { up = 0 ; res.a[i + j] = te; } } if (up) res.a[i + T.len] = up; } res.len = len + T.len; while (res.len > 1 && res.a[res.len - 1 ] == 0 ) --res.len; return res; } Big Big::operator /(const int & b) const { Big res; int down = 0 ; gd(i, len - 1 , 0 ) { res.a[i] = (a[i] + down * (MAXN + 1 ) / b); down = a[i] + down * (MAXN + 1 ) - res.a[i] * b; } res.len = len; while (res.len > 1 && res.a[res.len - 1 ] == 0 ) --res.len; return res; } int Big::operator %(const int & b) const { int d = 0 ; gd(i, len - 1 , 0 ) d = (d * (MAXN + 1 ) % b + a[i]) % b; return d; } Big Big::operator ^(const int & n) const { Big t(n), res(1); int y = n; while (y) { if (y & 1 ) res = res * t; t = t * t; y >>= 1 ; } return res; } bool Big::operator <(const Big& T) const { int ln; if (len < T.len) return 233 ; if (len == T.len) { ln = len - 1 ; while (ln >= 0 && a[ln] == T.a[ln]) --ln; if (ln >= 0 && a[ln] < T.a[ln]) return 233 ; return 0 ; } return 0 ; } inline bool Big::operator <(const int & t) const { Big tee (t) ; return *this < tee; } inline void Big::print () { printf ("%d" , a[len - 1 ]); gd(i, len - 2 , 0 ) { printf ("%04d" , a[i]); } } inline void print (Big s) { int len = s.len; printf ("%d" , s.a[len - 1 ]); gd(i, len - 2 , 0 ) { printf ("%04d" , s.a[i]); } } char s[100024 ];
简约版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 static const int LEN = 1004 ;int a[LEN], b[LEN], c[LEN], d[LEN];void clear (int a[LEN]) { for (int i = 0 ; i < LEN; ++i) a[i] = 0 ; } void read (int a[LEN]) { static char s[LEN + 1 ]; scanf ("%s" , s); clear(a); int len = strlen (s); for (int i = 0 ; i < len; ++i) a[len - i - 1 ] = s[i] - '0' ; } void print (int a[LEN]) { int i; for (i = LEN - 1 ; i >= 1 ; --i) if (a[i] != 0 ) break ; for (; i >= 0 ; --i) putchar (a[i] + '0' ); putchar ('\n' ); } void add (int a[LEN], int b[LEN], int c[LEN]) { clear(c); for (int i = 0 ; i < LEN - 1 ; ++i) { c[i] += a[i] + b[i]; if (c[i] >= 10 ) { c[i + 1 ] += 1 ; c[i] -= 10 ; } } } void sub (int a[LEN], int b[LEN], int c[LEN]) { clear(c); for (int i = 0 ; i < LEN - 1 ; ++i) { c[i] += a[i] - b[i]; if (c[i] < 0 ) { c[i + 1 ] -= 1 ; c[i] += 10 ; } } } void mul (int a[LEN], int b[LEN], int c[LEN]) { clear(c); for (int i = 0 ; i < LEN - 1 ; ++i) { for (int j = 0 ; j <= i; ++j) c[i] += a[j] * b[i - j]; if (c[i] >= 10 ) { c[i + 1 ] += c[i] / 10 ; c[i] %= 10 ; } } } inline bool greater_eq (int a[LEN], int b[LEN], int last_dg, int len) { if (a[last_dg + len] != 0 ) return true ; for (int i = len - 1 ; i >= 0 ; --i) { if (a[last_dg + i] > b[i]) return true ; if (a[last_dg + i] < b[i]) return false ; } return true ; } void div (int a[LEN], int b[LEN], int c[LEN], int d[LEN]) { clear(c); clear(d); int la, lb; for (la = LEN - 1 ; la > 0 ; --la) if (a[la - 1 ] != 0 ) break ; for (lb = LEN - 1 ; lb > 0 ; --lb) if (b[lb - 1 ] != 0 ) break ; if (lb == 0 ) { puts ("> <" ); return ; } for (int i = 0 ; i < la; ++i) d[i] = a[i]; for (int i = la - lb; i >= 0 ; --i) { while (greater_eq(d, b, i, lb)) { for (int j = 0 ; j < lb; ++j) { d[i + j] -= b[j]; if (d[i + j] < 0 ) { d[i + j + 1 ] -= 1 ; d[i + j] += 10 ; } } c[i] += 1 ; } } }
Java大整数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import java.util.*;import java.math.*;public class BigInt { static Scanner in = new Scanner(System.in); public static void main (String[] args) { BigInteger bigInt_1 = new BigInteger("100" ); BigInteger bigInt_2 = BigInteger.valueOf(123 ); bigInt_1.add(bigInt_2); bigInt_1.subtract(bigInt_2); bigInt_1.multiply(bigInt_2); bigInt_1.divide(bigInt_2); bigInt_1.divideAndRemainder(bigInt_2); bigInt_1.remainder(bigInt_2); bigInt_1.mod(bigInt_2); bigInt_1.pow(10 ); bigInt_1.gcd(bigInt_2); bigInt_1.compareTo(bigInt_2); bigInt_1.equals(bigInt_2); bigInt_1.negate(); bigInt_1.abs(); bigInt_1.min(bigInt_2); bigInt_1.max(bigInt_2); BigInteger a = in.nextBigInteger(); System.out.println(bigInt_1); } }
Java大实数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import java.util.*;import java.math.*;public class Big { static Scanner in = new Scanner(System.in); public static void main (String[] args) { BigDecimal bigDec_1 = new BigDecimal("123.1" ); BigDecimal bigDec_2 = BigDecimal.valueOf(233.213 ); int scale = 3 ; bigDec_1.divide(bigDec_2, scale, RoundingMode.HALF_UP); } }
手动扩栈
1 #pragma comment(linker, "/STACK:1024000000,1024000000" )
对拍
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <stdio.h> #include <stdlib.h> int main () { while (true ) { system("data.exe > data.in" ); system("std.exe < data.in > std.out" ); system("test.exe < data.in > test.out" ); if (system("fc std.out test.out" )) { break ; } } return 0 ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <stdio.h> #include <stdlib.h> int main () { while (true ) { system("./data > data.in" ); system("./std < data.in > std.out" ); system("./test < data.in > test.out" ); if (system("diff std.out test.out" )) { break ; } } return 0 ; }