text
stringlengths
2
104M
meta
dict
#pragma once #include <bits/stdc++.h> using namespace std; // Binary search a boolean function over a floating point range // Template Arguments: // T: the type of the range to search over, must be a floating point type // F: the type of the function that is being searched over // Function Arguments: // lo: the inclusive lower bound // hi: the inclusive upper bound // f: the function to search over // iters: the number of iterations to run the ternary search // Return Value: the value x in the range [lo, hi] such that f(x - EPS) is // false, while f(x + EPS) is true for some small value EPS // In practice, has a small constant // Time Complexity: O(iters) * (cost to compute f(x)) // Memory Complexity: O(1) // Tested: // https://dmoj.ca/problem/globexcup19s2 template <class T, class F> T bsearchFloat(T lo, T hi, F f, int iters) { static_assert(is_floating_point<T>::value, "T must be a floating point type"); for (int it = 0; it < iters; it++) { T mid = lo + (hi - lo) / 2; if (f(mid)) hi = mid; else lo = mid; } return lo + (hi - lo) / 2; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../datastructures/trees/fenwicktrees/FenwickTree1D.h" using namespace std; // Computes a longest increasing subsequence in an array // Template Arguments: // T: the type of each element in the array // Function Arguments: // A: a vector of type T // Return Value: a vector of indices of the element in the longest increasing // subsequence of the array, guaranteed that the values of those indices form // the lexicographically least subsequence // In practice, has a small constant, slower than // LongestIncreasingSubsequence.h // Time Complexity: O(N log N) // Memory Complexity: O(N) // Tested: // Fuzz and Stress Tested // https://dmoj.ca/problem/lis // https://open.kattis.com/problems/longincsubseq template <class T> vector<int> longestIncreasingSubsequenceFenwick(const vector<T> &A) { vector<T> tmp = A; int N = A.size(), mx = 0; sort(tmp.begin(), tmp.end()); tmp.erase(unique(tmp.begin(), tmp.end()), tmp.end()); vector<int> ret(N), ind(N + 1, -1); for (int i = 0; i < N; i++) ret[i] = lower_bound(tmp.begin(), tmp.end(), A[i]) - tmp.begin(); struct Max { int operator () (int a, int b) { return max(a, b); } }; FenwickTree1D<int, Max> FT(N, 0); for (int i = 0; i < N; i++) { int len = FT.query(ret[i] - 1) + 1; if (ind[len] == -1) ind[mx = len] = i; else if (!(A[ind[len]] < A[i])) ind[len] = i; FT.update(ret[i], len); ret[i] = ind[len - 1]; } for (int i = N, k = ind[mx], p; k != -1; k = p) { p = ret[k]; ret[--i] = k; } ret.erase(ret.begin(), ret.end() - mx); return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Sum over subsets (or supersets) (similar to FST) // Transforms an array a into an array a' such that a'[i] is equal to the // aggregate of all a[j] such that i | j == i if TYPE == SUBSET // or i & j == i if TYPE == SUPERSET // Template Arguments: // TYPE: SUBSET or SUPERSET // T: the type of each element // Function Arguments: // a: a reference to the vector of type T to transform // op: the op being performed (this can also be an inverse operation) // Time Complexity: O(N log N) where N = size(a) // Memory Complexity: O(1) // Tested: // https://judge.yosupo.jp/problem/bitwise_and_convolution // https://csacademy.com/contest/round-53/task/maxor/ const bool SUBSET = true, SUPERSET = false; template <const bool TYPE, class T, class Op> void sos(vector<T> &a, Op op) { int N = a.size(); assert(!(N & (N - 1))); for (int m = 1; m < N; m <<= 1) for (int mask = 0; mask < N; mask++) if (bool(mask & m) == TYPE) a[mask] = op(a[mask], a[mask ^ m]); }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Solves the 0-1 knapsack problem (each item can appear either 0 or 1 times) // Template Arguments: // V: the value type // Function Arguments: // A: a vetor of pairs, with the first element of each pair being the weight // of type int, and the second being the value of type V // M: type maximum weight the knapsack can hold // NEG_INF: a value of type V for negative infinity // Return Value: a vector dp of size M + 1 with dp[i] being the maximum value // that a knapsack with weights summing to exactly i has (or NEG_INF if // that sum is not possible) // In practice, has a very small constant // Time Complexity: O(NM) // Memory Complexity: O(M) // Tested: // https://atcoder.jp/contests/dp/tasks/dp_d template <class V> vector<V> zeroOneKnapsack(const vector<pair<int, V>> &A, int M, V NEG_INF = numeric_limits<V>::lowest()) { vector<V> dp(M + 1, NEG_INF); dp[0] = V(); for (auto &&a : A) for (int j = M; j >= a.first; j--) if (dp[j - a.first] > NEG_INF) dp[j] = max(dp[j], dp[j - a.first] + a.second); return dp; } // Solves the dual of the 0-1 knapsack problem (each item can appear // either 0 or 1 times) // Template Arguments: // W: the weight type // Function Arguments: // A: a vetor of pairs, with the first element of each pair being the weight // of type W, and the second being the value of type int // K: type maximum value the knapsack can hold // INF: a value of type W for infinity // Return Value: a vector dp of size K + 1 with dp[i] being the minimum weight // that a knapsack with values summing to exactly i has (or INF if that sum // is not possible) // In practice, has a very small constant // Time Complexity: O(NK) // Memory Complexity: O(K) // Tested: // https://atcoder.jp/contests/dp/tasks/dp_e template <class W> vector<W> zeroOneKnapsackDual( const vector<pair<W, int>> &A, int K, W INF = numeric_limits<W>::max()) { vector<W> dp(K + 1, INF); dp[0] = W(); for (auto &&a : A) for (int j = K; j >= a.second; j--) if (dp[j - a.second] < INF) dp[j] = min(dp[j], dp[j - a.second] + a.first); return dp; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Solves the multisubset sum problem with the occurrence of each sum (elements // can be chosen multiple times) // Template Arguments: // U: the type of the count // T: the type of each element in the array // Function Arguments: // A: a vector of type T // M: the maximum sum to count the number of multisubsets // Return Value: a vector dp of type U with length M + 1 with dp[i] equal to // the number of multisubsets that have a sum of i // In practice, has a very small constant // Time Complexity: O(NM) // Memory Complexity: O(M) // Tested: // https://cses.fi/problemset/task/1636 template <class U, class T> vector<U> multisubsetSumCount(const vector<T> &A, int M) { vector<U> dp(M + 1, U()); dp[0] = U(1); for (auto &&a : A) for (int j = a; j <= M; j++) dp[j] += dp[j - a]; return dp; } // Solves the multisubset sum problem (elements can be chosen multiple times) // Template Arguments: // U: the type representing the boolean // T: the type of each element in the array // Function Arguments: // A: a vector of type T // M: the maximum sum to determine if a subset exists // Return Value: a boolean vector dp with length M + 1 with dp[i] equal to // 1 if a multisubset has a sum of i, 0 otherwise // In practice, has a very small constant, faster if U is int, but less memory // is used if U is bool (as long as the compiler optimizes vector<booL>); // char gives mixed results depending on whether vector<char> is compiled // as a string (better if it is not a string) // Time Complexity: O(NM) // Memory Complexity: O(M / 64) // Tested: // Stress Tested // https://mcpt.ca/problem/acoinproblem template <class U = bool, class T> vector<U> multisubsetSum(const vector<T> &A, int M) { vector<U> dp(M + 1, U(0)); dp[0] = U(1); for (auto &&a : A) for (int j = a; j <= M; j++) dp[j] = dp[j] || dp[j - a]; return dp; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Solves the subset sum problem with the occurrence of each sum (elements // can be chosen 0 or 1 times) // Template Arguments: // U: the type of the count // T: the type of each element in the array // Function Arguments: // A: a vector of type T // M: the maximum sum to count the number of subsets // Return Value: a vector dp of type U with length M + 1 with dp[i] equal to // the number of subsets that have a sum of i // In practice, has a very small constant // Time Complexity: O(NM) // Memory Complexity: O(M) // Tested: // Fuzz Tested template <class U, class T> vector<U> subsetSumCount(const vector<T> &A, int M) { vector<U> dp(M + 1, U()); dp[0] = U(1); for (auto &&a : A) for (int j = M; j >= a; j--) dp[j] += dp[j - a]; return dp; } // Solves the subset sum problem (elements can be chosen 0 or 1 times) // Template Arguments: // M: the maximum sum to determine if a subset exists // T: the type of each element in the array // Function Arguments: // A: a vector of type T // en: an iterator pointing to after the last element in the array // Return Value: a bitset dp with length M + 1 with dp[i] equal to // whether a subset has a sum of i // In practice, has a very small constant // Time Complexity: O(NM / 64) // Memory Complexity: O(M / 64) // Tested: // Fuzz Tested // https://cses.fi/problemset/task/1745/ template <const int M, class T> bitset<M + 1> subsetSum(const vector<T> &A) { bitset<M + 1> dp; dp[0] = true; for (auto &&a : A) dp |= dp << a; return dp; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes the maximum sum of a non empty, non consecutive subsequence // Template Arguments: // T: the type of each element in the array // Function Arguments: // A: a vector of type T // NEG_INF: a value for negative infinity // Return Value: the maximum sum of a non empty, non consecutive subsequence // In practice, has a small constant // Time Complexity: O(N) // Memory Complexity: O(1) // Tested: // https://dmoj.ca/problem/seq0 template <class T> T maxNonConsecutiveSum( const vector<T> &A, T NEG_INF = numeric_limits<T>::lowest()) { T incl = NEG_INF, excl = NEG_INF; for (auto &&a : A) { T v = a; if (excl > NEG_INF) v = max(v, v + excl); excl = max(incl, excl); incl = v; } return max(incl, excl); }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Solves the bounded knapsack problem (each item can appear up to a specified // number of times) // Template Arguments: // V: the value type // Function Arguments: // A: a vector of tuples, with the first element of each tuple being the // weight of type int, the second being the value of type V, and the third // being the frequency of type int // M: type maximum weight the knapsack can hold // NEG_INF: a value of type V for negative infinity // Return Value: a vector dp of size M + 1 with dp[i] being the maximum value // that a knapsack with weights summing to exactly i has (or NEG_INF if // that sum is not possible) // In practice, has a small constant // Time Complexity: O(NM) // Memory Complexity: O(M) // Tested: // https://dmoj.ca/problem/knapsack template <class V> vector<V> boundedKnapsack(const vector<tuple<int, V, int>> &A, int M, V NEG_INF = numeric_limits<V>::lowest()) { vector<V> dp(M + 1, NEG_INF), q(M + 1, V()), dq(M + 1, V()); dp[0] = V(); for (auto &&a : A) { int w = get<0>(a), f = get<2>(a); V v = get<1>(a); if (w <= M) for (int s = 0; s < w; s++) { V alpha = V(); int ql = 0, qr = 0, dql = 0, dqr = 0; for (int j = s; j <= M; j += w) { alpha += v; V a = dp[j] <= NEG_INF ? NEG_INF : dp[j] - alpha; while (dql < dqr && dq[dqr - 1] < a) dqr--; q[qr++] = dq[dqr++] = a; while (qr - ql > f + 1) if (q[ql++] == dq[dql]) dql++; dp[j] = dq[dql] <= NEG_INF ? NEG_INF : dq[dql] + alpha; } } } return dp; } // Solves the dual of the bounded knapsack problem (each item can appear up to // a specified number of times) // Template Arguments: // W: the weight type // Function Arguments: // A: a vector of tuples, with the first element of each tuple being the // weight of type W, the second being the value of type int, and the third // being the frequency of type int // K: type maximum value the knapsack can hold // INF: a value of type W for infinity // Return Value: a vector dp of size K + 1 with dp[i] being the minimum weight // that a knapsack with values summing to exactly i has (or INF if that sum // is not possible) // In practice, has a small constant // Time Complexity: O(NK) // Memory Complexity: O(K) // Tested: // https://dmoj.ca/problem/knapsack (Subtask 1) template <class W> vector<W> boundedKnapsackDual(const vector<tuple<W, int, int>> &A, int K, W INF = numeric_limits<W>::max()) { vector<W> dp(K + 1, INF), q(K + 1, W()), dq(K + 1, W()); dp[0] = W(); for (auto &&a : A) { int v = get<1>(a), f = get<2>(a); W w = get<0>(a); if (v <= K) for (int s = 0; s < v; s++) { W alpha = W(); int ql = 0, qr = 0, dql = 0, dqr = 0; for (int j = s; j <= K; j += v) { alpha += w; W a = dp[j] >= INF ? INF : dp[j] - alpha; while (dql < dqr && dq[dqr - 1] > a) dqr--; q[qr++] = dq[dqr++] = a; while (qr - ql > f + 1) if (q[ql++] == dq[dql]) dql++; dp[j] = dq[dql] >= INF ? INF : dq[dql] + alpha; } } } return dp; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes the longest common subsequence between 2 arrays // Template Arguments: // T: the type of the elements in the arrays // Function Arguments: // A: the first array // B: the second array // Return Value: the length of the longest common subsequence between the // 2 arrays // In practice, has a small constant // Time Complexity: O(NM) where N = en1 - st1 and M = en2 - st2 // Memory Complexity: O(M) // Tested: // https://dmoj.ca/problem/lcs template <class T> int longestCommonSubsequence(const vector<T> &A, const vector<T> &B) { int N = A.size(), M = B.size(); vector<vector<int>> dp(2, vector<int>(M + 1, 0)); for (int i = 1; i <= N; i++) { int cur = i % 2, prv = 1 - cur; for (int j = 1; j <= M; j++) dp[cur][j] = A[i - 1] == B[j - 1] ? dp[prv][j - 1] + 1 : max(dp[cur][j - 1], dp[prv][j]); } return dp[N % 2][M]; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Knuth's Dynamic Programming Optimization // Must satisfy dp[l][r] = max(dp[l][m] + dp[m][r] + cost(l, m, r)) // for l <= m <= r and // max(l + 1, opt[l][r - 1]) <= opt[l][r] <= min(opt[l + 1][r], r - 1), // where opt[l][r] is the optimal value of m for dp[l][r] // Template Arguments: // T: the type of the return value of the cost function // F: the type of the function used to compute the cost function // Cmp: the comparator to compare two T values, // convention is same as std::priority_queue in STL // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Function Arguments: // N: the size of the array, must be positive // f(l, m, r): computes the cost function for the range [l, r) with the // midpoint m // cmp: an instance of the Cmp struct // Return Value: a dp array of size N x (N + 1) with dp[l][r] equal to the // maximum dp value (based on the comparator) of the range [l, r) // In practice, has a small constant // Time Complexity: O(N^2) // Memory Complexity: O(N^2) // Tested: // https://atcoder.jp/contests/dp/tasks/dp_n template <class T, class F, class Cmp = less<T>> vector<vector<T>> knuth(int N, F f, Cmp cmp = Cmp()) { assert(N > 0); vector<vector<T>> dp(N, vector<T>(N + 1, T())); vector<vector<int>> opt(N, vector<int>(N + 1)); for (int l = N - 1; l >= 0; l--) for (int r = l; r <= N; r++) { if (r - l <= 1) { opt[l][r] = l; continue; } int st = max(l + 1, opt[l][r - 1]), en = min(opt[l + 1][r], r - 1); for (int m = st; m <= en; m++) { T cost = dp[l][m] + dp[m][r] + f(l, m, r); if (m == st || cmp(dp[l][r], cost)) { dp[l][r] = cost; opt[l][r] = m; } } } return dp; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Solves the unbounded knapsack problem (each item can appear any number // of times) // Template Arguments: // V: the value type // Function Arguments: // A: a vetor of pairs, with the first element of each pair being the weight // of type int, and the second being the value of type V // M: type maximum weight the knapsack can hold // NEG_INF: a value of type V for negative infinity // Return Value: a vector dp of size M + 1 with dp[i] being the maximum value // that a knapsack with weights summing to exactly i has (or NEG_INF if // that sum is not possible) // In practice, has a very small constant // Time Complexity: O(NM) // Memory Complexity: O(M) // Tested: // https://www.spoj.com/problems/DBALLZ/ template <class V> vector<V> unboundedKnapsack(const vector<pair<int, V>> &A, int M, V NEG_INF = numeric_limits<V>::lowest()) { vector<V> dp(M + 1, NEG_INF); dp[0] = V(); for (auto &&a : A) for (int j = a.first; j <= M; j++) if (dp[j - a.first] > NEG_INF) dp[j] = max(dp[j], dp[j - a.first] + a.second); return dp; } // Solves the dual of the unbounded knapsack problem (each item can appear // any number of times) // Template Arguments: // W: the weight type // Function Arguments: // A: a vetor of pairs, with the first element of each pair being the weight // of type W, and the second being the value of type int // K: type maximum value the knapsack can hold // INF: a value of type W for infinity // Return Value: a vector dp of size K + 1 with dp[i] being the minimum weight // that a knapsack with values summing to exactly i has (or INF if that sum // is not possible) // In practice, has a very small constant // Time Complexity: O(NK) // Memory Complexity: O(K) // Tested: // https://www.spoj.com/problems/PIGBANK/ template <class W> vector<W> unboundedKnapsackDual( const vector<pair<W, int>> &A, int K, W INF = numeric_limits<W>::max()) { vector<W> dp(K + 1, INF); dp[0] = W(); for (auto &&a : A) for (int j = a.second; j <= K; j++) if (dp[j - a.second] < INF) dp[j] = min(dp[j], dp[j - a.second] + a.first); return dp; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes a longest increasing subsequence in an array // Template Arguments: // T: the type of each element in the array // Function Arguments: // A: the array // Return Value: a vector of indices of the element in a longest increasing // subsequence of the array, the indices is guaranteed to be the // lexicographically largest vector of indices // In practice, has a very small constant, faster than the Fenwick Tree version // Time Complexity: O(N log N) // Memory Complexity: O(N) // Tested: // Fuzz and Stress Tested // https://dmoj.ca/problem/lis // https://open.kattis.com/problems/longincsubseq template <class T> vector<int> longestIncreasingSubsequence(const vector<T> &A) { int N = A.size(), k = -1; vector<int> ret(N); vector<pair<T, int>> dp; dp.reserve(N); for (int i = 0; i < N; i++) { int j = lower_bound(dp.begin(), dp.end(), make_pair(A[i], -1)) - dp.begin(); ret[i] = j == 0 ? -1 : dp[j - 1].second; if (j >= int(dp.size())) dp.emplace_back(A[i], i); else dp[j] = make_pair(A[i], i); if (j == int(dp.size()) - 1) k = i; } for (int i = N, p; k != -1; k = p) { p = ret[k]; ret[--i] = k; } ret.erase(ret.begin(), ret.end() - dp.size()); return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Divide and Conquer Dynamic Programming Optimization // Must satisfy dp[k][i] = max(dp[k - 1][j] + cost(k, j, i)) // for 0 <= j <= i <= N and opt[k][i] <= opt[k][i + 1] where opt[k][i] is // the optimal value of j for dp[k][i] // Template Arguments: // T: the type of the return value of the cost function // F: the type of the function used to compute the cost function // Cmp: the comparator to compare two T values, // convention is same as std::priority_queue in STL // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Function Arguments: // K: the number of iterations, must be positive // N: the size of the array, must be positive // f(k, j, i): computes the cost function for the kth iteration (1-indexed) // for the transition from j to i (0 <= j <= i <= N) // cmp: an instance of the Cmp struct // Return Value: a vector of length K + 1 with the value of dp[k][N] // for 1 <= k <= N with dp[0][N] = 0 // In practice, has a small constant // Time Complexity: O(KN log N) // Memory Complexity: O(N) // Tested: // https://codeforces.com/contest/321/problem/E // https://www.acmicpc.net/problem/7052 template <class T, class F, class Cmp = less<T>> vector<T> divideAndConquer(int K, int N, F f, Cmp cmp = Cmp()) { assert(N > 0 && K > 0); vector<vector<T>> dp(2, vector<T>(N + 1, T())); for (int i = 0; i <= N; i++) dp[1][i] = f(1, 0, i); vector<T> ret(K + 1, T()); ret[1] = dp[1][N]; vector<int> mid(N + 1); vector<pair<int, int>> bnd(N + 1, make_pair(0, N)), opt = bnd; for (int i = 0, b = 1; i <= N; i++) { int l, r; tie(l, r) = bnd[i]; int m = mid[i] = l + (r - l) / 2; if (l <= m - 1) bnd[b++] = make_pair(l, m - 1); if (m + 1 <= r) bnd[b++] = make_pair(m + 1, r); } for (int k = 2; k <= K; k++) { int cur = k % 2, prv = 1 - cur; for (int i = 0, b = 1; i <= N; i++) { int l, r, m = mid[i], optl, optr; tie(l, r) = bnd[i]; tie(optl, optr) = opt[i]; int optm = optl; for (int j = optl, en = min(m, optr); j <= en; j++) { T cost = dp[prv][j] + f(k, j, m); if (j == optl || cmp(dp[cur][m], cost)) { dp[cur][m] = cost; optm = j; } } if (l <= m - 1) opt[b++] = make_pair(optl, optm); if (m + 1 <= r) opt[b++] = make_pair(optm, optr); } ret[k] = dp[cur][N]; } return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes the maximum sum of a non empty subarray // Template Arguments: // T: the type of each element in the array // Function Arguments: // A: a vector of type T // NEG_INF: a value for negative infinity // Return Value: a tuple with the maximum sum of a non empty subarray, and the // inclusive left and right indices of the subarray // In practice, has a small constant // Time Complexity: O(N) // Memory Complexity: O(1) // Tested: // https://mcpt.ca/problem/subarraymaximization template <class T> tuple<T, int, int> maxSubarraySum( const vector<T> &A, T NEG_INF = numeric_limits<T>::lowest()) { tuple<T, int, int> ret = make_tuple(NEG_INF, 0, -1); T sm = T(); for (int i = 0, l = 0; i < int(A.size()); i++) { sm += A[i]; if (get<0>(ret) < sm) ret = make_tuple(sm, l, i); if (sm < T()) { sm = T(); l = i + 1; } } return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes the minimum edit distance between 2 arrays, allowing for custom // penalties for copying, replacement, insertion, and deletion // Template Arguments: // T: the type of each element in the arrays // U: the type of the penalties // Function Arguments: // A: the first array of type T // B: the second array of type T // Return Value: the minimum cost to edit the first array to become the // second array // In practice, has a small constant // Time Complexity: O(NM) // Memory Complexity: O(M) // Tested: // https://www.spoj.com/problems/EDIST/ template <class T, class U = int> U minEditDistance(const vector<T> &A, const vector<T> &B, U cpyPen = U(), U repPen = U(1), U insPen = U(1), U delPen = U(1)) { int N = A.size(), M = B.size(); vector<vector<U>> dp(2, vector<U>(M + 1, U())); for (int i = 1; i <= M; i++) dp[0][i] = dp[0][i - 1] + insPen; for (int i = 1; i <= N; i++) { int cur = i % 2, prv = 1 - cur; dp[cur][0] = dp[prv][0] + delPen; for (int j = 1; j <= M; j++) { dp[cur][j] = min(min(dp[prv][j - 1] + repPen, dp[cur][j - 1] + insPen), dp[prv][j] + delPen); if (A[i - 1] == B[j - 1]) dp[cur][j] = min(dp[cur][j], dp[prv][j - 1] + cpyPen); } } return dp[N % 2][M]; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../datastructures/trees/fenwicktrees/FenwickTree1D.h" using namespace std; // Counts inversions and sorts an array using a Fenwick Tree with a comparator // Template Arguments: // It: the type of the iterator // Cmp: the comparator to compare two values // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Function Arguments: // st: an iterator pointing to the first element in the array // en: an iterator pointing to after the last element in the array // cmp: an instance of the Cmp struct // Return Value: the number of inversions in the array // In practice, has a moderate constant, slower than the merge sort version // Time Complexity: O(N log N) // Memory Complexity: O(N) // Tested: // https://www.spoj.com/problems/INVCNT/ // https://codeforces.com/problemsets/acmsguru/problem/99999/180 template <class It, class Cmp = less<typename iterator_traits<It>::value_type>> long long countInversionsFenwick(It st, It en, Cmp cmp = Cmp()) { vector<typename iterator_traits<It>::value_type> tmp(st, en); int N = en - st; long long ret = 0; sort(tmp.begin(), tmp.end(), cmp); tmp.erase(unique(tmp.begin(), tmp.end()), tmp.end()); FenwickTree1D<int> FT(tmp.size()); for (int i = N - 1; i >= 0; i--) { int c = lower_bound(tmp.begin(), tmp.end(), st[i], cmp) - tmp.begin(); ret += FT.query(c - 1); FT.update(c, 1); } return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Sorts an array using shell sort with a comparator // Shell sort is not stable // Template Arguments: // It: the type of the iterator // Cmp: the comparator to compare two values // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Function Arguments: // st: an iterator pointing to the first element in the array // en: an iterator pointing to after the last element in the array // cmp: an instance of the Cmp struct // In practice, has a very small constant, slower than std::sort by // a factor of 2 at N = 1e7 // Time Complexity: O(N^(4/3)) // Memory Complexity: O(1) // Tested: // https://dmoj.ca/problem/bf1hard template <class It, class Cmp = less<typename iterator_traits<It>::value_type>> void shellSort(It st, It en, Cmp cmp = Cmp()) { int n = en - st, h = 1; while (h < n * 4 / 9) h = h * 9 / 4 + 1; for (; h >= 1; h = h * 4 / 9) for (int i = h; i < n; i++) for (int j = i; j >= h && cmp(st[j], st[j - h]); j -= h) swap(st[j], st[j - h]); }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Helper function for inversion counting template <class InIt, class OutIt, class Cmp> long long countInversions(InIt st1, OutIt st2, int N, Cmp cmp, int len) { long long ret = 0; for (int lo = 0; lo < N; lo += len + len) { int mid = min(lo + len, N), hi = min(mid + len, N); for (int i = lo, j = mid, k = lo; k < hi; k++) { if (i >= mid) st2[k] = st1[j++]; else if (j >= hi) { st2[k] = st1[i++]; ret += j - mid; } else if (cmp(st1[j], st1[i])) { st2[k] = st1[j++]; ret += mid - i; } else { st2[k] = st1[i++]; ret += j - mid; } } } return ret; } // Counts inversions and sorts an array using merge sort with a comparator // Template Arguments: // It: the type of the iterator // Cmp: the comparator to compare two values // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Function Arguments: // st: an iterator pointing to the first element in the array // en: an iterator pointing to after the last element in the array // cmp: an instance of the Cmp struct // Return Value: the number of inversions in the array // In practice, has a small constant, faster than the Fenwick Tree version // Time Complexity: O(N log N) // Memory Complexity: O(N) // Tested: // https://www.spoj.com/problems/INVCNT/ // https://codeforces.com/problemsets/acmsguru/problem/99999/180 template <class It, class Cmp = less<typename iterator_traits<It>::value_type>> long long countInversions(It st, It en, Cmp cmp = Cmp()) { vector<typename iterator_traits<It>::value_type> tmp(st, en); int N = en - st; auto aux = tmp.begin(); long long ret = 0; bool flag = true; for (int len = 1; len < N; len *= 2, flag = !flag) ret += flag ? countInversions(aux, st, N, cmp, len) : countInversions(st, aux, N, cmp, len); if (flag) copy_n(aux, N, st); return ret / 2; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Mo's algorithm to answer offline ranges queries over // a static array A of length N where elements can be only added to a // multiset-like object // Template Arguments: // S: struct to maintain a multiset of elements // Required Fields: // T: the type of each element // R: the type of the return value for each query // Q: the query object that contains information for each query // Required Fields: // l: the left endpoint of the query range // r: the right endpoint of the query range // Required Functions: // constructor(...args): takes any number of arguments (arguments are // passed from constructor of Mo) // add(v): adds the value v to the multiset // save(): saves the current state of the multiset // rollback(): rollbacks the multiset to the saved state // reset(): resets the multiset to its initial state // query(q): returns the answer of type R for the query q of type Q to // the multiset, which is guaranteed to contain all elements in the range // [q.l, q.r] and only those elements // Sample Struct: supporting queries for 0-1 knapsack problem with a size of // q.w over a subarray of items with a weight and value // struct S { // using T = pair<int, int>; using R = int; // struct Q { int l, r, w; }; // int MAXW; vector<int> dp, saved; // S(int MAXW) : MAXW(MAXW), dp(MAXW + 1) {} // void add(const T &v) { // for (int j = MAXW; j >= v.first; j--) // dp[j] = max(dp[j], dp[j - v.first] + v.second); // } // void save() { saved = dp; } // void rollback() { dp = saved; } // void reset() { fill(dp.begin(), dp.end(), 0); } // R query(const Q &q) const { return dp[q.w]; } // }; // Constructor Arguments: // A: a vector of type S::T of the values in the array // queries: a vector of type S::Q representing the queries // SCALE: the value to scale sqrt by // ...args: arguments to pass to the constructor of S // Fields: // ans: a vector of integers with the answer for each query // In practice, has a very small constant // Time Complexity: // constructor: O(C + K ((log K + A sqrt N) + R + T) + D sqrt N) // for K queries where C is the time complexity of S's constructor, // A is the time complexity of S.add, T is the time complexity of S.query, // R is the time complexity of S.save and S.rollback, // and D is the time complexity of S.reset // Memory Complexity: O(K + M) for K queries where M is the memory complexity // of S // Tested: // https://www.spoj.com/problems/DQUERY/ // https://dmoj.ca/problem/vpex1p5 template <class S> struct MoRollback { using T = typename S::T; using R = typename S::R; using Q = typename S::Q; struct Query { Q q; int i, b; Query(const Q &q, int i, int b) : q(q), i(i), b(b) {} pair<int, int> getPair() const { return make_pair(b, q.r); } bool operator < (const Query &o) const { return getPair() < o.getPair(); } }; vector<R> ans; template <class ...Args> MoRollback( const vector<T> &A, const vector<Q> &queries, double SCALE = 1, Args &&...args) { int N = A.size(), K = queries.size(), bsz = max(1.0, sqrt(N) * SCALE); vector<Query> q; q.reserve(K); S s(forward<Args>(args)...); int l = 0, r = -1, last = -1; for (int i = 0; i < K; i++) q.emplace_back(queries[i], i, queries[i].l / bsz); sort(q.begin(), q.end()); for (auto &&qi : q) { if (qi.b != last) { l = min(N, ((last = qi.b) + 1) * bsz); r = l - 1; s.reset(); s.save(); } if (qi.q.r < l) { for (int i = qi.q.l; i <= qi.q.r; i++) s.add(A[i]); } else { while (r < qi.q.r) s.add(A[++r]); s.save(); for (int i = l - 1; i >= qi.q.l; i--) s.add(A[i]); } R res = s.query(qi.q); if (ans.empty()) ans.resize(K, res); ans[qi.i] = res; s.rollback(); } } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../datastructures/WaveletMatrix.h" using namespace std; // Supports online queries for the number of distinct elements in the // range [l, r] for a static array A of length N // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // Constructor Arguments: // A: a vector of type T of the values in the array // Functions: // query(l, r): returns the number of distinct values in the range [l, r] // In practice, has a moderate constant, faster than mo, but slower than the // offline version // Time Complexity: // constructor: O(N log N) // query: O(log N) // Memory Complexity: O(N + (N log N) / 64) // Tested: // https://www.acmicpc.net/problem/14898 template <class T> struct CountDistinct { WaveletMatrix<int> wm; vector<int> init(const vector<T> &A) { vector<T> temp = A; sort(temp.begin(), temp.end()); temp.erase(unique(temp.begin(), temp.end()), temp.end()); vector<int> last(temp.size(), -1), ret(A.size()); for (int i = 0; i < int(A.size()); i++) { int c = lower_bound(temp.begin(), temp.end(), A[i]) - temp.begin(); ret[i] = last[c]; last[c] = i; } return ret; } CountDistinct(const vector<T> &A) : wm(init(A)) {} int query(int l, int r) { return wm.rank(l, r, l); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Mo's algorithm to answer offline ranges queries over // a static array A of length N where elements can be added to and removed // from a multiset-like object // Template Arguments: // S: struct to maintain a multiset of the elements in the subarray [l, r] // Required Fields: // T: the type of each element // R: the type of the return value for each query // Q: the query object that contains information for each query // Required Fields: // l: the left endpoint of the query range // r: the right endpoint of the query range // Required Functions: // constructor(...args): takes any number of arguments (arguments are // passed from constructor of Mo) // addLeft(v): adds the value v to the multiset by expanding the subarray // [l, r] to [l - 1, r] // addRight(v): adds the value v to the multiset by expanding the subarray // [l, r] to [l, r + 1] // removeLeft(v): removes the value v from the multiset assuming // it exists by contracting the subarray [l, r] to [l + 1, r] // removeRight(v): removes the value v from the multiset assuming // it exists by contracting the subarray [l, r] to [l, r - 1] // query(q): returns the answer of type R for the query q of type Q to // the multiset, which is guaranteed to contain all elements in the range // [q.l, q.r] and only those elements // Sample Struct: supporting queries for the number of inversions // in an integer array with a small maximum value // struct S { // using T = int; using R = long long; // struct Q { int l, r; }; // int U; FenwickTree1D<int> ft; long long inversions; // S(const vector<T> &A) // : U(*max_element(A.begin(), A.end()) + 1), ft(U), // inversions(0) {} // void addLeft(const T &v) { // inversions += ft.query(0, v - 1); ft.update(v, 1); // } // void addRight(const T &v) { // inversions += ft.query(v + 1, U - 1); ft.update(v, 1); // } // void removeLeft(const T &v) { // inversions -= ft.query(0, v - 1); ft.update(v, -1); // } // void removeRight(const T &v) { // inversions -= ft.query(v + 1, U - 1); ft.update(v, -1); // } // R query(const Q &q) const { return inversions; } // }; // Constructor Arguments: // A: a vector of type S::T of the values in the array // queries: a vector of type S::Q representing the queries // SCALE: the value to scale sqrt by // ...args: arguments to pass to the constructor of S // Fields: // ans: a vector of integers with the answer for each query // In practice, has a very small constant // Time Complexity: // constructor: O(C + K ((log K + U sqrt N) + T)) // for K queries where C is the time complexity of S's constructor, // U is the time complexity of S.addLeft, S.addRight, // S.removeLeft, S.removeRight, // and T is the time complexity of S.query // Memory Complexity: O(K + M) for K queries where M is the memory complexity // of S // Tested: // https://www.spoj.com/problems/DQUERY/ // https://atcoder.jp/contests/abc174/tasks/abc174_f // https://judge.yosupo.jp/problem/static_range_inversions_query template <class S> struct Mo { using T = typename S::T; using R = typename S::R; using Q = typename S::Q; struct Query { Q q; int i, b; Query(const Q &q, int i, int b) : q(q), i(i), b(b) {} pair<int, int> getPair() const { return make_pair(b, b % 2 ? -q.r : q.r); } bool operator < (const Query &o) const { return getPair() < o.getPair(); } }; vector<R> ans; template <class ...Args> Mo(const vector<T> &A, const vector<Q> &queries, double SCALE = 2, Args &&...args) { int K = queries.size(), bsz = max(1.0, sqrt(A.size()) * SCALE); vector<Query> q; q.reserve(K); S s(forward<Args>(args)...); for (int i = 0; i < K; i++) q.emplace_back(queries[i], i, queries[i].l / bsz); sort(q.begin(), q.end()); int l = 0, r = l - 1; for (auto &&qi : q) { while (l > qi.q.l) s.addLeft(A[--l]); while (r < qi.q.r) s.addRight(A[++r]); while (l < qi.q.l) s.removeLeft(A[l++]); while (r > qi.q.r) s.removeRight(A[r--]); R res = s.query(qi.q); if (ans.empty()) ans.resize(K, res); ans[qi.i] = res; } } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Uses divide and conquer to answer offline ranges queries over // a multiset where elements can be added or removed at anytime, but the // underlying data structure is only able to add and delete elements in LIFO // order, as well as save and restore its state // Template Arguments: // S: struct to maintain a multiset of elements // Required Fields: // T: the type of each element // R: the type of the return value for each query // Q: the query object that contains information for each query // Required Functions: // constructor(...args): takes any number of arguments (arguments are // passed from LIFOSetDivAndConq::solveQueries) // push(v): adds the value v to the multiset // pop(): pops the most recent element pushed to the multiset // query(q): returns the answer of type R for the query q of type Q to // the multiset // Sample Struct: supports queries for the sum of element in the same // connected component as a vertex in a graph, where edges are // added and removed // struct S { // using T = pair<int, int>; using R = long long; // struct Q { int v; }; // WeightedUnionFindUndo<R, plus<R>> uf; // S(const vector<R> &W) : uf(W) {} // void push(const T &e) { uf.join(e.first, e.second); } // void pop() { uf.undo(); } // R query(const Q &q) { return uf.getWeight(q.v); } // }; // Fields: // ans: a vector of integers with the answer for each query // Functions: // addElement(v): adds v to the multiset // removeElement(v): removes v from the multiset // addQuery(q): adds a query of type S::Q // solveQueries(...args): solves all queries asked so far, with // ...args being passed to the constructor of S // In practice, has a small constant // Time Complexity: // addElement, removeElement: O(1) amortized // solveQueries: O(C + P E log E + KT) // for K queries and E total elements where C is the time complexity // of S's constructor, P is the time complexity of S.push and S.pop, // T is the time complexity of S.query, with S.push and S.pop being called // at most O(log K) times in total for each element, over all operations // Memory Complexity: O(K + E + M) for K queries and E total elements, where // M is the memory complexity of S // Tested: // https://judge.yosupo.jp/problem/dynamic_graph_vertex_add_component_sum template <class S> struct LIFOSetDivAndConq { using T = typename S::T; using R = typename S::R; using Q = typename S::Q; vector<T> add, rem; vector<Q> queries; vector<R> ans; vector<char> type; void addElement(const T &v) { add.push_back(v); type.push_back(1); } void removeElement(const T &v) { rem.push_back(v); type.push_back(-1); } void addQuery(const Q &q) { queries.push_back(q); type.push_back(0); } template <class ...Args> void solveQueries(Args &&...args) { int E = type.size(); ans.clear(); ans.reserve(queries.size()); vector<T> A = add; sort(A.begin(), A.end()); vector<pair<int, int>> events; events.reserve(E); vector<int> last(A.size(), INT_MAX); S s(forward<Args>(args)...); for (int i = 0, addInd = 0, remInd = 0, queryInd = 0; i < E; i++) { if (type[i] == 1) { int j = lower_bound(A.begin(), A.end(), add[addInd++]) - A.begin(); events.emplace_back(j, last[j]); last[j] = i; } else if (type[i] == -1) { int j = lower_bound(A.begin(), A.end(), rem[remInd++]) - A.begin(); events.emplace_back(j, last[j]); int temp = events[last[j]].second; events[last[j]].second = i; last[j] = temp; } else events.emplace_back(queryInd++, i); } function<void(int, int)> dc = [&] (int l, int r) { if (l == r) { if (events[l].second == l) ans.push_back(s.query(queries[events[l].first])); return; } int m = l + (r - l) / 2; int cnt = 0; for (int i = m + 1; i <= r; i++) if (events[i].second < l) { s.push(A[events[i].first]); cnt++; } dc(l, m); for (int i = 0; i < cnt; i++) s.pop(); cnt = 0; for (int i = l; i <= m; i++) if (events[i].second > r) { s.push(A[events[i].first]); cnt++; } dc(m + 1, r); for (int i = 0; i < cnt; i++) s.pop(); }; if (E > 0) dc(0, E - 1); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../datastructures/trees/fenwicktrees/BitFenwickTree.h" #include "../datastructures/WaveletMatrixAggregationOfflineUpdates.h" using namespace std; // Supports online queries for the number of distinct elements in the // range [l, r] for an array A of length N where the sequence of all update // indices and values are known beforehand // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // C: a container representing a mapping from type T to a set of integers // Constructor Arguments: // A: a vector of type T of the initial values in the array // updates: a vector of pairs of type int and T with the first element // representing the index being updated, and the second element being the // the value it is updated to // ...args: arguments to pass to the constructor of an instance of type C // Functions: // processNextUpdate(): processes the next update (starting with the intial // array and proceeding in the order given by the updates vector) // query(l, r): returns the number of distinct values in the range [l, r] in // the current array // In practice, has a small constant, slgithly faster than the online version // Time Complexity: // constructor: O((N + U) log (N + U)) for U total updates // query: O(log(N + U) log((N + U) / 64)) for U total updates // Memory Complexity: O(N + ((N + U) log (N + U)) / 64) for U total updates // Tested: // https://dmoj.ca/problem/mnyc17p6 template <class T, class C = map<T, set<int>>> struct CountDistinctOfflineUpdates { struct R { using Data = int; using Lazy = int; static Data qdef() { return 0; } static Data merge(const Data &l, const Data &r) { return l + r; } static Data applyLazy(const Data &l, const Lazy &r) { return l + r; } BitFenwickTree FT; R(const vector<Data> &A) : FT(A.size()) { for (int i = 0; i < int(A.size()); i++) FT.set(i, A[i]); FT.build(); } void update(int i, const Lazy &val) { FT.update(i, val); } Data query(int l, int r) { return FT.query(l, r); } }; C M; int N, cur, ucnt; vector<int> en; vector<pair<int, int>> wupds; WaveletMatrixAggregationOfflineUpdates<int, R> wm; void add(int i, const T &v, vector<pair<int, int>> &wus) { set<int> &mv = M[v]; auto it = mv.upper_bound(i); int j = it == mv.begin() ? -1 : *prev(it); wus.emplace_back(i, j); if (it != mv.end()) wus.emplace_back(*it, i); mv.insert(it, i); } void rem(int i, const T &v, vector<pair<int, int>> &wus) { set<int> &mv = M[v]; auto it = mv.erase(mv.find(i)); int j = it == mv.begin() ? -1 : *prev(it); wus.emplace_back(i, N); if (it != mv.end()) wus.emplace_back(*it, j); } vector<pair<int, int>> init1(vector<T> A, const vector<pair<int, T>> &updates) { vector<pair<int, int>> ret; for (int i = 0; i < int(A.size()); i++) add(i, A[i], ret); cur = ret.size(); for (int i = 0; i < int(updates.size()); i++) { int j = updates[i].first; rem(j, A[j], ret); add(j, A[j] = updates[i].second, ret); en[i] = ret.size(); } return ret; } WaveletMatrixAggregationOfflineUpdates<int, R> init2(const vector<T> &A) { int N = A.size(); vector<vector<int>> vals(N); for (auto &&wu : wupds) vals[wu.first].push_back(wu.second); return WaveletMatrixAggregationOfflineUpdates<int, R>(vector<int>(N, N), vector<int>(N, 1), vals); } template <class ...Args> CountDistinctOfflineUpdates(const vector<T> &A, const vector<pair<int, T>> &updates, Args &&...args) : M(forward<Args>(args)...), N(A.size()), cur(0), ucnt(0), en(updates.size(), 0), wupds(init1(A, updates)), wm(init2(A)) { for (int k = 0; k < cur; k++) wm.updateToNextKey(wupds[k].first); } void processNextUpdate() { for (; cur < en[ucnt]; cur++) wm.updateToNextKey(wupds[cur].first); ucnt++; } int query(int l, int r) { return wm.query(l, r, l - 1); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../datastructures/trees/fenwicktrees/BitFenwickTree.h" using namespace std; // Supports offline queries for the number of distinct elements in the // range [l, r] for a static array A of length N // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // Constructor Arguments: // A: a vector of type T of the values in the array // queries: a vector of pairs containing the inclusive endpoints of // the queries // Fields: // ans: a vector of integers with the answer for each query // In practice, has a small constant, faster than Mo and the online version // Time Complexity: // constructor: O(N log N + Q (log Q + log N)) // Memory Complexity: O(N + Q) // Tested: // https://www.spoj.com/problems/DQUERY/ // https://atcoder.jp/contests/abc174/tasks/abc174_f template <class T> struct CountDistinctOffline { vector<int> ans; CountDistinctOffline(const vector<T> &A, const vector<pair<int, int>> &queries) : ans(queries.size()) { int N = A.size(); vector<T> temp = A; sort(temp.begin(), temp.end()); temp.erase(unique(temp.begin(), temp.end()), temp.end()); vector<int> last(temp.size(), -1); vector<tuple<int, int, int>> q; int i = 0; BitFenwickTree ft(N); for (auto &&qi : queries) q.emplace_back(qi.first, qi.second, i++); sort(q.rbegin(), q.rend()); i = N - 1; for (auto &&qi : q) { int l, r, ind; tie(l, r, ind) = qi; for (; i >= l; i--) { int c = lower_bound(temp.begin(), temp.end(), A[i]) - temp.begin(); if (last[c] != -1) ft.update(last[c], 0); ft.update(last[c] = i, 1); } ans[ind] = ft.query(r); } } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../datastructures/trees/fenwicktrees/SparseFenwickTrees2D.h" using namespace std; // Supports online queries for the number of distinct elements in the // range [l, r] for an array A of length N with point updates // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // C: a container representing a mapping from type T to a set of integers // Constructor Arguments: // A: a vector of type T of the initial values in the array // SCALE: the value to scale sqrt by // ...args: arguments to pass to the constructor of an instance of type C // Functions: // update(i, v): updates index i with the value v // query(l, r): returns the number of distinct values in the range [l, r] // In practice, has a very small constant, slightly slower than the // offline version // Time Complexity: // constructor: O(N log N) // update: O(log N) // query: O(log N sqrt(N + U)) for U updates // Memory Complexity: O((N + U) log N) for U updates // Tested: // https://dmoj.ca/problem/mnyc17p6 template <class T, class C = map<T, set<int>>> struct CountDistinctUpdates { vector<T> A; C M; SemiSparseFenwickTree2DSimple<int> ft; void add(int i, const T &v) { set<int> &mv = M[v]; auto it = mv.upper_bound(++i); int j = it == mv.begin() ? 0 : *prev(it); ft.add(j, i); if (it != mv.end()) { ft.rem(j, *it); ft.add(i, *it); } mv.insert(it, i); } void rem(int i, const T &v) { set<int> &mv = M[v]; auto it = mv.erase(mv.find(++i)); int j = it == mv.begin() ? 0 : *prev(it); ft.rem(j, i); if (it != mv.end()) { ft.rem(i, *it); ft.add(j, *it); } } void update(int i, const T &v) { rem(i, A[i]); add(i, A[i] = v); } int query(int l, int r) { return ft.query(l, l + 1, r + 1); } template <class ...Args> CountDistinctUpdates(const vector<T> &A, double SCALE = 1, Args &&...args) : A(A), M(forward<Args>(args)...), ft(A.size() + 1, SCALE) { for (int i = 0; i < int(A.size()); i++) add(i, A[i]); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Fast Subset Transform (similar to SumOverSubsets) // Template Arguments: // TYPE: the type of susbet transform (OR, AND, or XOR) // T: the type of each element // Function Arguments: // a: a reference to the vector of type T to transform // inv: a boolean indicating whether the inverse transform should be // performed or not // In practice, has a small constant // Time Complexity: O(N log N) where N = size(a) // Memory Complexity: O(1) // Tested: // https://judge.yosupo.jp/problem/subset_convolution // https://judge.yosupo.jp/problem/bitwise_and_convolution // https://judge.yosupo.jp/problem/bitwise_xor_convolution // https://csacademy.com/contest/round-53/task/maxor/ const int OR = 0, AND = 1, XOR = 2; template <const int TYPE, class T> void fst(vector<T> &a, bool inv) { int N = a.size(); assert(!(N & (N - 1))); for (int len = 1; len < N; len <<= 1) for (int i = 0; i < N; i += len << 1) for (int j = 0; j < len; j++) { T &u = a[i + j], &v = a[len + i + j]; if (TYPE == OR) tie(u, v) = inv ? make_pair(v, u - v) : make_pair(u + v, u); else if (TYPE == AND) tie(u, v) = inv ? make_pair(v - u, u) : make_pair(v, u + v); else if (TYPE == XOR) tie(u, v) = make_pair(u + v, u - v); else assert(false); } if (TYPE == XOR && inv) for (auto &&ai : a) ai /= T(N); }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "BinaryExponentiation.h" #include "ModularArithmetic.h" using namespace std; // Computes n! // Template Arguments: // T: the type of n // Function Arguments: // n: the value to find the factorial of, must be non negative // Return Value: n! // In practice has a very small constant // Time Complexity: O(n) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T factorial(T n) { T ret = 1; for (T i = 2; i <= n; i++) ret *= i; return ret; } // Computes n! modulo mod // Template Arguments: // T: the type of n and mod // Function Arguments: // n: the value to find the factorial of, must be non negative // mod: the modulo, must be not less than 2 // Return Value: n! modulo mod // In practice has a very small constant // Time Complexity: O(n) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T factorialMod(T n, T mod) { T ret = 1; for (T i = 2; i <= n; i++) ret = mulMod(ret, i, mod); return ret; } // Computes n permute k (n! / (n - k)!) // Template Arguments: // T: the type of n and k // Function Arguments: // n: the total number of elements, must be non negative // k: the number of elements to permute, must be in the range [0, n] // Return Value: n permute k // In practice has a very small constant // Time Complexity: O(min(k, n - k)) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T permute(T n, T k) { T ret = 1; for (T i = 0; i < k; i++) ret = ret * (n - i); return ret; } // Computes n permute k (n! / (n - k)!) modulo mod // Template Arguments: // T: the type of n, k, and mod // Function Arguments: // n: the total number of elements, must be non negative // k: the number of elements to permute // mod: the modulo, must be not less than 2 // Return Value: n permute k modulo mod // In practice has a very small constant // Time Complexity: O(min(k, n - k)) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T permuteMod(T n, T k, T mod) { T ret = 1; for (T i = 0; i < k; i++) ret = mulMod(ret, n - i, mod); return ret; } // Computes n choose k (n! / (k! (n - k)!)) // Template Arguments: // T: the type of n and k // Function Arguments: // n: the total number of elements, must be non negative // k: the number of elements to choose, must be in the range [0, n] // Return Value: n choose k // In practice has a very small constant // Time Complexity: O(min(k, n - k)) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T choose(T n, T k) { if (k > n - k) k = n - k; T ret = 1; for (T i = 0; i < k; i++) ret = ret * (n - i) / (i + 1); return ret; } // Computes n choose k (n! / (k! (n - k)!)) modulo a prime p // Template Arguments: // T: the type of n, k, and p // Function Arguments: // n: the total number of elements, must be non negative // k: the number of elements to choose, must be in the range [0, n] // p: the prime modulo, must be greater than n // Return Value: n permute k modulo p // In practice has a very small constant // Time Complexity: O(min(k, n - k) + log(p)) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T chooseModPrime(T n, T k, T p) { if (k > n - k) k = n - k; T num = 1, den = 1; for (T i = 0; i < k; i++) { num = mulMod(num, n - i, p); den = mulMod(den, i + 1, p); } return divModPrime(num, den, p); } // Computes n multichoose k ((n + k - 1)! / (k! (n - 1)!)) // Template Arguments: // T: the type of n and k // Function Arguments: // n: the total number of elements, must be positive // k: the number of elements to choose with repetitions, must be non negative // Return Value: n choose k // In practice has a very small constant // Time Complexity: O(min(k, n - 1)) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T multiChoose(T n, T k) { return choose(n + k - 1, k); } // Computes n multichoose k ((n + k - 1)! / (k! (n - 1)!)) modulo a prime p // Template Arguments: // T: the type of n, k, and p // Function Arguments: // n: the total number of elements, must be positive // k: the number of elements to choose with repetitions, must be non negative // p: the prime modulo // Return Value: n permute k modulo p // In practice has a very small constant // Time Complexity: O(min(k, n - 1) + log(p)) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T multiChooseModPrime(T n, T k, T p) { return chooseModPrime(n + k - 1, k, p); } // Combinatorics struct to compute factorials, permutations, and combinations // Template Arguments: // T: the type of the value of N! // Constructor Arguments: // N: the maximum value to compute factorials of // Functions: // factorial(n): returns n! for 0 <= n <= N // permute(n, k): returns n permute k (n! / (n - k)!) for 0 <= k <= n <= N // choose(n, k): returns n permute k (n! / (k! (n - k)!)) // for 0 <= k <= n <= N // multiChoose(n, k): returns n permute k ((n + k - 1)! / (k! (n - 1)!)) // for n >= 1, k >= 0, n + k - 1 <= N // In practice, has a very small constant // Time Complexity: // constructor: O(N) // factorial, permute, choose, multiChoose: O(1) // Memory Complexity: O(N) // Tested: // Fuzz Tested template <class T> struct Combinatorics { vector<T> fact; Combinatorics(int N) : fact(N + 1, 1) { for (int i = 1; i <= N; i++) fact[i] = fact[i - 1] * i; } T factorial(int n) { return fact[n]; } T permute(int n, int k) { return fact[n] / fact[n - k]; } T choose(int n, int k) { return fact[n] / fact[k] / fact[n - k]; } T multiChoose(int n, int k) { return choose(n + k - 1, k); } }; // Combinatorics struct to compute factorials, permutations, and combinations // modulo a prime P // Template Arguments: // T: the type of the value of N! and P // Constructor Arguments: // N: the maximum value to compute factorials of // P: the prime modulo P, must be greater than N // Functions: // factorial(n): returns n! modulo P for 0 <= n <= N // invFactorial(n): returns multiplicative inverse of n! modulo P // for 0 <= n <= N // permute(n, k): returns n permute k (n! / (n - k)!) modulo P // for 0 <= k <= n <= N // choose(n, k): returns n permute k (n! / (k! (n - k)!)) modulo P // for 0 <= k <= n <= N // multiChoose(n, k): returns n permute k ((n + k - 1)! / (k! (n - 1)!)) // modulo P for n >= 1, k >= 0, n + k - 1 <= N // In practice, has a very small constant // Time Complexity: // constructor: O(N + log P) // factorial, invFactorial, permute, choose, multiChoose: O(1) // Memory Complexity: O(N) // Tested: // Fuzz Tested template <class T> struct CombinatoricsModPrime { vector<T> fact, invFact; T P; CombinatoricsModPrime(int N, T P) : fact(N + 1, 1), invFact(N + 1), P(P) { for (int i = 1; i <= N; i++) fact[i] = mulMod(fact[i - 1], T(i), P); invFact[N] = mulInvModPrime(fact[N], P); for (int i = N - 1; i >= 0; i--) invFact[i] = mulMod(invFact[i + 1], T(i + 1), P); } T factorial(int n) { return fact[n]; } T invFactorial(int n) { return invFact[n]; } T permute(int n, int k) { return mulMod(fact[n], invFact[n - k], P); } T choose(int n, int k) { return mulMod(mulMod(fact[n], invFact[k], P), invFact[n - k], P); } T multiChoose(int n, int k) { return choose(n + k - 1, k); } }; // Computes a row of Pascal's triangle // Template Arguments: // T: the type of the values in the row of Pascal's triangle // Function Arguments: // N: the row of Pascal's triangle to compute // Return Value: a vector of length N + 1 with the values in the Nth row of // Pascal's triangle // In practice, has a very small constant // Time Complexity: O(N) // Memory Complexity: O(N) // Tested: // Fuzz Tested template <class T> vector<T> pascalsRow(int N) { vector<T> C(N + 1, 1); for (int j = 1; j <= N; j++) C[j] = C[j - 1] * (N - j + 1) / j; return C; } // Computes a row of Pascal's triangle modulo a prime p // Template Arguments: // T: the type of the values in the row of Pascal's triangle // Function Arguments: // N: the row of Pascal's triangle to compute // p: the prime modulo, must be greater than N // Return Value: a vector of length N + 1 with the values in the Nth row of // Pascal's triangle modulo a prime p // In practice, has a small constant // Time Complexity: O(N log N) // Memory Complexity: O(N) template <class T> vector<T> pascalsRowModPrime(int N, T p) { vector<T> C(N + 1, 1); for (int j = 1; j <= N; j++) C[j] = divModPrime(mulMod(C[j - 1], T(N - j + 1), p), T(j), p); return C; } // Computes Pascal's triangle // Template Arguments: // T: the type of the values in Pascal's triangle // Function Arguments: // N: the maximum row of Pascal's triangle to compute // Return Value: a vector of vectors length N + 1 with the ith vector having // length i + 1 with the values in the ith row of Pascal's triangle // In practice, has a very small constant // Time Complexity: O(N^2) // Memory Complexity: O(N^2) // Tested: // Fuzz Tested template <class T> vector<vector<T>> pascalsTriangle(int N) { vector<vector<T>> C(N + 1); for (int i = 0; i <= N; i++) { C[i] = vector<T>(i + 1, 1); for (int j = 1; j < i; j++) C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } return C; } // Computes Pascal's triangle modulo mod // Template Arguments: // T: the type of the values in Pascal's triangle and mod // Function Arguments: // N: the maximum row of Pascal's triangle to compute // mod: the modulo, must be not less than 2 // Return Value: a vector of vectors length N + 1 with the ith vector having // length i + 1 with the values in the ith row of Pascal's triangle // modulo mod // In practice, has a very small constant // Time Complexity: O(N^2) // Memory Complexity: O(N^2) // Tested: // Fuzz Tested template <class T> vector<vector<T>> pascalsTriangleMod(int N, T mod) { vector<vector<T>> C(N + 1); for (int i = 0; i <= N; i++) { C[i] = vector<T>(i + 1, 1); for (int j = 1; j < i; j++) C[i][j] = addMod(C[i - 1][j - 1], C[i - 1][j], mod); } return C; } // Computes the sum from 1 to n inclusive // Template Arguments: // T: the type of n // Function Arguments: // n: the maximum bound, must be non negative // Return Value: the sum from 1 to n inclusive // In practice has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T sumTo(T n) { return n * (n + 1) / 2; } // Computes the sum from a to b inclusive // Template Arguments: // T: the type of n // Function Arguments: // a: the lower bound, must be non negative // b: the upper bound, must be non negative and not less than a // Return Value: the sum from a to b inclusive // In practice has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T sumBetween(T a, T b) { return sumTo(b) - sumTo(a - 1); } // Computes the nth term of an arithmetic sequence with starting value a1 and // common difference d // Template Arguments: // T: the type of a1 and d // U: the type of n // Function Arguments: // a1: the starting value // d: the common difference // n: the index of the term to find, must be positive // Return Value: the nth term of the arithmetic sequence // In practice has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T, class U> T arithSeq(T a1, T d, U n) { return a1 + d * (n - 1); } // Computes the sum of an arithmetic sequence with starting value a1 and // common difference d from term 1 to n // Template Arguments: // T: the type of a1 and d // U: the type of n // Function Arguments: // a1: the starting value // d: the common difference // n: the maximum index of the term to sum, must be positive // Return Value: the sum of the arithmetic sequence from term 1 to n // In practice has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Fuzz Tested template <class T, class U> T arithSeries(T a1, T d, U n) { return n * (a1 + arithSeq(a1, d, n)) / 2; } // Computes the nth term of an geometric sequence with starting value a1 and // common ratio r // Template Arguments: // T: the type of a1 and r // U: the type of n // Function Arguments: // a1: the starting value // r: the common ratio // n: the index of the term to find, must be positive // Return Value: the nth term of the geometric sequence // In practice has a small constant // Time Complexity: O(log n) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T, class U> T geoSeq(T a1, T r, U n) { return a1 * pow2(r, n - 1); } // Computes the sum of a geometric sequence with starting value a1 and // common ratio r from term 1 to n // Template Arguments: // T: the type of a1 and r // U: the type of n // Function Arguments: // a1: the starting value // r: the common ratio // n: the maximum index of the term to sum, must be positive // Return Value: the sum of the geometric sequence from term 1 to n // In practice has a small constant // Time Complexity: O(log n) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T, class U> T geoSeries(T a1, T r, U n) { return r == 1 ? a1 * n : a1 * (T(1) - pow2(r, n)) / (T(1) - r); } // Computes the sum of a infinite geometric sequence with starting value a1 and // common ratio r where -1 < r < 1 // Template Arguments: // T: the type of a1 and r // Function Arguments: // a1: the starting value // r: the common ratio // Return Value: the sum of the infinite geometric sequence // In practice has a small constant // Time Complexity: O(1) // Memory Complexity: O(1) template <class T> T infGeoSeries(T a1, T r) { assert(-1 < r && r < 1); return a1 / (T(1) - r); } // Computes the sum of floor((a * i + b) / m) for 0 <= i < n // Equivalent to the number of integer points (x, y) where 0 <= x < n and // 0 <= y <= (a * i + b) / m // Template Arguments: // T: an integral type // Function Arguments: // n: the upper bound for x // a: the linear factor's numerator // b: the constant factor's numerator // m: the common denominator // Return Value: the sum of floor((a * i + b) / m) for 0 <= i < n // In practice, has a small constant // Time Complexity: O(log n) // Memory Complexity: O(1) // Tested: // https://judge.yosupo.jp/problem/sum_of_floor_of_linear template <class T> T sumFloorLinear(T n, T a, T b, T m) { static_assert(is_integral<T>::value, "T must be integral"); if (a == 0) return (b / m) * n; if (a >= m || b >= m) return ((a / m) * (n - 1) + 2 * (b / m)) * n / 2 + sumFloorLinear(n, a % m, b % m, m); return sumFloorLinear((a * n + b) / m, m, (a * n + b) % m, a); }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "GCD.h" using namespace std; // Data structure representing a fraction // Template Arguments: // T: the type of the numerator and denominator, must be integral // Constructor Arguments: // num: the numerator // den: the denominator, should be non negative // Fields: // num: the numerator // den: the denominator // Functions: // reduce(): reduces the fraction to lowest terms with a positive denominator // +, +=, -, -=, *, *=, /, /=: standard arithmetic operators on fractions // <, <=, >, >=, ==, !=: comparison operators // >>, <<: input and output operators // Time Complexity: // constructor, +, +=, -, -=, *, *=, /, /=, >>, <<: O(1) // reduce, <, <=, >, >=, ==, !=: O(log(max(num, den))) // Memory Complexity: O(1) // Tested: // https://dmoj.ca/problem/bfs19p4 template <class T> struct Fraction { static_assert(is_integral<T>::value, "T must be an integral type"); using F = Fraction<T>; T num, den; constexpr Fraction(T num = T(), T den = T(1)) : num(num), den(den) {} F reduce() const { T g = gcd(num, den); return den >= 0 ? F(num / g, den / g) : F(-num / g, -den / g); } F operator + (const F &f) const { return F(*this) += f; } F &operator += (const F &f) { num = (num * f.den + f.num * den); den = den * f.den; return *this; } F operator - (const F &f) const { return F(*this) -= f; } F &operator -= (const F &f) { num = (num * f.den - f.num * den); den = den * f.den; return *this; } F operator + () const { return *this; } F operator - () const { return F(-num, den); } F operator * (const F &f) const { return F(*this) *= f; } F &operator *= (const F &f) { num = num * f.num; den = den * f.den; return *this; } F operator / (const F &f) const { return F(*this) /= f; } F &operator /= (const F &f) { T t_num = num * f.den, t_den = den * f.num; num = t_num; den = t_den; return *this; } bool operator < (const F &f) const { F a = den >= 0 ? *this : F(-num, -den); F b = f.den >= 0 ? f : F(-f.num, -f.den); return a.num * b.den < b.num * a.den; } bool operator <= (const F &f) const { return !(f < *this); } bool operator > (const F &f) const { return f < *this; } bool operator >= (const F &f) const { return !(*this < f); } bool operator == (const F &f) const { return !(*this < f) && !(f < *this); } bool operator != (const F &f) const { return *this < f || f < *this; } friend istream &operator >> (istream &stream, F &f) { return stream >> f.num >> f.den; } friend ostream &operator << (ostream &stream, const F &f) { return stream << f.num << '/' << f.den; } }; #define ftype long double template <class T> Fraction<T> abs(Fraction<T> a) { return a >= 0 ? a : -a; } #define FUN(name) \ template <class T> ftype name(Fraction<T> a) { \ return name((ftype)(a.num) / (ftype)(a.den)); \ } FUN(sqrt) FUN(sin) FUN(cos) FUN(tan) FUN(asin) FUN(acos) FUN(atan) #undef FUN template <class T> ftype atan2(Fraction<T> y, Fraction<T> x) { return atan2((ftype)(y.num) / (ftype)(y.den), (ftype)(x.num) / (ftype)(x.den)); } #undef ftype
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Karatsuba Multiplication // Template Arguments: // T: the type of each element // ItA: the type of the iterator pointing to the first multiplyPolynomial // ItB: the type of the iterator pointing to the second polynomial // ItRes: the type of the iterator pointing to the result polynomial // Function Arguments: // n: the length of the polynomial, must be a power of 2 // a: a pointer to the first polynomial of length n, a[i] stores // the coefficient of x^i // b: a pointer to the second polynomial of length n, b[i] stores // the coefficient of x^i // res: a pointer to the result polynomial of length 2n which stores the // result of a multipled by b, res[i] stores the coefficient of x^i // In practice, has a small constant, slower than FFT and NTT // Time Complexity: O(n^log_2(3)) // Memory Complexity: O(n) // Tested: // https://open.kattis.com/problems/polymul2 // https://dmoj.ca/problem/atimesb const int KARATSUBA_CUTOFF = 16; template <class T, class ItA, class ItB, class ItRes> void karatsuba(int n, ItA a, ItB b, ItRes res) { if (n <= KARATSUBA_CUTOFF) { fill(res, res + n * 2, 0); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) res[i + j] += a[i] * b[j]; return; } assert(!(n & (n - 1))); int k = n / 2; vector<T> tmp(n, T()), c(n, T()); auto atmp = tmp.begin(), btmp = atmp + k; for (int i = 0; i < k; i++) { atmp[i] = a[i] + a[i + k]; btmp[i] = b[i] + b[i + k]; } karatsuba<T>(k, atmp, btmp, c.begin()); karatsuba<T>(k, a, b, res); karatsuba<T>(k, a + k, b + k, res + n); for (int i = 0; i < k; i++) { T t = res[i + k]; res[i + k] += c[i] - res[i] - res[i + k * 2]; res[i + k * 2] += c[i + k] - t - res[i + k * 3]; } } // Polynomial Multiplication // Template Arguments: // T: the type of each element // Functions Arguments: // a: a vector of type T representing the first polynomial, a[i] stores // the coefficient of x^i // b: a vector of type T representing the second polynomial, b[i] stores // the coefficient of x^i // Return Value: a vector of type T representing the polynomial a times b with // no trailing zeros // In practice, has a small constant // Time Complexity: O(n^log_2(3)) where n = max(size(a), size(b)) // Memory Complexity: O(n) // Tested: // https://open.kattis.com/problems/polymul2 template <class T> vector<T> mulPolyKaratsuba(vector<T> a, vector<T> b) { int n = max(a.size(), b.size()); while (n & (n - 1)) n++; a.resize(n, T()); b.resize(n, T()); vector<T> res(n * 2, T()); karatsuba<T>(n, a.begin(), b.begin(), res.begin()); while (int(res.size()) > 1 && res.back() == T()) res.pop_back(); return res; } // Integer Multiplication // Template Arguments: // T: the type of each digit // Functions Arguments: // a: a vector of type T representing the first integer, a[i] stores // the digit of BASE^i // b: a vector of type T representing the second polynomial, b[i] stores // the digit of BASE^i // BASE: the base of the integer // Return Value: a vector of type T representing the integer a times b with // no trailing zeros // In practice, has a small constant // Time Complexity: O(n^log_2(3)) where n = max(size(a), size(b)) // Memory Complexity: O(n) // Tested: // https://dmoj.ca/problem/atimesb template <class T> vector<T> mulIntKaratsuba(vector<T> a, vector<T> b, T BASE = T(10)) { vector<T> res = mulPolyKaratsuba(move(a), move(b)); T carry = T(); res.reserve(res.size() + 1); for (int i = 0; i < int(res.size()); i++) { T cur = res[i] + carry; res[i] = T(cur % BASE); carry = T(cur / BASE); } if (carry > T()) res.push_back(carry); return res; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes the floor of the sqrt of an integer // Template Arguments: // T: the type of x, must be integral // Function Arguments: // x: the value to compute the sqrt of, must be non-negative // Return Value: returns the floor of the sqrt of x // In practice, has a moderate constant, slower than binary search, but this // does not overflow // Time Complexity: O(log x) // Memory Complexity: O(1) // Tested: // https://codeforces.com/gym/100753/problem/F template <class T> T isqrt(T x) { static_assert(is_integral<T>::value, "T must be integral"); assert(x >= 0); if (x <= 1) return x; T y = x, z = 0; while (y > z) z = x / (y = (y + z) / 2); return y; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "ModularArithmetic.h" #include "GCD.h" #include "Primes.h" using namespace std; // Computes the nth tetration of a modulo mod // Assumes 0^0 = 1 // Template Arguments: // T: the type of base and mod // U: the type of the number of iterations // Function Arguments: // a: the base // n: the number of iterations // mod: the modulo // Return Value: the nth tetration of a modulo mod, // a value in the range [0, mod) // In practice, has a small constant // Time Complexity: O(sqrt(mod) log(mod)) // Memory Complexity: O(log(mod)) // Tested: // https://judge.yosupo.jp/problem/tetration_mod template <class T, class U> T tetraMod(T a, U n, T mod) { if (mod == T(1)) return T(0); if (a == T(0)) return (T(1) - T(n % U(2))) % mod; if (n == U(0)) return T(1) % mod; if (n == U(1)) return a % mod; if (n == U(2)) return powMod(a % mod, a, mod); T p = phi(mod), ret = tetraMod(a, n - 1, p); if (ret == 0) ret += p; return powMod(a % mod, ret, mod); } // Helper function returning a * b % mod + mod if a * b >= mod, // a * b % mod otherwise template <class T> T mulMod2(T a, T b, T mod) { return (a *= b) >= mod ? a % mod + mod : a; } // Helper function returning base^pow % mod + mod if base^pow >= mod, // base^pow % mod otherwise template <class T, class U> T powMod2(T base, U pow, T mod) { if (base >= mod) base = base % mod + mod; T x = 1; while (true) { if (pow % 2 == 1) x = mulMod2(x, base, mod); if ((pow /= 2) == 0) break; base = mulMod2(base, base, mod); } return x; } // Helper function template <class T> T powSeqModRec(const vector<T> &A, int i, T mod) { if (i == int(A.size()) - 1) return A[i]; T p = phi(mod), res = powSeqModRec(A, i + 1, p); return res == T(0) ? T(1) : powMod2(A[i], res, mod); } // Computes A[0]^A[1]^...^A[N - 1] modulo mod // Assumes 0^0 = 1 // Template Arguments: // T: the type of each element in the sequence // Function Arguments: // A: the sequence // mod: the modulo // Return Value: A[0]^A[1]^...^A[N - 1] modulo mod, // a value in the range [0, mod) // In practice, has a small constant // Time Complexity: O(N + sqrt(mod) log(mod)) // Memory Complexity: O(N + log(mod)) // Tested: // https://dmoj.ca/problem/dmopc20c3p5 template <class T> T powSeqMod(const vector<T> &A, T mod) { return powSeqModRec(A, 0, mod) % mod; } // Finds an integer x such that (x^2 = a) modulo a prime p // If x is a solution, then (p - x) % p is the other solution // Template Arguments: // T: the type of a and p // Function Arguments: // a: the argument, must be in the range [0, p) // p: the prime modulo // Return Value: the square root of a modulo p in the range [0, p), or -1 if // it does not exist, // In practice, has a small constant // Time Complexity: O(log(p)^2) // Memory Complexity: O(1) // Tested: // https://judge.yosupo.jp/problem/sqrt_mod template <class T> T sqrtMod(T a, T p) { if (a == T(0)) return 0; if (powMod(a, (p - 1) / 2, p) != T(1)) return -1; if (p % 4 == 3) return powMod(a, (p + 1) / 4, p); T s = p - 1, n = 2; int r = 0; for (; s % 2 == 0; s /= 2) r++; while (powMod(n % p, (p - 1) / 2, p) != p - 1) n++; T x = powMod(a, (s + 1) / 2, p), b = powMod(a, s, p); T g = powMod(n % p, s, p); while (true) { T t = b, m = T(0); for (; m < r && t != T(1); m++) t = mulMod(t, t, p); if (m == T(0)) return x; T gs = g; for (int i = 0; i < r - m - 1; i++) gs = mulMod(gs, gs, p); g = mulMod(gs, gs, p); x = mulMod(x, gs, p); b = mulMod(b, g, p); r = m; } return -1; } // Finds the smallest non negative integer c such that // (a^c = b) modulo mod // Assumes 0^0 = 1 // Template Arguments: // T: the type of a, b, and mod // Function Arguments: // a: the base, must be in the range [0, mod) // b: the argument, must be in the range [0, mod) // mod: the modulo // Return Value: the discrete log of b in base a modulo mod, or -1 if // it does not exist // In practice, has a small constant // Time Complexity: O(sqrt(mod) log(mod)) // Memory Complexity: O(sqrt(mod)) // Tested: // https://judge.yosupo.jp/problem/discrete_logarithm_mod template <class T> T discreteLogMod(T a, T b, T mod) { if (b == T(1) % mod) return 0; T n = max(T(0), T(sqrt(mod)) - 1), e = T(1), f = T(1), j = T(1); vector<pair<T, T>> A; while (n * n <= mod) n++; while (j <= n && (e = f = mulMod(e, a, mod)) != b) A.emplace_back(mulMod(e, b, mod), j++); if (e == b) return j; sort(A.begin(), A.end()); if (gcd(mod, e) == gcd(mod, b)) { for (T i = 2; i <= n + 1; i++) { e = mulMod(e, f, mod); auto it = lower_bound(A.begin(), A.end(), make_pair(e, T(0))); if (it != A.end() && it->first == e) return n * i - it->second; } } return -1; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Given a set of N points, P[i] = (X[i], Y[i]), compute a polynomial Q of // degree N - 1, such that Q passes through them: // Q(x) = A[0] * x^0 + ... + A[N - 1] * x^(N - 1). // For real numbers, pick X[i] = C * cos(i / (N - 1) * PI) for a // large constant C // Template Arguments: // T: the type of the x and y values, as well as the coefficients // Function Arguments: // P: a vector of pairs of type T representing the N points // Return Value: a polynomial of degree N - 1 (with N coefficients) with // the ith coefficient associated with the term x^i // In practice, has a small constant // Time Complexity: O(N^2) // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/angieandfunctions template <class T> vector<T> lagrangePolynomialInterpolation(vector<pair<T, T>> P) { int N = P.size(); vector<T> A(N, T()), temp(N, T()); temp[0] = T(1); for (int k = 0; k < N; k++) for (int i = k + 1; i < N; i++) P[i].second = (P[i].second - P[k].second) / (P[i].first - P[k].first); T last = T(); for (int k = 0; k < N; k++) for (int i = 0; i < N; i++) { A[i] += P[k].second * temp[i]; swap(last, temp[i]); temp[i] -= P[k].first * last; } return A; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "GCD.h" using namespace std; // Computes the non negative remainder of a by mod // Template Arguments: // T: the type of a and mod // Function Arguments: // a: the value to find the non negative remainder // mod: the modulo // Return Value: the non negative remainder of a by mod // In practice, has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // https://dmoj.ca/problem/bts18p5 template <class T> T posMod(T a, T mod) { T ret = -mod < a && a < mod ? a : a % mod; return 0 <= ret ? ret : ret + mod; } // Adds two integers a and b modulo mod // Template Arguments: // T: the type of a, b, and mod // Function Arguments: // a: the first value, must be in the range [0, mod) // b: the second value, must be in the range [0, mod) // mod: the modulo // Return Value: a + b modulo mod, a value in the range [0, mod) // In practice, has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // https://open.kattis.com/problems/modulararithmetic // https://dmoj.ca/problem/bts18p5 template <class T> T addMod(T a, T b, T mod) { T ret = a + b; return ret < mod ? ret : ret - mod; } // Subtracts two integers a and b modulo mod // Template Arguments: // T: the type of a, b, and mod // Function Arguments: // a: the first value, must be in the range [0, mod) // b: the second value, must be in the range [0, mod) // mod: the modulo // Return Value: a - b modulo mod, a value in the range [0, mod) // In practice, has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // https://open.kattis.com/problems/modulararithmetic template <class T> T subMod(T a, T b, T mod) { return a >= b ? a - b : a + mod - b; } // Multiplies two integers a and b modulo mod where a * b does not overflow // Template Arguments: // T: the type of a, b, and mod // Function Arguments: // a: the first value, must be in the range [0, mod) // b: the second value, must be in the range [0, mod) // mod: the modulo // Return Value: a * b modulo mod, a value in the range [0, mod) // In practice, has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // https://open.kattis.com/problems/modulararithmetic // https://atcoder.jp/contests/m-solutions2019/tasks/m_solutions2019_e // https://dmoj.ca/problem/bts18p5 template <class T> T mulMod(T a, T b, T mod) { return a * b % mod; } // Computes base to the power pow modulo mod where mod * mod does not overflow // Assumes 0^0 = 1 // Template Arguments: // T: the type of base and mod // U: the type of pow // Function Arguments: // base: the base, must be in the range [0, mod) // pow: the power, must be non negative and integral // mod: the modulo // Return Value: base to the power pow modulo mod, // a value in the range [0, mod) // In practice, has a small constant // Time Complexity: O(log pow) // Memory Complexity: O(1) // Tested: // https://atcoder.jp/contests/m-solutions2019/tasks/m_solutions2019_e template <class T, class U> T powMod(T base, U pow, T mod) { T x = 1; while (true) { if (pow % 2 == 1) x = mulMod(x, base, mod); if ((pow /= 2) == 0) break; base = mulMod(base, base, mod); } return x; } // Computes the multiplicative inverse of a for a prime mod p where p * p // does not overflow // Guaranteed to exist // Template Arguments: // T: the type of a and p // Function Arguments: // a: the value to find the inverse of, must be in the range [0, p) // p: the prime modulo // Return Value: the multiplicative inverse of a for a prime mod p // In practice, has a small constant // Time Complexity: O(log p) // Memory Complexity: O(1) // Tested: // https://atcoder.jp/contests/m-solutions2019/tasks/m_solutions2019_e template <class T> T mulInvModPrime(T a, T p) { return powMod(a, p - 2, p); } // Divides a by b modulo a prime p where p * p does not overflow // Guaranteed to be valid // Template Arguments: // T: the type of a, b and p // Function Arguments: // a: the dividend, must be in the range [0, p) // b: the divisor, must be in the range [1, p) // p: the prime modulo // Return Value: a / b modulo p // In practice, has a small constant // Time Complexity: O(log p) // Memory Complexity: O(1) // Tested: // https://atcoder.jp/contests/m-solutions2019/tasks/m_solutions2019_e template <class T> T divModPrime(T a, T b, T p) { return mulMod(a, mulInvModPrime(b, p), p); } // Divides a by b modulo mod // Only valid if gcd(b, mod) == 1 // Template Arguments: // T: the type of a, b and mod // Function Arguments: // a: the dividend, must be in the range [0, mod) // b: the divisor, must be in the range [1, mod) // mod: the modulo // Return Value: a / b modulo mod, or -1 if invalid // In practice, has a small constant // Time Complexity: O(log p) // Memory Complexity: O(1) // Tested: // https://open.kattis.com/problems/modulararithmetic template <class T> T divMod(T a, T b, T mod) { T inv = mulInv(b, mod); return inv == -1 ? -1 : mulMod(a, inv, mod); } // The following functions are useful when mod * mod overflow // Multiplies two integers a and b modulo mod where a * b does overflow, but // mod + mod does not overflow // Template Arguments: // T: the type of a, b, and mod // Function Arguments: // a: the first value, must be in the range [0, mod) // b: the second value, must be in the range [0, mod) // mod: the modulo // Return Value: a * b modulo mod, a value in the range [0, mod) // In practice, has a small constant // Time Complexity: O(log b) // Memory Complexity: O(1) // Tested: // https://atcoder.jp/contests/m-solutions2019/tasks/m_solutions2019_e template <class T> T mulModOvf(T a, T b, T mod) { T x = 0; while (true) { if (b % 2 == 1) x = addMod(x, a, mod); if ((b /= 2) == 0) break; a = addMod(a, a, mod); } return x; } // Computes base to the power pow modulo mod where mod * mod overflows, but // mod + mod does not overflow // Template Arguments: // T: the type of base and mod // U: the type of pow // Function Arguments: // base: the base, must be in the range [0, mod) // pow: the power, must be non negative and integral // mod: the modulo // Return Value: base to the power pow modulo mod, // a value in the range [0, mod) // In practice, has a small constant // Time Complexity: O(log pow log mod) // Memory Complexity: O(1) // Tested: // https://atcoder.jp/contests/m-solutions2019/tasks/m_solutions2019_e template <class T, class U> T powModOvf(T base, U pow, T mod) { T x = 1; while (true) { if (pow % 2 == 1) x = mulModOvf(x, base, mod); if ((pow /= 2) == 0) break; base = mulModOvf(base, base, mod); } return x; } // Computes the multiplicative inverse of a for a prime mod p where p * p // overflows, but mod + mod does not overflow // Guaranteed to exist // Template Arguments: // T: the type of a and p // Function Arguments: // a: the value to find the inverse of, must be in the range [0, p) // p: the prime modulo // Return Value: the multiplicative inverse of a for a prime mod p // In practice, has a small constant // Time Complexity: O(log p log mod) // Memory Complexity: O(1) // Tested: // https://atcoder.jp/contests/m-solutions2019/tasks/m_solutions2019_e template <class T> T mulInvModPrimeOvf(T a, T p) { return powModOvf(a, p - 2, p); } // Divides a by b modulo a prime p where p * p overflows, but mod + mod does // not overflow // Guaranteed to be valid // Template Arguments: // T: the type of a, b and p // Function Arguments: // a: the dividend, must be in the range [0, p) // b: the divisor, must be in the range [1, p) // p: the prime modulo // Return Value: a / b modulo p // In practice, has a small constant // Time Complexity: O(log p log mod) // Memory Complexity: O(1) // Tested: // https://atcoder.jp/contests/m-solutions2019/tasks/m_solutions2019_e template <class T> T divModPrimeOvf(T a, T b, T p) { return mulModOvf(a, mulInvModPrimeOvf(b, p), p); } // Struct supporting operations in Montgomery form // Constructor Arguments: // mod: the modulo of the space // Functions: // init(x): transforms a number into Montgomery form // reduce(x): transforms a number from Montgomery form // mul(a, b): multiplies the numbers a and b in Montgomery form and returns // their product modulo mod in Montgomery form // In practice, has a small constant // Time Complexity: // constructor, init, reduce, mul: O(1) // Memory Complexity: O(1) // Tested: // https://loj.ac/p/6466 // https://www.spoj.com/problems/FACT2/ struct Montgomery { using u64 = uint64_t; using u128 = __uint128_t; using s128 = __int128_t; struct u256 { static u128 HI(u128 x) { return x >> 64; } static u128 LO(u128 x) { return u64(x); } u128 hi, lo; u256(u128 lo = 0) : hi(0), lo(lo) {} u256(u128 hi, u128 lo) : hi(hi), lo(lo) {} static u256 mul(u128 x, u128 y) { u128 t1 = LO(x) * LO(y), t2 = HI(x) * LO(y) + HI(y) * LO(x) + HI(t1); return u256(HI(x) * HI(y) + HI(t2), (t2 << 64) + LO(t1)); } }; u128 mod, inv, r2; Montgomery(u128 mod = 1) : mod(mod), inv(1), r2(-mod % mod) { for (int i = 0; i < 7; i++) inv *= 2 - mod * inv; for (int i = 0; i < 4; i++) if ((r2 <<= 1) >= mod) r2 -= mod; for (int i = 0; i < 5; i++) r2 = mul(r2, r2); } u128 init(u128 x) { return mul(x, r2); } u128 reduce(u256 x) { u128 q = x.lo * inv; s128 a = x.hi - u256::mul(q, mod).hi; return a < 0 ? a + mod : a; } u128 mul(u128 a, u128 b) { return reduce(u256::mul(a, b)); } }; // Multiplies two unsigned 128-bit integers a and b modulo mod even if a * b // overflows, using Montgomery reduction // Function Arguments: // a: the first value, must be in the range [0, mod) // b: the second value, must be in the range [0, mod) // mod: the modulo // Return Value: a * b modulo mod, a value in the range [0, mod) // In practice, has a small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // https://loj.ac/p/6466 // https://www.spoj.com/problems/FACT2/ __uint128_t mulMod(__uint128_t a, __uint128_t b, __uint128_t mod) { static Montgomery mont; if (mont.mod != mod) mont = Montgomery(mod); return mont.reduce(mont.mul(mont.init(a), mont.init(b))); } // Barrett Reduction for fast modulo // Constructor Arguments: // mod: the modulo of the space // Functions: // reduce(a): returns a value congruent to a modulo mod in the range // [0, 2 mod) // In practice, has a very small constant // Time Complexity: // constructor, reduce: O(1) // Memory Complexity: O(1) // Tested: // https://open.kattis.com/problems/modulararithmetic struct Barrett { uint64_t mod, inv; Barrett(uint64_t mod = 1) : mod(mod), inv(uint64_t(-1) / mod) {} uint64_t reduce(uint64_t a) { return a - uint64_t((__uint128_t(inv) * a) >> 64) * mod; } }; // Fast modulo using Barrett Reduction // Function Arguments: // a: the value to modulo // mod: the modulo // Return Value: a modulo mod // In practice, has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // https://open.kattis.com/problems/modulararithmetic uint64_t bmod(uint64_t a, uint64_t mod) { static Barrett b; if (b.mod != mod) b = Barrett(mod); uint64_t ret = b.reduce(a); if (ret >= mod) ret -= mod; return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "FFT.h" using namespace std; // Big Integer // Constructor Arguments: // s: a string of digits // v: a long long // Functions: // read(s): reads a BigInt from a string // write(s): write a BigInt to a string // >>, <<: input and output operators // <, <=, >, >=, ==, !=: comparison operators // isZero(): returns true if the big integer is 0 // abs(): returns the absolute value // ++, --, +, +=, -, -=, *, *=, /, /=, %, %=: standard arithmetic operators // divMod(a1, b1): returns a pair with the quotient and remainder of // a1 divided by b1 // In practice, multiplication has a moderate constant, all other functions // have a small constant // Time Complexity: // constructor: O(N) // isZero: O(1) // read, write, >>, <<, <, <=, >, >=, ==, !=, abs, ++, --, +, +=, -, -=: O(N) // *, *= (long long variants): O(N) // *, *= (BigInt variants): O(N log N) // /, /=, % (long long variants): O(N) // /, /=, %, %= (BigInt variants): O(N^2) // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/aplusb2 // https://dmoj.ca/problem/atimesb // https://dmoj.ca/problem/ccc96s2 // https://dmoj.ca/problem/ccc97s5 struct BigInt { using T = long long; static constexpr const int DIG = 4; static constexpr const T BASE = pow(10, DIG); vector<T> a; int sign; void trim() { while (!a.empty() && a.back() == 0) a.pop_back(); if (a.empty()) sign = 1; } void read(const string &s) { sign = 1; a.clear(); int pos = 0; for (; pos < int(s.size()) && (s[pos] == '-' || s[pos] == '+'); ++pos) if (s[pos] == '-') sign = -sign; for (int i = int(s.size()) - 1; i >= pos; i -= DIG) { T x = 0; for (int j = max(pos, i - DIG + 1); j <= i; j++) x = x * 10 + s[j] - '0'; a.push_back(x); } trim(); } friend istream& operator >> (istream &stream, BigInt &v) { string s; stream >> s; v.read(s); return stream; } string write() const { string ret = ""; if (sign == -1) ret.push_back('-'); for (char c : to_string(a.empty() ? 0 : a.back())) ret.push_back(c); for (int i = int(a.size()) - 2; i >= 0; i--) { string s = to_string(a[i]); for (int j = int(s.size()); j < DIG; j++) ret.push_back('0'); for (char c : s) ret.push_back(c); } return ret; } friend ostream& operator << (ostream &stream, const BigInt &v) { stream << v.write(); return stream; } bool operator < (const BigInt &v) const { if (sign != v.sign) return sign < v.sign; if (int(a.size()) != int(v.a.size())) return int(a.size()) * sign < int(v.a.size()) * v.sign; for (int i = int(a.size()) - 1; i >= 0; i--) if (a[i] != v.a[i]) return a[i] * sign < v.a[i] * sign; return false; } bool operator <= (const BigInt &v) const { return !(v < *this); } bool operator > (const BigInt &v) const { return v < *this; } bool operator >= (const BigInt &v) const { return !(*this < v); } bool operator == (const BigInt &v) const { return !(*this < v) && !(v < *this); } bool operator != (const BigInt &v) const { return *this < v || v < *this; } BigInt() : sign(1) {} BigInt(const string &s) { read(s); } BigInt(T v) : BigInt(to_string(v)) {} bool isZero() const { return a.empty() || (int(a.size()) == 1 && !a[0]); } BigInt operator + () const { return *this; } BigInt operator - () const { BigInt res = *this; res.sign = -sign; return res; } BigInt abs() const { BigInt res = *this; res.sign *= res.sign; return res; } T value() const { T res = 0; for (int i = int(a.size()) - 1; i >= 0; i--) res = res * BASE + a[i]; return res * sign; } BigInt operator ++ () { return *this += BigInt(1); } BigInt operator ++ (int) { BigInt ret = *this; *this += BigInt(1); return ret; } BigInt operator -- () { return *this -= BigInt(1); } BigInt operator -- (int) { BigInt ret = *this; *this -= BigInt(1); return ret; } BigInt operator + (const BigInt &v) const { if (sign == v.sign) { BigInt res = v; T carry = 0; for (int i = 0; i < max(int(a.size()), int(v.a.size())) || carry; i++) { if (i == int(res.a.size())) res.a.push_back(0); res.a[i] += carry + (i < int(a.size()) ? a[i] : 0); carry = res.a[i] >= BASE; if (carry) res.a[i] -= BASE; } return res; } return *this - (-v); } BigInt &operator += (const BigInt &v) { return *this = *this + v; } BigInt operator - (const BigInt &v) const { if (sign == v.sign) { if (abs() >= v.abs()) { BigInt res = *this; T carry = 0; for (int i = 0; i < int(v.a.size()) || carry; i++) { res.a[i] -= carry + (i < int(v.a.size()) ? v.a[i] : 0); carry = res.a[i] < 0; if (carry) res.a[i] += BASE; } res.trim(); return res; } return -(v - *this); } return *this + (-v); } BigInt &operator -= (const BigInt &v) { return *this = *this - v; } BigInt operator * (T v) const { BigInt res = *this; res *= v; return res; } BigInt &operator *= (T v) { if (v < 0) { sign = -sign; v = -v; } T carry = 0; for (int i = 0; i < int(a.size()) || carry; i++) { if (i == int(a.size())) a.push_back(0); T cur = a[i] * v + carry; carry = cur / BASE; a[i] = cur % BASE; } trim(); return *this; } BigInt operator * (const BigInt &v) const { BigInt res; res.a = mulIntFFT(a, v.a, BASE); res.sign = sign * v.sign; res.trim(); return res; } BigInt &operator *= (const BigInt &v) { return *this = *this * v; } friend pair<BigInt, BigInt> divmod(const BigInt &a1, const BigInt &b1) { T norm = BASE / (b1.a.back() + 1); BigInt a = a1.abs() * norm, b = b1.abs() * norm, q, r; q.a.resize(int(a.a.size())); for (int i = int(a.a.size()) - 1; i >= 0; i--) { r *= BASE; r += a.a[i]; T s1 = int(r.a.size()) <= int(b.a.size()) ? 0 : r.a[int(b.a.size())]; T s2 = int(r.a.size()) <= int(b.a.size()) - 1 ? 0 : r.a[int(b.a.size()) - 1]; T d = (BASE * s1 + s2) / b.a.back(); r -= b * d; for (; r < 0; r += b) --d; q.a[i] = d; } q.sign = a1.sign * b1.sign; r.sign = a1.sign; q.trim(); r.trim(); return make_pair(q, r / norm); } BigInt operator / (T v) const { BigInt res = *this; res /= v; return res; } BigInt &operator /= (T v) { if (v < 0) { sign = -sign; v = -v; } for (int i = int(a.size()) - 1, rem = 0; i >= 0; i--) { T cur = a[i] + rem * BASE; a[i] = cur / v; rem = cur % v; } trim(); return *this; } T operator % (T v) const { if (v < 0) v = -v; T m = 0; for (int i = int(a.size()) - 1; i >= 0; i--) m = (a[i] + m * BASE) % v; return m * sign; } BigInt operator / (const BigInt &v) const { return divmod(*this, v).first; } BigInt operator % (const BigInt &v) const { return divmod(*this, v).second; } BigInt &operator /= (const BigInt &v) { return *this = *this / v; } BigInt &operator %= (const BigInt &v) { return *this = *this % v; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Type templated greatest common divisor function // Always returns a non negative integer // Template Arguments: // T: the type of a and b // Function Arguments: // a: the first value // b: the second value // Return Value: the greatest common divisor of a and b // In practice, has a small constant // Time Complexity: O(log(min(a, b))) // Memory Complexity: O(1) // Tested: // https://hackerrank.com/contests/projecteuler/challenges/euler005/problem template <class T> T gcd(T a, T b) { return b == 0 ? (a >= 0 ? a : -a) : gcd(b, a % b); } // Type templated lowest common multiple function // Always returns a non negative integer // Template Arguments: // T: the type of a and b // Function Arguments: // a: the first value // b: the second value // Return Value: the lowest common multiple of a and b // In practice, has a small constant // Time Complexity: O(log(min(a, b))) // Memory Complexity: O(1) // Tested: // https://hackerrank.com/contests/projecteuler/challenges/euler005/problem template <class T> T lcm(T a, T b) { if (a == 0 || b == 0) return 0; if (a < 0) a = -a; if (b < 0) b = -b; return a / gcd(a, b) * b; } // Extended Euclidean Algorithm to compute x and y, where ax + by = gcd(a, b) // Template Arguments: // T: the type of a and b // Function Arguments: // a: the first value // b: the second value // x: a reference to a variable to store x // y: a reference to a variable to store y // Return Value: the greatest common divisor of a and b // In practice, has a small constant // Time Complexity: O(log(min(a, b))) // Memory Complexity: O(1) // Tested: // https://dmoj.ca/problem/modinv // https://www.spoj.com/problems/CEQU/ // https://codeforces.com/problemsets/acmsguru/problem/99999/106 template <class T> T EEA(T a, T b, T &x, T &y) { T xx = y = 0, yy = x = 1; while (b != 0) { T q = a / b; a %= b; swap(a, b); x -= q * xx; swap(x, xx); y -= q * yy; swap(y, yy); } if (a < 0) { a = -a; x = -x; y = -y; } return a; } // Computes the multiplicative inverse of a in Zm // Inverse only exists if gcd(a, m) == 1 // Template Arguments: // T: the type of a and m // Function Arguments: // a: the value to find the inverse of, must be in the range [0, m) // m: the mod, must be positive // Return Value: the multiplicative inverse of a in Zm, -1 if no inverse // In practice, has a small constant // Time Complexity: O(log m) // Memory Complexity: O(1) // Tested: // https://dmoj.ca/problem/modinv template <class T> T mulInv(T a, T m) { if (a == 0) return -1; T x, y; if (EEA(a, m, x, y) != 1) return -1; x %= m; return x < 0 ? x + m : x; } // Solves the linear congruence ax = c mod m // Template Arguments: // T: the type of a, c, and m // Function Arguments: // a: must be in the range [0, m) // c: must be in the range [0, m) // m: the mod, must be positive // Return Value: a pair containing x, and the modulus of the answer (equal to // m / gcd(a, m)), x is -1 if there is no solution // In practice, has a small constant // Time Complexity: O(log m) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> pair<T, T> solveCongruence(T a, T c, T m) { T x, y, g = EEA(a, m, x, y); if (c % g != 0) return make_pair(-1, m / g); x = (x % m + m) % m; x = (x * c / g) % (m / g); return make_pair(x, m / g); } // Solves the Linear Diophantine Equation ax + by = c // All pairs of integers (s, t) where s = x.first + k * x.second // and t = y.first + k * y.second for all integers k are solutions // Edge cases: // 1. a == 0 && b == 0 is satisfied by all integer pairs (s, t) if c == 0, // no solutions otherwise // 2. a == 0 is satisfied by all integer pairs (s, t) with t = c / b if c is // divisible by b, no solutions otherwise // 3. b == 0 is satisfied by all integer pairs (s, t) with s = c / a if c is // divisible by a, no solutions otherwise // Template Arguments: // T: the type of a, b, c // Function Arguments: // a: the first value // b: the second value // c: the value of ax + by // x: a reference to a pair storing x and its mod (equal to b / gcd(a, b)) // y: a reference to a pair storing y and its mod (equal to -a / gcd(a, b)) // Return Value: true if there is a solution, false otherwise // In practice, has a small constant // Time Complexity: O(log(min(a, b))) // Memory Complexity: O(1) // Tested: // https://www.spoj.com/problems/CEQU/ // https://codeforces.com/problemsets/acmsguru/problem/99999/106 template <class T> bool LDE(T a, T b, T c, pair<T, T> &x, pair<T, T> &y) { assert(a != 0 && b != 0); T xg, yg, g = EEA(a, b, xg, yg); if (c % g != 0) return false; x = make_pair(xg * (c / g), b / g); y = make_pair(yg * (c / g), -a / g); return true; } // Generalized Chinese Remainder Theorem to find the solution to // x mod lcm(a.second, b.second) given x = a.first mod a.second // and x = b.first mod b.second // Template Arguments: // T: the type of x // Function Arguments: // a: the first value and its associated mod (0 <= a.first < a.second) // b: the second value and its associated mod (0 <= b.first < b.second) // Return Value: the pair x and lcm(a.second, b.second) where // 0 <= x < lcm(a.second, b.second), x is -1 if there is no solution // In practice, has a small constant // Time Complexity: O(log(min(a.second, b.second))) // Memory Complexity: O(1) // Tested: // https://open.kattis.com/problems/generalchineseremainder template <class T> pair<T, T> CRT(pair<T, T> a, pair<T, T> b) { T g = gcd(a.second, b.second), l = a.second / g * b.second; if ((b.first - a.first) % g != 0) return make_pair(-1, l); T A = a.second / g, B = b.second / g; T mul = (b.first - a.first) / g * mulInv(A % B, B) % B; return make_pair(((mul * a.second + a.first) % l + l) % l, l); }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "BinaryExponentiation.h" using namespace std; // Struct representing integers modulo MOD where MOD can change during runtime // Template Arguments: // T: the type of the integer, must be integral // Constructor Arguments: // x: the value to initialize the struct with // Fields: // static MOD: the value to mod by, must be non negative // static PRIME_MOD: a boolean indicating whether MOD is prime // static MUL_OVERFLOW: a boolean indicating whether MOD * MOD overflows // v: the value // Functions: // statis setMod(mod, primeMod, mulOverflow): sets the mod to MOD, with // primeMod indicating whether the mod is prime and mulOverflow indicating // whether multiplication overflows // <, <=, >, >=, ==, !=: comparison operators // ++, --, +, +=, -, -=, *, *=: standard arithmetic operators modulo MOD // pow(p): returns this value raises this to the power of p // hasMulInv(): returns whether a multiplicative inverse of this value exists // mulInv(): returns the multiplicative inverse of this value, only exists // if gcd(v, MOD) is 1 // /, /=: division in modular arithmetic, only valid if a multiplicative // inverse of the divisor exists // >>, <<: input and output operators // Time Complexity: // constructor: O(1) // setMod: O(1) // <, <=, >, >=, ==, !=, ++, --, +, +=, -, -=, >>, <<: O(1) // *, *=: O(1) if MUL_OVERFLOW is false, O(log MOD) otherwise // pow: O(log MOD) if MUL_OVERFLOW is false, O((log MOD)^2) otherwise // hasMulInv, mulInv, /, /=: O(log MOD) // Memory Complexity: O(1) // Tested: // https://open.kattis.com/problems/modulararithmetic template <class T> struct DynamicIntMod { static_assert(is_integral<T>::value, "T must be an integral type"); static_assert(is_signed<T>::value, "T must be a signed type"); using IM = DynamicIntMod<T>; static T MOD; static bool PRIME_MOD, MUL_OVERFLOW; static void setMod(T mod, bool primeMod = false, bool mulOverflow = false) { MOD = mod; PRIME_MOD = primeMod; MUL_OVERFLOW = mulOverflow; } T v; DynamicIntMod() : v(0) {} DynamicIntMod(const T &x) { v = -MOD < x && x < MOD ? x : x % MOD; if (v < 0) v += MOD; } bool operator < (const IM &i) const { return v < i.v; } bool operator <= (const IM &i) const { return v <= i.v; } bool operator > (const IM &i) const { return v > i.v; } bool operator >= (const IM &i) const { return v >= i.v; } bool operator == (const IM &i) const { return v == i.v; } bool operator != (const IM &i) const { return v != i.v; } IM operator ++ () { if (++v == MOD) v = 0; return *this; } IM operator ++ (int) { IM ret = *this; if (++v == MOD) v = 0; return ret; } IM operator -- () { if (v-- == 0) v = MOD - 1; return *this; } IM operator -- (int) { IM ret = *this; if (v-- == 0) v = MOD - 1; return ret; } IM operator + (const IM &i) const { return IM(*this) += i; } IM &operator += (const IM &i) { if ((v += i.v) >= MOD) v -= MOD; return *this; } IM operator - (const IM &i) const { return IM(*this) -= i; } IM &operator -= (const IM &i) { if ((v -= i.v) < 0) v += MOD; return *this; } IM operator + () const { return *this; } IM operator - () const { return IM(-v); } IM operator * (const IM &i) const { return IM(*this) *= i; } IM &operator *= (const IM &i) { if (MUL_OVERFLOW) { IM x = 0, y = *this; T z = i.v; for (; z > 0; z /= 2, y += y) if (z % 2 == 1) x += y; *this = x; } else v = v * i.v % MOD; return *this; } bool hasMulInv() const { if (v == 0) return false; if (!PRIME_MOD || MUL_OVERFLOW) { T g = MOD, r = v; while (r != 0) { g %= r; swap(g, r); } return g == 1; } else return true; } IM mulInv() const { assert(v != 0); if (!PRIME_MOD || MUL_OVERFLOW) { T g = MOD, r = v, x = 0, y = 1; while (r != 0) { T q = g / r; g %= r; swap(g, r); x -= q * y; swap(x, y); } assert(g == 1); return IM(x); } else return pow2(*this, MOD - 2); } IM operator / (const IM &i) const { return IM(*this) /= i; } IM &operator /= (const IM &i) { return *this *= i.mulInv(); } friend istream &operator >> (istream &stream, IM &i) { T v; stream >> v; i = IM(v); return stream; } friend ostream &operator << (ostream &stream, const IM &i) { return stream << i.v; } }; template <class T> T DynamicIntMod<T>::MOD = T(1); template <class T> bool DynamicIntMod<T>::PRIME_MOD = false; template <class T> bool DynamicIntMod<T>::MUL_OVERFLOW = false;
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes the Kth term of a linear recurrence of length N // A[i] = sum (C[j] * A[i - 1 - j]) for 0 <= j < N // Template Arguments: // T: the type of the elements in the sequence // U: the type of K // Function Arguments: // A: a vector of the first N terms of the sequence // C: a vector of the the N recurrence coefficients of the sequence // K: the term of the sequence to find // Return Value: the Kth term (0-indexed) of the linear recurrence // Time Complexity: O(N^2 log K) // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/ddrp6 template <class T, class U> T linearRecurrence(const vector<T> &A, const vector<T> &C, U K) { assert(A.size() == C.size()); int N = A.size(); if (K < N) return A[K]; auto comb = [&] (const vector<T> &a, const vector<T> &b) { vector<T> res(N * 2 + 1, T()); for (int i = 0; i <= N; i++) for (int j = 0; j <= N; j++) res[i + j] += a[i] * b[j]; for (int i = N * 2; i > N; i--) for (int j = 0; j < N; j++) res[i - 1 - j] += res[i] * C[j]; return res; }; vector<T> P(N + 1, T()), E = P; P[0] = E[1] = T(1); K++; while (true) { if (K % 2 == 1) P = comb(P, E); if ((K /= 2) == 0) break; E = comb(E, E); } T res = T(); for (int i = 0; i < N; i++) res += P[i + 1] * A[i]; return res; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Adds two nimbers a and b // Template Arguments: // T: the type of a, b, must be an unsigned integral type // Function Arguments: // a: the first value // b: the second value // Return Value: a + b with nimber addition // In practice, has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // https://judge.yosupo.jp/problem/nim_product_64 template <class T> T addNim(T a, T b) { static_assert(is_unsigned<T>::value, "T must be an unsigned integral type"); return a ^ b; } // Helper function to initialize the product cache array template <class T, const int BITS> T initNim(T prod[BITS][BITS]) { for (int i = 0; i < BITS; i++) fill(prod[i], prod[i] + BITS, T()); return T(); } // Helper function to multiply 2^i and 2^j template <class T, const int BITS> T mulNimPow2(T prod[BITS][BITS], int i, int j) { static_assert(is_unsigned<T>::value, "T must be an unsigned integral type"); T &res = prod[i][j]; if (res) return res; if (!(i & j)) return res = T(1) << (i | j); int a = (i & j) & -(i & j); return res = mulNimPow2(prod, i ^ a, j) ^ mulNimPow2(prod, (i ^ a) | (a - 1), (j ^ a) | (i & (a - 1))); } // Multiplies two nimbers a and b // Template Arguments: // T: the type of a, b, must be an unsigned integral type // Function Arguments: // a: the first value // b: the second value // Return Value: a * b with nimber multiplication // In practice, has a very small constant // Time Complexity: O(BITS^2) // Memory Complexity: O(1) // Tested: // https://judge.yosupo.jp/problem/nim_product_64 template <class T> T mulNim(T a, T b) { static_assert(is_unsigned<T>::value, "T must be an unsigned integral type"); static constexpr const int BITS = 8 * sizeof(T); static T prod[BITS][BITS]; static T ZERO = initNim(prod); T res = ZERO; for (int i = 0; i < BITS; i++) if ((a >> i) & 1) for (int j = 0; j < BITS; j++) if ((b >> j) & 1) res = addNim(res, mulNimPow2(prod, i, j)); return res; } // Computes base to the power pow in nimber arithmetic // Template Arguments: // T: the type of base, must be an unsigned integral type // U: the type of pow // Function Arguments: // base: the base // pow: the power, must be non negative and integral // Return Value: base to the power pow in nimber arithmetic // In practice, has a very small constant // Time Complexity: O(BITS^2 log pow) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T, class U> T powNim(T base, U pow) { static_assert(is_unsigned<T>::value, "T must be an unsigned integral type"); T x = 1; while (true) { if (pow % 2 == 1) x = mulNim(x, base); if ((pow /= 2) == 0) break; base = mulNim(base, base); } return x; } // Computes the multiplicative inverse of a in nimber arithmetic // Guaranteed to exist // Template Arguments: // T: the type of a, must be an unsigned integral type // Function Arguments: // a: the value to find the inverse of // Return Value: the multiplicative inverse of a in nimber arithmetic // In practice, has a small constant // Time Complexity: O(BITS^3) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> T mulInvNim(T a) { static_assert(is_unsigned<T>::value, "T must be an unsigned integral type"); return powNim(a, T(-2)); }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Helper functions template <class F, class T> T S(F &f, T a, T b) { return (f(a) + 4 * f((a + b) / 2) + f(b)) * (b - a) / 6; } template <class F, class T> T rec(F &f, T a, T b, T eps, T s) { T c = (a + b) / 2, S1 = S(f, a, c), S2 = S(f, c, b), SS = S1 + S2; if (abs(SS - s) <= 15 * eps || b - a < 1e-10) return SS + (SS - s) / 15; return rec(f, a, c, eps / 2, S1) + rec(f, c, b, eps / 2, S2); } // Integrates the function f over the range [a, b] // Template Arguments: // F: the type of f // T: the type of the bounds and the return value of the function f // Function Arguments: // a: the lower bound // b: the upper bound // f(x): the function returning the y value at x // eps: a value for epsilon // Return Value: the integral of f over the range [a, b] // Time Complexity: O(b - a) * (cost to compute f(x)) // Memory Complexity: O(1) // Tested: // https://codeforces.com/problemsets/acmsguru/problem/99999/217 template <class F, class T> T integrate(F f, T a, T b, T eps) { return rec(f, a, b, eps, S(f, a, b)); }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Given a sequence A of length N, compute a sequence C of minimum length M, // such that A[i] = sum (C[j] * A[i - 1 - j]) for 0 <= j < M // Template Arguments: // T: the type of the elements in the sequence // Function Arguments: // A: the sequence to find the recurrence // Return Value: the shortest vector C of length M, representing the // recurrence coefficients // Time Complexity: O(N^2) // Memory Complexity: O(N) // Tested: // https://judge.yosupo.jp/problem/find_linear_recurrence // https://dmoj.ca/problem/ddrp6 template <class T> vector<T> berlekampMassey(const vector<T> &A) { if (A.empty()) return vector<T>(); int N = A.size(), L = 0; vector<T> C(N, T()), B = C, tmp; T b = C[0] = B[0] = T(1); for (int i = 0, m = 1; i < N; i++, m++) { T d = A[i]; for (int j = 1; j <= L; j++) d += C[j] * A[i - j]; if (d == T()) continue; tmp = C; T c = d / b; for (int j = m; j < N; j++) C[j] -= c * B[j - m]; if (2 * L > i) continue; L = i + 1 - L; B = tmp; b = d; m = 0; } C.resize(L + 1); C.erase(C.begin()); for (auto &&c : C) c = -c; return C; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../datastructures/unionfind/UnionFindUndo.h" using namespace std; // Graphic Matroid for spanning forests // Constructor Arguments: // V: the number of vertices in the simple graph // edges: a vector of pairs in the form (v, w) representing // an undirected edge in the graph between vertices v and w // Functions: // clear(): clears all edges in the independent set // add(i): adds the ith edge to the independent set // independent(i): returns whether adding edge i to the current // existing independent set would still result in an independent set // In practice, has a small constant // Time Complexity: // constructor: O(V + E) // clear: O(K) for K edges added // add, independent: O(log V) // Memory Complexity: O(V + E) // Tested: // https://www.spoj.com/problems/COIN/ struct GraphicMatroid { int V; UnionFindUndo uf; vector<pair<int, int>> edges; GraphicMatroid(int V, const vector<pair<int, int>> &edges) : V(V), uf(V), edges(edges) {} void clear() { while (!uf.history.empty()) uf.undo(); } void add(int i) { uf.join(edges[i].first, edges[i].second); } bool independent(int i) { return !uf.connected(edges[i].first, edges[i].second); } }; // Colorful Matroid // Constructor Arguments: // color: the colors of each element in the ground set // Functions: // clear(): clears all elements in the independent set // add(i): adds the ith element to the independent set // independent(i): returns whether adding element i to the current // existing independent set would still result in an independent set // In practice, has a small constant // Time Complexity: // constructor: O(N) for N elements in the ground set // clear: O(C) for C colors // add, independent: O(1) // Memory Complexity: O(N + C) for N elements in the ground set and C colors // Tested: // https://codeforces.com/gym/102156/problem/D // https://www.spoj.com/problems/COIN/ struct ColorfulMatroid { vector<bool> in; vector<int> color; ColorfulMatroid(const vector<int> &color) : in(*max_element(color.begin(), color.end()) + 1, false), color(color) {} void clear() { fill(in.begin(), in.end(), false); } void add(int i) { in[color[i]] = true; } bool independent(int i) { return !in[color[i]]; } }; // Matroid for vectors in Z2 // Template Arguments: // BITS: the number of bits // Constructor Arguments: // vec: the vectors in the ground set // Functions: // clear(): clears all vector in the independent set // add(i): adds the ith vector to the independent set // independent(i): returns whether adding vector i to the current // existing independent set would still result in an independent set // In practice, has a very small constant // Time Complexity: // constructor: O(N BITS) for N vectors in the ground set // clear: O(BITS) // add, independent: O(BITS^2 / 64) // Memory Complexity: O(N BITS) for N vectors in the ground set // Tested: // https://codeforces.com/gym/102156/problem/D template <const int BITS> struct Z2Matroid { vector<bitset<BITS>> basis, vec; Z2Matroid(const vector<bitset<BITS>> &vec) : basis(BITS), vec(vec) {} void clear() { fill(basis.begin(), basis.end(), bitset<BITS>()); } void add(int i) { bitset<BITS> v = vec[i]; for (int j = 0; j < BITS; j++) if (v[j]) { if (basis[j].none()) { basis[j] = v; return; } v ^= basis[j]; } } bool independent(int i) { bitset<BITS> v = vec[i]; for (int j = 0; j < BITS; j++) if (v[j]) { if (basis[j].none()) return true; v ^= basis[j]; } return false; } }; // Linear Matroid for vectors // Template Arguments: // T: the type of each element // Constructor Arguments: // vec: the vectors in the ground set // EPS: a value for epsilon // Functions: // clear(): clears all vector in the independent set // add(i): adds the ith vector to the independent set // independent(i): returns whether adding vector i to the current // existing independent set would still result in an independent set // In practice, has a small constant // Time Complexity: // constructor: O(NV) for N vectors of size V in the ground set // clear: O(V) for vectors of size V // add, independent: O(V^2) for vectors of size V // Memory Complexity: O(NV) for N vectors of size V in the ground set template <class T> struct LinearMatroid { static T abs(T a) { return a >= 0 ? a : -a; } int vars; T EPS; vector<vector<T>> basis, vec; LinearMatroid(const vector<vector<T>> &vec, T EPS = T(1e-9)) : vars(vec.empty() ? 0 : vec[0].size()), EPS(EPS), basis(vars), vec(vec) {} void clear() { fill(basis.begin(), basis.end(), vector<T>()); } void add(int i) { vector<T> v = vec[i]; for (int j = 0; j < vars; j++) if (abs(v[j]) > EPS) { if (basis[j].empty()) { basis[j] = v; return; } T alpha = v[j] / basis[j][j]; for (int k = j; k < vars; k++) v[j] -= alpha * basis[j][k]; } } bool independent(int i) { vector<T> v = vec[i]; for (int j = 0; j < vars; j++) if (abs(v[j]) > EPS) { if (basis[j].empty()) return true; T alpha = v[j] / basis[j][j]; for (int k = j; k < vars; k++) v[j] -= alpha * basis[j][k]; } return false; } }; // Find the largest subset of a ground set of N elements that is // independent in both matroids // A matroid must have the basic properties of: // - the empty set is independent // - any subset of an independent set is empty // - if independent set A is smaller than independent set B, then there is // at least 1 element of B can be added to A without loss of independency // Elements are 0-indexed // Template Arguments: // Matroid1: the type of the first matroid // Required Functions: // clear(): clears all elements in the independent set of this matroid // add(i): adds element i to the independent set of this matroid // independent(i): returns whether adding element i to the current // existing independent set would still result in an independent set // Matroid2: the type of the second matroid // Required Functions: same as Matroid1 // Constructor Arguments: // N: the number of elements in the ground set // m1: an instance of the first matroid // m2: an instance of the second matroid // Fields: // N: the number of elements in the ground set // inSet: a vector of booleans indicating whether each element is in the // largest independent set or not // independentSet: a vector of the indices of the elements in the largest // independent set // In practice, has a very small constant // Time Complexity: // constructor: O(NI sqrt I) * (time complexity of m1.add, m2.add, // m1.independent, and m2.independent) where I is the size of the largest // independent set // Memory Complexity: O(N + M1 + M2) where M1 and M2 are the memory // complexities of m1 and m2 // Tested: // https://codeforces.com/gym/102156/problem/D // https://www.spoj.com/problems/COIN/ template <class Matroid1, class Matroid2> struct MatroidIntersection { int N; vector<bool> inSet; vector<int> independentSet; bool augment(Matroid1 &m1, Matroid2 &m2) { vector<int> par(N + 1, -1); queue<int> q; q.push(N); while (!q.empty()) { int v = q.front(); q.pop(); if (inSet[v]) { m1.clear(); for (int i = 0; i < N; i++) if (inSet[i] && i != v) m1.add(i); for (int i = 0; i < N; i++) if (!inSet[i] && par[i] == -1 && m1.independent(i)) { par[i] = v; q.push(i); } } else { auto backE = [&] { m2.clear(); for (int c = 0; c < 2; c++) for (int i = 0; i < N; i++) if ((v == i || inSet[i]) && (par[i] == -1) == c) { if (!m2.independent(i)) { if (c) { par[i] = v; q.push(i); return i; } else return -1; } m2.add(i); } return N; }; for (int w = backE(); w != -1; w = backE()) if (w == N) { for (; v != N; v = par[v]) inSet[v] = !inSet[v]; return true; } } } return false; } MatroidIntersection(int N, Matroid1 m1, Matroid2 m2) : N(N), inSet(N + 1, false) { m1.clear(); m2.clear(); inSet[N] = true; for (int i = N - 1; i >= 0; i--) if (m1.independent(i) && m2.independent(i)) { inSet[i] = true; m1.add(i); m2.add(i); } while (augment(m1, m2)); inSet.pop_back(); for (int i = 0; i < N; i++) if (inSet[i]) independentSet.push_back(i); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "BinaryExponentiation.h" #include "Primes.h" using namespace std; // Struct representing integers modulo MOD // Template Arguments: // T: the type of the integer, must be integral // MOD: the value to mod by, must be non negative // PRIME_MOD: a boolean indicating whether MOD is prime, can be computed // automatically if C++ 14 or above, and if MOD is small // MUL_OVERFLOW: a boolean indicating whether MOD * MOD overflows, can be // computed automatically if numeric_limits<T>::max() exists // Constructor Arguments: // x: the value to initialize the struct with // Fields: // v: the value // Functions: // <, <=, >, >=, ==, !=: comparison operators // ++, --, +, +=, -, -=, *, *=: standard arithmetic operators modulo MOD // pow(p): returns this value raises this to the power of p // hasMulInv(): returns whether a multiplicative inverse of this value exists // mulInv(): returns the multiplicative inverse of this value, only exists // if gcd(v, MOD) is 1 // /, /=: division in modular arithmetic, only valid if a multiplicative // inverse of the divisor exists // >>, <<: input and output operators // Time Complexity: // constructor: O(1) // <, <=, >, >=, ==, !=, ++, --, +, +=, -, -=, >>, <<: O(1) // *, *=: O(1) if MUL_OVERFLOW is false, O(log MOD) otherwise // pow: O(log MOD) if MUL_OVERFLOW is false, O((log MOD)^2) otherwise // hasMulInv, mulInv, /, /=: O(log MOD) // Memory Complexity: O(1) // Tested: // https://dmoj.ca/problem/angieandfunctions template <class T, const T MOD, #if __cplusplus < 201402L const bool PRIME_MOD, #else const bool PRIME_MOD = isPrime(MOD), #endif const bool MUL_OVERFLOW = (numeric_limits<T>::max() / MOD < MOD)> struct IntMod { static_assert(is_integral<T>::value, "T must be an integral type"); static_assert(is_signed<T>::value, "T must be a signed type"); static_assert(0 < MOD, "MOD must be a positive integer"); using IM = IntMod<T, MOD, PRIME_MOD, MUL_OVERFLOW>; T v; IntMod() : v(0) {} IntMod(const T &x) { v = -MOD < x && x < MOD ? x : x % MOD; if (v < 0) v += MOD; } bool operator < (const IM &i) const { return v < i.v; } bool operator <= (const IM &i) const { return v <= i.v; } bool operator > (const IM &i) const { return v > i.v; } bool operator >= (const IM &i) const { return v >= i.v; } bool operator == (const IM &i) const { return v == i.v; } bool operator != (const IM &i) const { return v != i.v; } IM operator ++ () { if (++v == MOD) v = 0; return *this; } IM operator ++ (int) { IM ret = *this; if (++v == MOD) v = 0; return ret; } IM operator -- () { if (v-- == 0) v = MOD - 1; return *this; } IM operator -- (int) { IM ret = *this; if (v-- == 0) v = MOD - 1; return ret; } IM operator + (const IM &i) const { return IM(*this) += i; } IM &operator += (const IM &i) { if ((v += i.v) >= MOD) v -= MOD; return *this; } IM operator - (const IM &i) const { return IM(*this) -= i; } IM &operator -= (const IM &i) { if ((v -= i.v) < 0) v += MOD; return *this; } IM operator + () const { return *this; } IM operator - () const { return IM(-v); } IM operator * (const IM &i) const { return IM(*this) *= i; } IM &operator *= (const IM &i) { if (MUL_OVERFLOW) { IM x = 0, y = *this; T z = i.v; for (; z > 0; z /= 2, y += y) if (z % 2 == 1) x += y; *this = x; } else v = v * i.v % MOD; return *this; } bool hasMulInv() const { if (v == 0) return false; if (!PRIME_MOD || MUL_OVERFLOW) { T g = MOD, r = v; while (r != 0) { g %= r; swap(g, r); } return g == 1; } else return true; } IM mulInv() const { if (!PRIME_MOD || MUL_OVERFLOW) { T g = MOD, r = v, x = 0, y = 1; while (r != 0) { T q = g / r; g %= r; swap(g, r); x -= q * y; swap(x, y); } assert(g == 1); return IM(x); } else return pow2(*this, MOD - 2); } IM operator / (const IM &i) const { return IM(*this) /= i; } IM &operator /= (const IM &i) { return *this *= i.mulInv(); } friend istream &operator >> (istream &stream, IM &i) { T v; stream >> v; i = IM(v); return stream; } friend ostream &operator << (ostream &stream, const IM &i) { return stream << i.v; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Finds a candidate for the majority element with constant space // A second pass is required to ensure the candidate is actually a // majority element // Template Arguments: // F: the type of the function generating the elements // Function Arguments: // N: the number of elements // f: a function that returns the ith element on the ith call // Return Value: returns an element that is a candidate for the // majority element // In practice, has a very small constant // Time Complexity: O(N) // Memory Complexity: O(1) // Tested: // https://open.kattis.com/problems/farmingmars template <class F> auto boyerMooreMajority(int N, F f) -> typename decay<decltype(f())>::type { typename decay<decltype(f())>::type ret = f(); for (int cnt = 1, i = 1; i < N; i++) { auto v = f(); if (cnt == 0) { ret = v; cnt++; } else if (v == ret) cnt++; else cnt--; } return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "ModularArithmetic.h" #include "Primes.h" using namespace std; // Helper function to find a primitive root for the mod p template <class T> T primitiveRoot(T p) { T phi = p - 1, n = phi; vector<T> pf; for (T i = 2; i * i <= n; i++) { if (n % i == 0) pf.push_back(i); while (n % i == 0) n /= i; } for (T res = 2; res <= p; res++) { bool ok = true; for (int i = 0; i < int(pf.size()) && ok; i++) ok &= powMod(res, phi / pf[i], p) != 1; if (ok) return res; } return -1; } // Number Theoretic Transform // Template Arguments: // T: the type of the integer, must be integral // MOD: the value to mod by, must be in the form C * 2^K + 1 for some // integers C, K where size(a) <= 2^K // Sample Mods: // 998244353 = 119 * 2^23 + 1, primitiveRoot = 3 // 754974721 = 45 * 2^24 + 1, primitiveRoot = 11 // 167772161 = 5 * 2^25 + 1, primitiveRoot = 3 // 469762049 = 7 * 2^26 + 1, primitiveRoot = 3 // 1004535809 = 479 * 2^21 + 1, primitiveRoot = 3 // 1012924417 = 483 * 2^21 + 1, primitiveRoot = 5 // Function Arguments: // a: a reference to the vector of type T in the range [0, MOD) // In practice, has a moderate constant, faster than FFT and Karatsuba // Time Complexity: O(N log N) where N = size(a) // Memory Complexity: O(N) // Tested: // https://judge.yosupo.jp/problem/convolution_mod // https://judge.yosupo.jp/problem/convolution_mod_1000000007 template <class T, const T MOD> void ntt(vector<T> &a) { static_assert(is_integral<T>::value, "T must be an integral type"); static_assert(is_signed<T>::value, "T must be a signed type"); #if __cplusplus >= 201402L static_assert(isPrime(MOD), "MOD must be prime"); #endif static T pk = 1, PK = 0; for (; pk < MOD; pk *= 2) if ((MOD - 1) % pk == 0) PK = pk; assert(PK != 0 && "MOD must be of the form C * 2^K + 1"); static T ROOT = powMod(primitiveRoot(MOD), (MOD - 1) / PK, MOD); static vector<T> rt(2, 1); static vector<int> ord; static int k = 2, len = 1; int N = a.size(); assert(N <= PK); assert(!(N & (N - 1))); for (; k < N; k <<= 1, len++) { rt.resize(N, T()); T x = powMod(ROOT, PK >> (len + 1), MOD); for (int i = k; i < (k << 1); i++) rt[i] = i & 1 ? mulMod(rt[i >> 1], x, MOD) : rt[i >> 1]; } if (int(ord.size()) != N) { ord.assign(N, 0); int len = __builtin_ctz(N); for (int i = 0; i < N; i++) ord[i] = (ord[i >> 1] >> 1) + ((i & 1) << (len - 1)); } for (int i = 0; i < N; i++) if (i < ord[i]) swap(a[i], a[ord[i]]); for (int len = 1; len < N; len <<= 1) for (int i = 0; i < N; i += len << 1) for (int j = 0; j < len; j++) { T u = a[i + j], v = mulMod(a[len + i + j], rt[len + j], MOD); a[i + j] = addMod(u, v, MOD); a[len + i + j] = subMod(u, v, MOD); } } // Polynomial Multiplication // Template Arguments: // T: the type of the integer, must be integral // MOD: the value to mod by, must be in the form C * 2^K + 1 for some // integers C, K where size(a) + size(b) - 1 <= 2^K // Functions Arguments: // a: a vector of type T representing the first polynomial, a[i] stores // the coefficient of x^i, must be in the range [0, MOD) // b: a vector of type T representing the second polynomial, b[i] stores // the coefficient of x^i, must be in the range [0, MOD) // eq: a boolean indicating whether a and b are equal (to reduce the number // of ntt calls) // Return Value: a vector of type T representing the polynomial a times b with // no trailing zeros, all value in the range [0, MOD) // In practice, has a moderate constant // Time Complexity: O(N log N) where N = size(a) + size(b) // Memory Complexity: O(N) // Tested: // https://judge.yosupo.jp/problem/convolution_mod // https://judge.yosupo.jp/problem/convolution_mod_1000000007 const int NTT_CUTOFF = 30000; template <class T, const T MOD> vector<T> mulPolyNTT(const vector<T> &a, const vector<T> &b, bool eq = false) { int N = max(0, int(a.size()) + int(b.size()) - 1); if ((long long)(a.size()) * (long long)(b.size()) <= NTT_CUTOFF) { vector<T> res(N, T()); for (int i = 0; i < int(a.size()); i++) for (int j = 0; j < int(b.size()); j++) res[i + j] = addMod(res[i + j], mulMod(a[i], b[j], MOD), MOD); while (int(res.size()) > 1 && res.back() == T()) res.pop_back(); return res; } while (N & (N - 1)) N++; vector<T> fa(N, T()), fb, res(N, T()); copy(a.begin(), a.end(), fa.begin()); ntt<T, MOD>(fa); if (eq) fb = fa; else { fb.assign(N, T()); copy(b.begin(), b.end(), fb.begin()); ntt<T, MOD>(fb); } T invN = mulInvModPrime(T(N), MOD); res[0] = mulMod(mulMod(fa[0], fb[0], MOD), invN, MOD); for (int i = 1; i < N; i++) res[N - i] = mulMod(mulMod(fa[i], fb[i], MOD), invN, MOD); ntt<T, MOD>(res); while (int(res.size()) > 1 && res.back() == T()) res.pop_back(); return res; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "ModularArithmetic.h" #include "GCD.h" #include "../utils/Random.h" using namespace std; // constexpr function (in C++14 and above) to determine if x is prime // Template Arguments: // T: the type of x // Function Arguments: // x: the value to check if prime // Return Value: true if x is prime, false otherwise // In practice, has a small constant // Time Complexity: O(sqrt x) // Memory Complexity: O(1) // Tested: // https://www.spoj.com/SHORTEN/problems/ISPRIME/ // https://dmoj.ca/problem/angieandfunctions template <class T> constexpr bool isPrime(T x) { if (x < 2) return false; for (T i = 2; i * i <= x; i++) if (x % i == 0) return false; return true; } // Finds the prime factors of x // Template Arguments: // T: the type of x // Function Arguments: // x: the value to prime factor // Return Value: a sorted vector of T with the prime factorization of x // In practice, has a small constant // Time Complexity: O(sqrt x) // Memory Complexity: O(log x) // Tested: // https://www.spoj.com/problems/FACT0/ template <class T> vector<T> primeFactor(T x) { vector<T> ret; for (T i = 2; i * i <= x; i++) while (x % i == 0) { ret.push_back(i); x /= i; } if (x > 1) ret.push_back(x); return ret; } // Finds the prime factors of x and its exponent // Template Arguments: // T: the type of x // Function Arguments: // x: the value to prime factor // Return Value: a sorted vector of pairs of T and int with each // prime factor of x and its exponent // In practice, has a small constant // Time Complexity: O(sqrt x) // Memory Complexity: O(log x) // Tested: // https://www.spoj.com/problems/FACT0/ template <class T> vector<pair<T, int>> primeFactorWithCount(T x) { vector<pair<T, int>> ret; for (T i = 2; i * i <= x; i++) if (x % i == 0) for (ret.emplace_back(i, 0); x % i == 0; x /= i) ret.back().second++; if (x > 1) ret.emplace_back(x, 1); return ret; } // Computes phi(x) which is the number of positive integers less than or equal // to x that are relatively prime to x // Template Arguments: // T: the type of x // Function Arguments: // x: the value to find phi(x) // Return Value: phi(x) // In practice, has a small constant // Time Complexity: O(sqrt x) // Memory Complexity: O(1) // Tested: // https://www.spoj.com/problems/ETF/ template <class T> T phi(T x) { T ret = x; for (T i = 2; i * i <= x; i++) if (x % i == 0) for (ret -= ret / i; x % i == 0; x /= i); if (x > 1) ret -= ret / x; return ret; } // Computes mobius(x), which is 0 if x contains a squared prime factor, // -1 if x has an odd number of prime factors with no squares, // 1 if x has an even number of prime factors with no squares // Template Arguments: // T: the type of x // Function Arguments: // x: the value to find mobius(x) // Return Value: the value of mobius(x) // In practice, has a small constant // Time Complexity: O(sqrt x) // Memory Complexity: O(1) template <class T> int mobius(T x) { int ret = 1; for (T i = 2; i * i <= x; i++) if (x % i == 0) { x /= i; ret *= -1; if (x % i == 0) return 0; } if (x > 1) ret *= -1; return ret; } // Finds the factors of x // Template Arguments: // T: the type of x // Function Arguments: // x: the value to find the factors // Return Value: a vector of T with the factors of x, // not guaranteed to be sorted // In practice, has a small constant // Time Complexity: O(sqrt x) // Memory Complexity: O(sqrt x) // Tested: // https://www.spoj.com/problems/CZ_PROB2/ template <class T> vector<T> factor(T x) { vector<T> ret; for (T i = 1; i * i <= x; i++) if (x % i == 0) { ret.push_back(i); if (x / i != i) ret.push_back(x / i); } return ret; } // Determine if x is prime using the Miller Rabin Primality Test // Template Arguments: // T: the type of x // Function Arguments: // x: the value to check if prime, mulMod(x, x, x) should not overflow // iterations: number of iterations to run, should be at least 7 // Return Value: true if x is prime, false otherwise, can return // false positives for x > 7e18, otherwise is guaranteed to be correct // In practice, has a small constant // Time Complexity: O(time complexity of powMod) // Memory Complexity: O(iterations) // Tested: // https://dmoj.ca/problem/bf3hard template <class T> bool millerRabin(T x, int iterations = 7) { if (x < 2 || x % 6 % 4 != 1) return (x | 1) == 3; vector<T> A = {2, 325, 9375, 28178, 450775, 9780504, 1795265022}; while (int(A.size()) < iterations) A.push_back(uniform_int_distribution<long long>( 1795265023, numeric_limits<long long>::max())(rng64)); int s = 0; while (!(((x - 1) >> s) & 1)) s++; T d = x >> s; for (T a : A) { T p = powMod(a % x, d, x); int i = s; while (p != 1 && p != x - 1 && a % x != 0 && i--) p = mulMod(p, p, x); if (p != x - 1 && i != s) return false; } return true; } // Sieve of Erathosthenes to identify primes less than or equal to N // Constructor Arguments: // N: the maximum value // f(i): the function to run a callback on for each prime i // Fields: // p: a vector of booleans with the ith indicating whether the integer // i * 2 + 1 is prime or not // Functions: // isPrime(x): returns whether x is prime or not // In practice, has a very small constant // Time Complexity: // constructor: O(N log log N) // isPrime: O(1) // Memory Complexity: O(N / 128) // Tested: // https://judge.yosupo.jp/problem/enumerate_primes // https://codeforces.com/contest/1149/problem/A struct Sieve { vector<bool> p; template <class F = function<void(int)>> Sieve(int N, F f = [] (int) {}) : p(N / 2 + 1, true) { p[0] = false; if (N >= 2) f(2); for (int i = 3; i <= N; i += 2) if (p[i / 2]) { f(i); if (i <= (N + i - 1) / i) for (int j = i * i; j <= N; j += i * 2) p[j / 2] = false; } } bool isPrime(int x) { return x == 2 || (x % 2 == 1 && p[x / 2]); } }; // Sieve of Erathosthenes to identify primes, the smallest prime factor of // each number from 1 to N, the phi function, and the mobius function // Constructor Arguments: // N: the maximum value // Fields: // isPrime: a vector of N + 1 booleans indicating whether each integer is // prime or not // primes: a vector of all primes less than or equal to N // SPF: a vector of N + 1 integers representing the smallest prime factor // less than or equal to each integer // phi: a vector of integers with phi[i] equal to the number of positive // integers less than or equal to i that are relatively prime to i // mobius: a vector of chars with mobius[i] equal to 0 if i contains a // squared prime factor, -1 if it has an odd number of prime factors with // no squares, 1 if it has an even number of prime factors with no squares // Functions: // primeFactor(x): returns a sorted vector of integers with the // prime factorization of x // primeFactorWithCount(x): returns a sorted vector of pairs of integers // with each prime factor of x and its exponent // In practice, has a small constant // Time Complexity: // constructor: O(N) // primeFactor, primeFactorWithCount: O(log x) // Memory Complexity: O(N) // Tested: // https://tlx.toki.id/problems/troc-16/E // https://dmoj.ca/problem/nccc7j5 struct SievePrimeFactoring { vector<bool> isPrime; vector<int> primes, SPF, phi; vector<char> mobius; SievePrimeFactoring(int N) : isPrime(N + 1, true), SPF(N + 1, 0), phi(N + 1, 0), mobius(N + 1, 1) { isPrime[0] = isPrime[1] = false; phi[1] = 1; for (int i = 2; i <= N; i++) { if (isPrime[i]) { primes.push_back(SPF[i] = i); phi[i] = i - 1; mobius[i] = -1; } for (int p : primes) { if (i * p > N) break; isPrime[i * p] = false; SPF[i * p] = p; if (i % p == 0) { phi[i * p] = phi[i] * p; mobius[i * p] = 0; break; } phi[i * p] = phi[i] * phi[p]; mobius[i * p] = mobius[i] * -1; } } } vector<int> primeFactor(int x) { vector<int> ret; while (x > 1) { ret.push_back(SPF[x]); x /= SPF[x]; } return ret; } vector<pair<int, int>> primeFactorWithCount(int x) { vector<pair<int, int>> ret; while (x > 1) { ret.emplace_back(SPF[x], 0); for (int spf = SPF[x]; x % spf == 0; x /= spf) ret.back().second++; } return ret; } }; // Segmented Sieve of Eratosthenes to identify primes between lo and hi // Template Arguments: // T: the type of lo and hi // F: the type of f // Functions Arguments: // lo: the inclusive lower bound // hi: the inclusive upper bound // f(i): the function to run a callback on for each prime i // In practice, has a small constant // Time Complexity: O(sqrt(hi) log(log(hi)) + (hi - lo)) // Memory Complexity: O(sqrt(hi) + (hi - lo)) // Tested: // https://dmoj.ca/problem/phantom3 template <class T, class F> void segmentedSieve(T lo, T hi, F f) { lo = max(lo, T(2)); T sqrtHi = sqrtl(hi) + 2; while (sqrtHi * sqrtHi > hi) sqrtHi--; vector<bool> p1(sqrtHi + 1, false), p2(hi - lo + 1, false); p1[0] = p1[1] = true; for (T i = 2; i <= sqrtHi; i++) if (!p1[i]) { for (T j = i * i; j <= sqrtHi; j += i) p1[j] = true; for (T j = (lo + i - 1) / i * i; j <= hi; j += i) if (j != i && !p2[j - lo]) p2[j - lo] = true; } for (T i = 0; i < hi - lo + 1; i++) if (!p2[i]) f(lo + i); } // Returns an arbitrary divisor of non prime N // Template Arguments: // T: the type of N // Function Arguments: // N: the non prime value to find a divisor, mulMod(N, N, N) should not // overflow // iterations: number of iterations to run, should be at least 40 // Return Value: an arbitrary divisor of N // In practice, has a moderate constant // Time Complexity: O(N^(1/4)) // Memory Complexity: O(1) // Tested: // https://loj.ac/p/6466 // https://www.spoj.com/problems/FACT2/ // https://judge.yosupo.jp/problem/factorize template <class T> T pollardsRho(T N, int iterations = 40) { if (N == 1) return 1; auto f = [&] (T x) { return mulMod(x, x, N) + 1; }; T x = 0, y = 0, p = 2, q; int t = 0, i = 1; while (t++ % iterations != 0 || gcd(p, N) == 1) { if (x == y) y = f(x = ++i); if ((q = mulMod(p, max(x, y) - min(x, y), N)) != 0) p = q; x = f(x); y = f(f(y)); } return gcd(p, N); } // Prime factors a large integer x // Template Arguments: // T: the type of N // Function Arguments: // x: the value to prime factor, mulMod(x, x, x) should not overflow // pollardsRhoIters: number of iterations to run pollard rho, should be // at least 40 // millerRabinIters: number of iterations to run miller rabin, should be // at least 7 // Return Value: a sorted vector of T with the prime factorization of x // In practice, has a moderate constant // Time Complexity: O(x^(1/4) log(x)) // Memory Complexity: O(log x) // Tested: // https://www.spoj.com/problems/FACT2/ // https://judge.yosupo.jp/problem/factorize template <class T> vector<T> pollardsRhoPrimeFactor(T x, int pollardsRhoIters = 40, int millerRabinIters = 7) { if (x == 1) return vector<T>(); vector<T> ret; queue<T> q; q.push(x); while (!q.empty()) { T y = q.front(); q.pop(); if (millerRabin(y, millerRabinIters)) ret.push_back(y); else { q.push(pollardsRho(y, pollardsRhoIters)); q.push(y / q.back()); } } return ret; } // Prime factors a large integer x and its exponent // Template Arguments: // T: the type of N // Function Arguments: // x: the value to prime factor, mulMod(x, x, x) should not overflow // pollardsRhoIters: number of iterations to run pollard rho, should be // at least 40 // millerRabinIters: number of iterations to run miller rabin, should be // at least 7 // Return Value: a sorted vector of pairs of T and int with each // prime factor of x and its exponent // In practice, has a moderate constant // Time Complexity: O(x^(1/4) log(x)) // Memory Complexity: O(log x) // Tested: // https://www.spoj.com/problems/FACT2/ template <class T> vector<pair<T, int>> pollardsRhoPrimeFactorWithCount( T x, int pollardsRhoIters = 40, int millerRabinIters = 7) { vector<T> pf = pollardsRhoPrimeFactor(x, pollardsRhoIters, millerRabinIters); sort(pf.begin(), pf.end()); vector<pair<T, int>> ret; for (int i = 0, cnt = 0; i < int(pf.size()); i++) { cnt++; if (i + 1 == int(pf.size()) || pf[i] != pf[i + 1]) { ret.emplace_back(pf[i], cnt); cnt = 0; } } return ret; } // Determines the factors of all numbers from 1 to N // Constructor Arguments: // N: the maximum value // Fields: // factors: a vector of vectors of integers with factors[i] being the sorted // factors of i // In practice, has a moderate constant // Time Complexity: // constructor: O(N log N) // Memory Complexity: O(N log N) // Tested: // https://codeforces.com/contest/111/problem/B struct Factors { vector<vector<int>> factors; Factors(int N) : factors(N + 1) { for (int i = 1; i <= N; i++) for (int j = i; j <= N; j += i) factors[j].push_back(i); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes base to the power of pow // Template Arguments: // T: the type of base // U: the type of pow // Function Arguments: // base: the base // pow: the power, must be non negative and integral // Return Value: returns base to the power of pow // In practice, has a small constant // Time Complexity: O(log pow) // Memory Complexity: O(1) // Tested: // https://cses.fi/problemset/task/1095 template <class T, class U> T pow2(T base, U pow) { T x = 1; while (true) { if (pow % 2 == 1) x = x * base; if ((pow /= 2) == 0) break; base = base * base; } return x; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Solve the equation Ax = b for a matrix A of size M x N, and vectors b of // size M, and vector x of size N // Template Arguments: // T: the type of each element // Constructor Arguments: // A: a M x N matrix // b: a vector, with dimension M // EPS: a value for epsilon // Fields: // NO_SOLUTION: static const int representing no solution // ONE_SOLUTION: static const int representing one solution // INF_SOLUTIONS: static const int representing infinite solution // M: the number of equations // N: the number of variables // solutions: the number of solution to the equation, equal to one of // NO_SOLUTION, ONE_SOLUTION, or INF_SOLUTIONS // EPS: the value for epsilon // x: the solution vector with dimension N, can be any solution if there are // infinite solutions, undefined if no solutions // In practice, has a very small constant // Time Complexity: // constructor: O(min(M, N) MN) // Memory Complexity: O(MN) // Tested: // https://open.kattis.com/problems/equationsolver template <class T> struct GaussianElimination { static const int NO_SOLUTION = 0, ONE_SOLUTION = 1, INF_SOLUTIONS = 2; T abs(T a) { return a >= 0 ? a : -a; } int M, N, solutions; T EPS; vector<T> x; GaussianElimination(vector<vector<T>> A, vector<T> b, T EPS = T(1e-9)) : M(A.size()), N(M == 0 ? 0 : A[0].size()), solutions(ONE_SOLUTION), EPS(EPS), x(N, T()) { vector<int> ind(N, -1); for (int r = 0, c = 0; c < N && r < M; c++) { int mx = r; for (int i = r + 1; i < M; i++) if (abs(A[i][c]) > abs(A[mx][c])) mx = i; if (abs(A[mx][c]) <= EPS) continue; if (r != mx) { A[r].swap(A[mx]); swap(b[r], b[mx]); } ind[c] = r; T inv = T(1) / A[r][c]; for (int i = 0; i < M; i++) if (i != r) { T alpha = A[i][c] * inv; b[i] -= b[r] * alpha; for (int j = c; j < N; j++) A[i][j] -= A[r][j] * alpha; } r++; } for (int i = 0; i < N; i++) if (ind[i] != -1) x[i] = b[ind[i]] / A[ind[i]][i]; for (int i = 0; i < M; i++) { T sm = T(); for (int j = 0; j < N; j++) sm += x[j] * A[i][j]; if (abs(sm - b[i]) > EPS) { solutions = NO_SOLUTION; x.clear(); return; } } for (int i = 0; i < N; i++) if (ind[i] == -1) solutions = INF_SOLUTIONS; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Solve the xor boolean satisfiability problem for a boolean matrix A of // size M x N, and vectors b of size M, and vector x of size N, so that // b_i = xor(A[i][j] & x[j]) for 0 <= j < N; equivalent to solving the // equation Ax = b mod 2 for a matrix A, and vectors b, x where all values // are 0 or 1 // Template Arguments: // MAXN: the maximmum value of N // Constructor Arguments: // A: a M x N boolean matrix // b: a boolean vector, with dimension M // Fields: // NO_SOLUTION: static const int representing no solution // ONE_SOLUTION: static const int representing one solution // INF_SOLUTIONS: static const int representing infinite solution // M: the number of equations // N: the number of variables // solutions: the number of solution to the equation, equal to one of // NO_SOLUTION, ONE_SOLUTION, or INF_SOLUTIONS // x: the solution vector with dimension N, can be any solution if there are // infinite solutions, undefined if no solutions // In practice, has a very small constant // Time Complexity: // constructor: O(min(M, N) M MAXN / 64) // Memory Complexity: O(M MAXN / 64) // Tested: // https://dmoj.ca/problem/tle16c1p6 // https://dmoj.ca/problem/dmopc20c4p6 template <const int MAXN> struct XorSat { static const int NO_SOLUTION = 0, ONE_SOLUTION = 1, INF_SOLUTIONS = 2; int M, N, solutions; bitset<MAXN> x; XorSat(vector<bitset<MAXN>> A, vector<bool> b) : M(A.size()), N(M == 0 ? 0 : A[0].size()), solutions(ONE_SOLUTION) { vector<int> ind(N, -1); for (int r = 0, c = 0; c < N && r < M; c++) { int mx = r; for (int i = r + 1; i < M; i++) if (A[i][c]) { mx = i; break; } if (!A[mx][c]) continue; if (r != mx) { swap(A[r], A[mx]); swap(b[r], b[mx]); } ind[c] = r; for (int i = 0; i < M; i++) if (i != r && A[i][c]) { b[i] = b[i] ^ b[r]; A[i] ^= A[r]; } r++; } for (int i = 0; i < N; i++) if (ind[i] != -1) x[i] = b[ind[i]]; for (int i = 0; i < M; i++) { bool val = false; for (int j = 0; j < N; j++) val ^= x[j] & A[i][j]; if (val != b[i]) { solutions = NO_SOLUTION; x.reset(); return; } } for (int i = 0; i < N; i++) if (ind[i] == -1) solutions = INF_SOLUTIONS; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes the basis of vectors in base 2 // Template Arguments: // BITS: the number of bits // Fields: // basis: a vector of bitsets of length BITS, with the ith element being the // reduced vector with the most significant bit of i, or empty if there is // no such vector // ids: a vector of integers representing the id of the ith vector in basis, // or -1 if basis[i] is empty // Functions: // addVector(v, id): adds the vector v to the set with and id of id // inSpan(v): returns whether a vector v is in the span of the basis // In practice, has a small constant // Time Complexity: // constructor, addVector, inSpan: O(BITS^2 / 64) // Memory Complexity: O(BITS^2 / 64) // Tested: // https://dmoj.ca/problem/dmopc19c5p5 template <const int BITS> struct XorBasis { vector<bitset<BITS>> basis; vector<int> ids; XorBasis() : basis(BITS), ids(BITS, -1) {} void addVector(bitset<BITS> v, int id) { for (int i = 0; i < BITS; i++) if (v[i]) { if (basis[i].none()) { basis[i] = v; ids[i] = id; return; } v ^= basis[i]; } } bool inSpan(bitset<BITS> v) { for (int i = 0; i < BITS; i++) if (v[i]) v ^= basis[i]; return v.none(); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Fast Fourier Transform // Template Arguments: // F: the floating point type of the complex number components // Function Arguments: // a: a reference to the vector of complex numbers (of type complex<F>) // to convolute // In practice, has a moderate constant, faster than using Karatsuba, slower // than NTT // Time Complexity: O(N log N) where N = size(a) // Memory Complexity: O(N) // Tested: // https://open.kattis.com/problems/polymul2 // https://dmoj.ca/problem/atimesb template <class F> void fft(vector<complex<F>> &a) { static_assert(is_floating_point<F>::value, "F must be a floating point type"); static vector<complex<F>> rt(2, 1); static vector<int> ord; static int k = 2; static F PI = acos(F(-1)); int N = a.size(); assert(!(N & (N - 1))); for (; k < N; k <<= 1) { rt.resize(N); complex<F> x = polar(F(1), PI / k); for (int i = k; i < (k << 1); i++) rt[i] = i & 1 ? rt[i >> 1] * x : rt[i >> 1]; } if (int(ord.size()) != N) { ord.assign(N, 0); int len = __builtin_ctz(N); for (int i = 0; i < N; i++) ord[i] = (ord[i >> 1] >> 1) + ((i & 1) << (len - 1)); } for (int i = 0; i < N; i++) if (i < ord[i]) swap(a[i], a[ord[i]]); for (int len = 1; len < N; len <<= 1) for (int i = 0; i < N; i += len << 1) for (int j = 0; j < len; j++) { complex<F> u = a[i + j], x = a[len + i + j], y = rt[len + j]; complex<F> v(real(x) * real(y) - imag(x) * imag(y), real(x) * imag(y) + imag(x) * real(y)); a[i + j] = u + v; a[len + i + j] = u - v; } } // Polynomial Multiplication // Template Arguments: // T: the type of each element // F: the floating point type to use for FFT // Functions Arguments: // a: a vector of type T representing the first polynomial, a[i] stores // the coefficient of x^i // b: a vector of type T representing the second polynomial, b[i] stores // the coefficient of x^i // Return Value: a vector of type T representing the polynomial a times b with // no trailing zeros // In practice, has a moderate constant // Time Complexity: O(N log N) where N = size(a) + size(b) // Memory Complexity: O(N) // Tested: // https://open.kattis.com/problems/polymul2 const int FFT_CUTOFF = 30000; template <class T, class F = long double> vector<T> mulPolyFFT(const vector<T> &a, const vector<T> &b) { int N = max(0, int(a.size()) + int(b.size()) - 1); if ((long long)(a.size()) * (long long)(b.size()) <= FFT_CUTOFF) { vector<T> res(N, T()); for (int i = 0; i < int(a.size()); i++) for (int j = 0; j < int(b.size()); j++) res[i + j] += a[i] * b[j]; while (int(res.size()) > 1 && res.back() == T()) res.pop_back(); return res; } while (N & (N - 1)) N++; vector<complex<F>> f(N, complex<F>(0, 0)); for (int i = 0; i < int(a.size()); i++) f[i].real(a[i]); for (int i = 0; i < int(b.size()); i++) f[i].imag(b[i]); fft(f); complex<F> r(0, F(-0.25) / N); for (int i = 0; i <= N / 2; i++) { int j = (N - i) & (N - 1); complex<F> prod = (f[j] * f[j] - conj(f[i] * f[i])) * r; f[i] = prod; f[j] = conj(prod); } fft(f); vector<T> res(N, T()); bool isIntegral = is_integral<T>::value; for (int i = 0; i < N; i++) res[i] = isIntegral ? round(real(f[i])) : real(f[i]); while (int(res.size()) > 1 && res.back() == T()) res.pop_back(); return res; } // Integer Multiplication // Template Arguments: // T: the type of each digit // F: the floating point type to use for FFT // Functions Arguments: // a: a vector of type T representing the first integer, a[i] stores // the digit of BASE^i // b: a vector of type T representing the second polynomial, b[i] stores // the digit of BASE^i // BASE: the base of the integer // Return Value: a vector of type T representing the integer a times b with // no trailing zeros // In practice, has a moderate constant // Time Complexity: O(n log n) where n = size(a) + size(b) // Memory Complexity: O(n) // Tested: // https://dmoj.ca/problem/atimesb template <class T, class F = long double> vector<T> mulIntFFT(const vector<T> &a, const vector<T> &b, T BASE = T(10)) { vector<T> res = mulPolyFFT<T, F>(a, b); T carry = T(); res.reserve(res.size() + 1); for (int i = 0; i < int(res.size()); i++) { T cur = res[i] + carry; res[i] = T(cur % BASE); carry = T(cur / BASE); } if (carry > T()) res.push_back(carry); return res; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Two Phase Simplex to solve a linear programming problem with N variables // and M equations in canonical form: // max c^T x // subject to Ax <= b and x >= 0 // where A is an M x N matrix; b is a vector with dimension M; // c, x are vectors with dimension N // Template Arguments: // F: a floating point type // Constructor Arguments: // A: a M x N coefficient matrix, memory is saved if this is moved and has // a capacity of M + 2 x N + 2 // b: a constraint vector, with dimension M // c: a cost vector, with dimension N // INF: a value for infinity // EPS: a value for epsilon // Fields: // M: the number of equations // N: the number of variables // INF: the value for infinity // EPS: the value for epsilon // val: the value of the maximum cost of the objective function c^T x, // INF if unbounded, -INF if infeasible // x: a solution vector of dimension N producing the maximum cost, can be // any solution if unbounded, empty if infeasible // In practice, has a very small constant // Time Complexity: // constructor: O(2^N), worst case, much faster in practice // Memory Complexity: O(MN) // Tested: // https://open.kattis.com/problems/cheeseifyouplease // https://open.kattis.com/problems/goatropes // https://codeforces.com/contest/375/problem/E // https://codeforces.com/contest/605/problem/C // https://codeforces.com/contest/1061/problem/E // https://codeforces.com/contest/1288/problem/F // https://www.spoj.com/problems/BABY/ // https://dmoj.ca/problem/noi08p3 template <class F> struct Simplex { static_assert(is_floating_point<F>::value, "F must be a floating point type"); int M, N; F INF, EPS, val; vector<int> IN, OUT; vector<F> x; vector<vector<F>> T; bool cmp(F a, int b, F c, int d) { return abs(a - c) > EPS ? a < c : b < d; } void pivot(int r, int s) { auto &a1 = T[r]; F inv1 = F(1) / a1[s]; for (int i = 0; i <= M + 1; i++) if (i != r && abs(T[i][s]) > EPS) { auto &a2 = T[i]; F inv2 = a2[s] * inv1; for (int j = 0; j <= N + 1; j++) a2[j] -= a1[j] * inv2; a2[s] = a1[s] * inv2; } for (int j = 0; j <= N + 1; j++) if (j != s) a1[j] *= inv1; for (int i = 0; i <= M + 1; i++) if (i != r) T[i][s] *= -inv1; a1[s] = inv1; swap(IN[r], OUT[s]); } bool simplex(int phase) { int x = M + phase - 1; while (true) { int s = -1; for (int j = 0; j <= N; j++) if (OUT[j] != -phase && (s == -1 || cmp(T[x][j], OUT[j], T[x][s], OUT[s]))) s = j; if (T[x][s] >= -EPS) return true; int r = -1; for (int i = 0; i < M; i++) if (T[i][s] > EPS && (r == -1 || cmp(T[i][N + 1] * T[r][s], IN[i], T[r][N + 1] * T[i][s], IN[r]))) r = i; if (r == -1) return false; pivot(r, s); } } Simplex(vector<vector<F>> A, const vector<F> &b, const vector<F> &c, F INF = numeric_limits<F>::infinity(), F EPS = F(1e-9)) : M(b.size()), N(c.size()), INF(INF), EPS(EPS), IN(M), OUT(N + 1), T(move(A)) { T.reserve(M + 2); for (int i = 0; i < M; i++) { T[i].resize(N + 2, F()); IN[i] = N + i; T[i][N] = F(-1); T[i][N + 1] = b[i]; } T.emplace_back(N + 2, F()); T.emplace_back(N + 2, F()); for (int j = 0; j < N; j++) { OUT[j] = j; T[M][j] = -c[j]; } OUT[N] = -1; T[M + 1][N] = F(1); int r = 0; for (int i = 1; i < M; i++) if (T[i][N + 1] < T[r][N + 1]) r = i; if (T[r][N + 1] < -EPS) { pivot(r, N); if (!simplex(2) || T[M + 1][N + 1] < -EPS) { val = -INF; return; } for (int i = 0; i < M; i++) if (IN[i] == -1) { int s = 0; for (int j = 1; j <= N; j++) if (s == -1 || cmp(T[i][j], OUT[j], T[i][s], OUT[s])) s = j; pivot(i, s); } } bool unbounded = !simplex(1); x.assign(N, F()); for (int i = 0; i < M; i++) if (IN[i] < N) x[IN[i]] = T[i][N + 1]; val = unbounded ? INF : T[M][N + 1]; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; template <class T> using Matrix = vector<vector<T>>; // Returns the size of the first dimension of a matrix // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: the matrix // Return Value: the size of the first dimension of the matrix A // In practice, has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> int getN(const Matrix<T> &A) { return A.size(); } // Returns the size of the second dimension of a matrix // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: the matrix // Return Value: the size of the second dimension of the matrix A // In practice, has a very small constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // Fuzz Tested template <class T> int getM(const Matrix<T> &A) { return A.empty() ? 0 : A[0].size(); } // Creates a matrix of size N x M filled with the default value of T // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // N: the size of the first dimension // M: the size of the second dimension // Return Value: a matrix of size N x M filled with the default value of T // In practice, has a very small constant // Time Complexity: O(NM) // Memory Complexity: O(NM) // Tested: // Fuzz Tested template <class T> Matrix<T> makeMatrix(int N, int M) { return vector<vector<T>>(N, vector<T>(M, T())); } // Creates an identity matrix of size N x N // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // N: the size of both dimensions // Return Value: an identity matrix of size N x N // In practice, has a very small constant // Time Complexity: O(N^2) // Memory Complexity: O(N^2) // Tested: // https://www.spoj.com/problems/MPOW/ template <class T> Matrix<T> identityMatrix(int N) { Matrix<T> A = makeMatrix<T>(N, N); for (int i = 0; i < N; i++) A[i][i] = T(1); return A; } // Returns the transpose of a matrix // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: the matrix // Return Value: the transpose of the matrix A // In practice, has a very small constant // Time Complexity: O(NM) // Memory Complexity: O(NM) // Tested: // Fuzz Tested template <class T> Matrix<T> transpose(const Matrix<T> &A) { Matrix<T> C = makeMatrix<T>(getM(A), getN(A)); for (int i = 0; i < getN(C); i++) for (int j = 0; j < getM(C); j++) C[i][j] = A[j][i]; return C; } // Adds B to the matrix A // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: a reference to the first matrix // B: a constant reference to the matrix to add // Return Value: a reference to the matrix A after B is added to it // In practice, has a very small constant // Time Complexity: O(NM) // Memory Complexity: O(NM) // Tested: // Fuzz Tested template <class T> Matrix<T> &operator += (Matrix<T> &A, const Matrix<T> &B) { assert(getN(A) == getN(B) && getM(A) == getM(B)); for (int i = 0; i < getN(A); i++) for (int j = 0; j < getM(A); j++) A[i][j] += B[i][j]; return A; } // Adds the matrices A and B // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: the first matrix // B: a constant reference to the matrix to add // Return Value: the matrix A plus B // In practice, has a very small constant // Time Complexity: O(NM) // Memory Complexity: O(NM) // Tested: // Fuzz Tested template <class T> Matrix<T> operator + (Matrix<T> A, const Matrix<T> &B) { return A += B; } // Subtracts B from the matrix A // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: a reference to the first matrix // B: a constant reference to the matrix to subtract // Return Value: a reference to the matrix A after B is subtracted from it // Time Complexity: O(NM) // Memory Complexity: O(NM) // Tested: // Fuzz Tested template <class T> Matrix<T> &operator -= (Matrix<T> &A, const Matrix<T> &B) { assert(getN(A) == getN(B) && getM(A) == getM(B)); for (int i = 0; i < getN(A); i++) for (int j = 0; j < getM(A); j++) A[i][j] -= B[i][j]; return A; } // Subtracts the matrices A and B // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: the first matrix // B: a constant reference to the matrix to add // Return Value: the matrix A minus B // In practice, has a very small constant // Time Complexity: O(NM) // Memory Complexity: O(NM) // Tested: // Fuzz Tested template <class T> Matrix<T> operator - (Matrix<T> A, const Matrix<T> &B) { return A -= B; } // Multiplies the matrices A and B, getM(A) must equal getN(B) // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: a constant reference to the first matrix // B: the matrix to multiply // Return Value: the matrix A times B // In practice, has a very small constant // Time Complexity: O(N(A) M(B) M(A)) // Memory Complexity: O((N(A) + N(B)) M(B)) // Tested: // https://www.spoj.com/problems/MPOW/ template <class T> Matrix<T> operator * (const Matrix<T> &A, Matrix<T> B) { assert(getM(A) == getN(B)); B = transpose(B); Matrix<T> C = makeMatrix<T>(getN(A), getN(B)); for (int i = 0; i < getN(C); i++) for (int j = 0; j < getM(C); j++) { T tmp = T(); for (int k = 0; k < getM(A); k++) tmp += A[i][k] * B[j][k]; C[i][j] = tmp; } return C; } // Multiplies the matrix B into the matrix A, getM(A) must equal getN(B) // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: a reference to the first matrix // B: a constant reference to the matrix to multiply // Return Value: a reference to the matrix A after it is multipled by B // In practice, has a very small constant // Time Complexity: O(N(A) M(B) M(A)) // Memory Complexity: O((N(A) + N(B)) M(B)) // Tested: // https://www.spoj.com/problems/MPOW/ template <class T> Matrix<T> &operator *= (Matrix<T> &A, const Matrix<T> &B) { return A = A * B; } // Raises the square matrix A to the power of pow, getN(A) must equal getM(A) // Template Arguments: // T: the type of each element in the matrix // U: the type of pow // Function Arguments: // A: the base square matrix // Return Value: the matrix A raised to the power pow // In practice, has a very small constant // Time Complexity: O(N^3 log pow) // Memory Complexity: O(N^2) // Tested: // https://www.spoj.com/problems/MPOW/ template <class T, class U> Matrix<T> powMat(Matrix<T> A, U pow) { assert(getN(A) == getM(A)); Matrix<T> x = identityMatrix<T>(getN(A)); while (true) { if (pow % 2 == 1) x *= A; if ((pow /= 2) == 0) break; A *= A; } return x; } // Computes the determinant of a square matrix A, getN(A) must equal getM(A) // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: the matrix // Return Value: the determinant of the matrix A // In practice, has a very small constant // Time Complexity: O(N^3) // Memory Complexity: O(N^2) // Tested: // https://judge.yosupo.jp/problem/matrix_det // https://dmoj.ca/problem/det template <class T> T det(Matrix<T> A) { auto abs = [&] (T a) { return a >= 0 ? a : -a; }; int N = getN(A); assert(N == getM(A)); T ret = T(1); for (int i = 0; i < N; i++) { int mx = i; for (int j = i + 1; j < N; j++) if (abs(A[j][i]) > abs(A[mx][i])) mx = j; if (i != mx) { ret = -ret; A[i].swap(A[mx]); } T inv = T(1) / A[i][i]; for (int j = i + 1; j < N; j++) { T alpha = A[j][i] * inv; for (int k = i + 1; k < N; k++) A[j][k] -= alpha * A[i][k]; } } for (int i = 0; i < N; i++) ret *= A[i][i]; return ret; } // Computes the inverse of a square matrix A, getN(A) must equal getM(A) // Template Arguments: // T: the type of each element in the matrix // Function Arguments: // A: the matrix // EPS: a value for epsilon // Return Value: the inverse of the matrix A, // or a 0 x 0 matrix if it does not exist // In practice, has a very small constant // Time Complexity: O(N^3) // Memory Complexity: O(N^2) // Tested: // https://www.spoj.com/problems/MIFF/ // https://judge.yosupo.jp/problem/inverse_matrix template <class T> Matrix<T> invMat(Matrix<T> A, T EPS = T(1e-9)) { auto abs = [&] (T a) { return a >= 0 ? a : -a; }; int N = getN(A); assert(N == getM(A)); Matrix<T> I = identityMatrix<T>(N); for (int i = 0; i < N; i++) { int mx = i; for (int j = i; j < N; j++) if (A[j][i] != 0) { mx = j; break; } if (abs(A[mx][i]) <= EPS) return makeMatrix<T>(0, 0); if (i != mx) { A[i].swap(A[mx]); I[i].swap(I[mx]); } T inv = T(1) / A[i][i]; for (int k = i; k < N; k++) A[i][k] *= inv; for (int k = 0; k < N; k++) I[i][k] *= inv; for (int j = 0; j < N; j++) if (j != i) { T alpha = A[j][i]; if (abs(alpha) <= EPS) continue; for (int k = i; k < N; k++) A[j][k] -= alpha * A[i][k]; for (int k = 0; k < N; k++) I[j][k] -= alpha * I[i][k]; } } return I; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes the maximum axis aligned rectangular area of a histogram where // all bars have width 1 // Template Arguments: // T: the type of the heights // Function Arguments: // A: a vector of the heights of each bar // Return Value: the maximum axis aligned rectangular area of the histogram // In practice, has a moderate constant // Time Complexity: O(N) // Memory Complexity: O(N) // Tested: // https://www.acmicpc.net/problem/6549 template <class T> T maxRectAreaHistogram(vector<T> A) { T ret = T(); int N = A.size(), top = 0; vector<int> stk(N); for (int i = 0; i < int(A.size()); i++) { int j = i; while (top > 0 && A[stk[top - 1]] >= A[i]) { ret = max(ret, (i - stk[top - 1]) * A[stk[top - 1]]); A[j = stk[--top]] = A[i]; } stk[top++] = j; } for (; top > 0; top--) ret = max(ret, (N - stk[top - 1]) * A[stk[top - 1]]); return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "MaxRectAreaHistogram.h" using namespace std; // Computes the maximum submatrix of a boolean matrix where // all elements are true // Function Arguments: // A: a vector of vectors of booleans // Return Value: the maximum submatrix of the boolean matrix where // all elements are true // In practice, has a moderate constant // Time Complexity: O(NM) // Memory Complexity: O(M) // Tested: // https://dmoj.ca/problem/ccoprep16q1 int maxOneSubmatrix(const vector<vector<bool>> &A) { int N = A.size(), M = N == 0 ? 0 : A[0].size(), ret = 0; vector<int> H(M, 0); for (int i = N - 1; i >= 0; i--) { for (int j = 0; j < M; j++) H[j] = A[i][j] ? i == N - 1 ? 1 : H[j] + 1 : 0; ret = max(ret, maxRectAreaHistogram(H)); } return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes an array z, where z[i] is the length of the longest subarray // starting at S[i], which is also a prefix of S (maximum k such // that S[i + j] == S[j] for all 0 <= j < k) // Indices are 0-indexed and ranges are inclusive // T: the type of each element in the array // Constructor Arguments: // S: a vector of type T // Fields: // N: the length of the array // S: a vector of type T representing the array // z: a vector of integers where the ith element is the length of the // longest subarray starting at index i which is also a prefix of S // In practice, has a moderate constant // Time Complexity: // constructor: O(N) // Memory Complexity: O(N) // Tested: // https://judge.yosupo.jp/problem/zalgorithm // https://open.kattis.com/problems/stringmatching template <class T> struct ZAlgorithm { int N; vector<int> z; ZAlgorithm(const vector<T> &S) : N(S.size()), z(N, 0) { z[0] = N; for (int i = 1, l = 0, r = 0; i < N; i++) { if (i <= r) z[i] = min(r - i + 1, z[i - l]); while (i + z[i] < N && S[z[i]] == S[i + z[i]]) z[i]++; if (i + z[i] - 1 > r) r = (l = i) + z[i] - 1; } } }; // Finds all starting indices of a pattern array in a text array // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element in the array // Constructor Arguments: // pat: the pattern array // txt: the text array // Fields: // Z: the associated ZAlgorithm object constructed from the concatenation // of the pattern and the text array // matches: a vector of all starting indices of the pattern array in // the text array // In practice, has a moderate constant, slightly slower than KMP // Time Complexity: // constructor: O(N + M) // Memory Complexity: O(N + M) // Tested: // https://open.kattis.com/problems/stringmatching template <class T> struct StringMatching { ZAlgorithm<T> Z; vector<int> matches; vector<T> init(vector<T> pat, const vector<T> &txt) { pat.reserve(pat.size() + txt.size()); pat.insert(pat.end(), txt.begin(), txt.end()); return pat; } StringMatching(const vector<T> &pat, const vector<T> &txt) : Z(init(pat, txt)) { assert(int(pat.size()) >= 1); for (int i = 0; i < int(txt.size()); i++) if (Z.z[pat.size() + i] >= int(pat.size())) matches.push_back(i); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // KMP array searching // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element in the array // Constructor Arguments: // pat: the pattern array // Fields: // N: the length of the pattern // fail: a vector of integers where the ith value is the fallback index when // a match failure occures // Functions // search(txt): returns the starting index of the first occurrence of pat in // txt, or -1 if there are none // multisearch(txt): returns a vector of all starting indices of the // pattern array in the text txt // In practice, has a moderate constant, slightly faster than ZAlgorithm // Time Complexity: // constructor: O(N) // search, multisearch: O(M) // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/bf4 // https://open.kattis.com/problems/stringmatching // https://codeforces.com/contest/1466/problem/G template <class T> struct KMP { int N; vector<T> pat; vector<int> fail; KMP(const vector<T> &pat) : N(pat.size()), pat(pat), fail(N + 1, -1) { assert(N >= 1); for (int i = 0, j = -1; i < N;) { while (j >= 0 && pat[i] != pat[j]) j = fail[j]; i++; j++; fail[i] = (i != N && pat[i] == pat[j] ? fail[j] : j); } } int search(const vector<T> &txt) { for (int i = 0, j = 0; i < int(txt.size()); i++, j++) { while (j >= 0 && txt[i] != pat[j]) j = fail[j]; if (j == N - 1) return i - j; } return -1; } vector<int> multiSearch(const vector<T> &txt) { vector<int> ret; for (int i = 0, j = 0; i < int(txt.size()); i++, j++) { while (j >= 0 && (j == N || txt[i] != pat[j])) j = fail[j]; if (j == N - 1) ret.push_back(i - j); } return ret; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Palindromic Tree Node backed by a map // Template Arguments: // _T: the type of the element in the string/array for the Palindromic Tree // Constructor Arguments: // len: the length of the longest palindromic substring represented // by this node // Fields: // T: the data type of each element in the string/array // len: the length of the longest palindromic substring this // node represents // link: the index of the suffix link of this node (the node with the // longest palindromic suffix of this node) // qlink: the index of the quick link of this node (the node with the // longest palindromic suffix which has a different preceding character // as the link node) // Functions: // getEdge(a): returns the index of the other node on the // incident edge with the element a or 1 if no such edge exists // setEdge(a, n): sets the other node on the incident edge // with the element a to n // Time Complexity: // constructor: O(1) // getEdge, setEdge: O(log E) where E is the number of edges // incident to this node // Memory Complexity: O(E) where E is the number of edges incident to this node // Tested: // https://dmoj.ca/problem/apio14p1 template <class _T> struct PalTreeMapNode { using T = _T; int len, link, qlink; map<T, int> to; PalTreeMapNode(int len) : len(len), link(1), qlink(1) {} int getEdge(const T &a) const { auto it = to.find(a); return it == to.end() ? 1 : it->second; } void setEdge(const T &a, int n) { to[a] = n; } }; // Palindromic Tree Node backed by an array // Template Arguments: // _T: the type of the element in the string/array for the Palindromic Tree // ALPHABET_SIZE: the size of the alphabet // OFFSET: the offset for the start of the alphabet // Constructor Arguments: // len: the length of the longest palindromic substring represented // by this node // Fields: // T: the data type of each element in the string/array // len: the length of the longest palindromic substring this // node represents // link: the index of the suffix link of this node (the node with the // longest palindromic suffix of this node) // qlink: the index of the quick link of this node (the node with the // longest palindromic suffix which has a different preceding character // as the link node) // Functions: // getEdge(a): returns the index of the other node on the // incident edge with the element a or 1 if no such edge exists // setEdge(a, n): sets the other node on the incident edge // with the element a to n // Time Complexity: // constructor: O(ALPHABET_SIZE) // getEdge, setEdge: O(1) // Memory Complexity: O(ALPHABET_SIZE) // Tested: // https://dmoj.ca/problem/mmcc15p3 // https://dmoj.ca/problem/apio14p1 template <class _T, const int ALPHABET_SIZE, const _T OFFSET> struct PalTreeArrayNode { using T = _T; int len, link, qlink; array<int, ALPHABET_SIZE> to; PalTreeArrayNode(int len) : len(len), link(1), qlink(1) { to.fill(1); } int getEdge(const T &a) const { return to[a - OFFSET]; } void setEdge(const T &a, int n) { to[a - OFFSET] = n; } }; // Palindromic Tree with two roots at 0 (with length -1) and 1 (with length 0) // Template Arguments: // Node: a node class // Required Fields: // T: the data type of each element in the string/array // len: the length of the longest palindromic substring this // node represents // link: the index of the suffix link of this node (the node with the // longest palindromic suffix of this node) // qlink: the index of the quick link of this node (the node with the // longest palindromic suffix which has a different preceding character // as the link node) // Required Functions: // constructor(len): initializes the node with a length of len with // link, qlink, and edges pointing to 1 by default // getEdge(a): returns the index of the other node on the // incident edge with the element a // setEdge(a, n): sets the other node on the incident edge // with the element a to n // Constructor Arguments: // def: the default value of type T, cannot be in the string/array // Fields: // S: the current string with the default character at the front and // between words // TR: the vector of all nodes in the tree // last: a vector of integers with the last node after each addition or // terminate call // Functions: // add(a): adds the element a to the tree // terminate(): terminates the current word, returning to the root (which // allows for another word to be added with add(a)) // undo(): undoes the last added element, or a terminate operation // In practice, has a small constant // Time Complexity: // constructor: time complexity of node constructor // add: O(log N) + time complexity of node constructor // + time complexity of getEdge in Node // terminate: O(1) // undo: time complexity of setEdge in Node // Memory Complexity: O(N) * memory complexity of node, after N calls to add // Tested: // https://dmoj.ca/problem/mmcc15p3 // https://dmoj.ca/problem/apio14p1 template <class Node> struct PalindromicTree { using T = typename Node::T; T def; vector<T> S; vector<Node> TR; vector<int> last, modified; PalindromicTree(const T &def) : def(def), S(1, def), TR(vector<Node>{Node(-1), Node(0)}), last(1, 1) { TR[1].link = TR[1].qlink = 0; } int getLink(int x, int i) { while (S[i - 1 - TR[x].len] != S[i]) x = S[i - 1 - TR[TR[x].link].len] == S[i] ? TR[x].link : TR[x].qlink; return x; } void add(const T &a) { int i = S.size(); S.push_back(a); int p = getLink(last.back(), i); modified.push_back(-1); if (TR[p].getEdge(a) == 1) { int u = TR.size(); TR.emplace_back(TR[p].len + 2); TR[u].link = TR[getLink(TR[p].link, i)].getEdge(a); T b = S[i - TR[TR[u].link].len], c = S[i - TR[TR[TR[u].link].link].len]; TR[u].qlink = b == c ? TR[TR[u].link].qlink : TR[u].link; TR[modified.back() = p].setEdge(a, u); } last.push_back(TR[p].getEdge(a)); } void terminate() { S.push_back(def); last.push_back(1); modified.push_back(-1); } void undo() { if (modified.back() != -1) { TR[modified.back()].setEdge(S.back(), 1); TR.pop_back(); } S.pop_back(); last.pop_back(); modified.pop_back(); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Modified from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/strings/suffix_array.py, // which has an Apache 2.0 license // Suffix Array Induced Sort to sort suffixes of an array in // lexicographical order // Indices are 0-indexed and ranges are inclusive // Template Arguments: // _T: the type of each element in the array // Constructor Arguments: // S: a vector of type _T // Fields: // T: the type of the character/element in the array // N: the length of the array // rnk: a vector of the ranks of the suffixes (rnk[i] is the rank of the // suffix starting from index i) // ind: a vector of the indices in the original array of the suffixes // sorted in lexicographical order (ind[i] is the index in original array // of the ith lexicographically smallest suffix) // LCP: a vector of the longest common prefixes between the suffixes when // sorted in lexicographical order (LCP[i] is the longest common prefix of // the ith and (i + 1)th lexicographically smallest suffix, with LCP[N - 1] // being 0) // In practice, has a moderate constant, usually faster than SuffixArray // Time Complexity: // constructor: O(N + K) where K is the range of the array // Memory Complexity: O(N + K) // Tested: // Fuzz and Stress Tested // https://judge.yosupo.jp/problem/suffixarray // https://judge.yosupo.jp/problem/number_of_substrings // https://dmoj.ca/problem/coci06c5p6 // https://dmoj.ca/problem/ccc20s3 template <class _T> struct SAISSuffixArray { using T = _T; static vector<int> SAIS(const vector<int> &S) { if (S.empty()) return vector<int>(); int N = S.size(), K = *max_element(S.begin(), S.end()) + 1; vector<bool> isL(N + 1, false); vector<int> ind(N), cnt(K + 1, 0), lms; lms.reserve(N); for (auto &&a : S) cnt[a + 1]++; partial_sum(cnt.begin(), cnt.end(), cnt.begin()); isL[N - 1] = true; for (int i = N - 2; i >= 0; i--) isL[i] = S[i] == S[i + 1] ? isL[i + 1] : S[i] > S[i + 1]; auto c = [&] (int i) { return i > 0 && !isL[i] && isL[i - 1]; }; for (int i = 1; i < N; i++) if (c(i)) lms.push_back(i); auto IS = [&] { vector<int> tmp(cnt.begin() + 1, cnt.end()); fill(ind.begin(), ind.end(), -1); for (int i = int(lms.size()) - 1; i >= 0; i--) ind[--tmp[S[lms[i]]]] = lms[i]; tmp = vector<int>(cnt.begin(), cnt.end() - 1); for (int i = -1, j; i < N; i++) if ((j = i < 0 ? N - 1 : ind[i] - 1) >= 0 && isL[j]) ind[tmp[S[j]]++] = j; tmp = vector<int>(cnt.begin() + 1, cnt.end()); for (int i = N - 1, j; i >= 0; i--) if ((j = ind[i] - 1) >= 0 && !isL[j]) ind[--tmp[S[j]]] = j; }; if (int(lms.size()) > 1) { IS(); vector<int> tmp(ind.begin(), ind.end()); for (int i = 0, j = 0, a = -1; i < N; i++) if (c(tmp[i])) { for (int b = tmp[i]; a >= 0 && S[a] == S[b];) { a++; b++; if (c(a) || c(b)) { j -= int(c(a) && c(b)); break; } } ind[a = tmp[i]] = ++j; } tmp = vector<int>(lms.size()); for (int i = 0; i < int(tmp.size()); i++) tmp[i] = ind[lms[i]]; tmp = SAIS(tmp); for (int i = 0; i < int(tmp.size()); i++) tmp[i] = lms[tmp[i]]; lms = tmp; } IS(); return ind; } static vector<int> init(const vector<T> &S) { if (S.empty()) return vector<int>(); T offset = *min_element(S.begin(), S.end()); vector<int> A(S.size()); for (int i = 0; i < int(S.size()); i++) A[i] = S[i] - offset; return A; } int N; vector<int> ind, rnk, LCP; SAISSuffixArray(const vector<T> &S) : N(S.size()) { ind = SAIS(init(S)); rnk.resize(N); LCP.resize(N); for (int i = 0; i < N; i++) rnk[ind[i]] = i; for (int i = 0, k = 0; i < N; i++) { if (rnk[i] == N - 1) { LCP[rnk[i]] = k = 0; continue; } int j = ind[rnk[i] + 1]; while (i + k < N && j + k < N && S[i + k] == S[j + k]) k++; if ((LCP[rnk[i]] = k) > 0) k--; } } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Factorizes a array S into Lyndon words w1w2w3... where w1, w2, w3, ... are // in non-increasing order // Guaranteed to exist and is unique // A Lyndon word is lexicographically smaller than all of its nontrivial // suffixes // Template Arguments: // T: the type of each element in the array // Function Arguments: // S: a vector of type T // Return Value: a vector of integers representing the lengths of each factor, // where the sum of the values in the vector is equal to // the length of the array // In practice, has a small constant // Time Complexity: O(N) // Memory Complexity: O(N) // Tested: // https://cses.fi/problemset/task/1110/ template <class T> vector<int> lyndonFactorization(const vector<T> &S) { int N = S.size(); vector<int> ret; for (int i = 0; i < N;) { int j = i + 1, k = i; for (; j < N && S[k] <= S[j]; j++) k = S[k] < S[j] ? i : k + 1; for (; i <= k; i += j - k) ret.push_back(j - k); } return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../datastructures/FischerHeunStructure.h" using namespace std; // Computes the longest common prefix of two suffixes of an array // be using the Fischer Heun Structure over the LCP array generated by the // Suffix Array // Indices are 0-indexed and ranges are inclusive // Template Arguments: // SuffixArray: a generic suffix array to be used (should be either // SuffixArray or SAISSuffixArray) // Required Fields: // N: the length of the array // rnk: a vector of the ranks of the suffixes (rnk[i] is the rank of the // suffix starting from index i) // ind: a vector of the indices in the original array of the suffixes // sorted in lexicographical order (ind[i] is the index in original // array of the ith lexicographically smallest suffix) // LCP: a vector of the longest common prefixes between the suffixes when // sorted in lexicographical order (LCP[i] is the longest common prefix // of the ith and (i + 1)th lexicographically smallest suffix, with // LCP[N - 1] being 0) // Required Functions: // constructor(S): construts a suffix array from the array S // Constructor Arguments: // S: a vector of type SuffixArray::T // Fields: // SA: the associated suffix array constructed from the array // Functions: // lcpRnk(i, j): computes the longest common prefix of the ith and jth // lexicographically least suffixes // lcp(i, j): computes the longest common prefix of the suffixes starting // from index i and j // In practice, the constructor has a very small constant, lcp has a // moderate constant, still faster than using segment trees // Time Complexity: // constructor: time complexity of SuffixArray constructor // lcpRnk, lcp: O(1) // Memory Complexity: memory complexity of SuffixArray // Tested: // Fuzz and Stress Tested // https://dmoj.ca/problem/ccc20s3 template <class SuffixArray> struct LongestCommonPrefix { SuffixArray SA; FischerHeunStructure<int, greater<int>> FHS; LongestCommonPrefix(const vector<typename SuffixArray::T> &S) : SA(S), FHS(SA.LCP) {} int lcpRnk(int i, int j) { if (i > j) swap(i, j); return i == j ? int(SA.N) - SA.ind[j] : FHS.query(i, j - 1); } int lcp(int i, int j) { return lcpRnk(SA.rnk[i], SA.rnk[j]); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Suffix Array using Sadakane's algorithm to sort suffixes of an array in // lexicographical order // Indices are 0-indexed and ranges are inclusive // Template Arguments: // _T: the type of each element in the array // Constructor Arguments: // S: a vector of type _T // Fields: // T: the type of the character/element in the array // N: the length of the array // rnk: a vector of the ranks of the suffixes (rnk[i] is the rank of the // suffix starting from index i) // ind: a vector of the indices in the original array of the suffixes // sorted in lexicographical order (ind[i] is the index in original array // of the ith lexicographically smallest suffix) // LCP: a vector of the longest common prefixes between the suffixes when // sorted in lexicographical order (LCP[i] is the longest common prefix of // the ith and (i + 1)th lexicographically smallest suffix, with LCP[N - 1] // being 0) // In practice, has a very small constant, usually slower than // SAISSuffixArray.h // Time Complexity: // constructor: O(N (log N)^2) // Memory Complexity: O(N) // Tested: // Fuzz and Stress Tested // https://judge.yosupo.jp/problem/suffixarray // https://judge.yosupo.jp/problem/number_of_substrings // https://dmoj.ca/problem/coci06c5p6 // https://dmoj.ca/problem/ccc20s3 template <class _T> struct SuffixArray { using T = _T; int N; vector<int> ind, rnk, LCP; SuffixArray(const vector<T> &S) : N(S.size()), ind(N + 1), rnk(N + 1), LCP(N + 1) { vector<int> &tmp = LCP; iota(ind.begin(), ind.end(), 0); sort(ind.begin(), ind.begin() + N, [&] (int a, int b) { return S[a] < S[b]; }); rnk[ind[N]] = -1; for (int i = 0; i < N; i++) { rnk[ind[i]] = i > 0 && S[ind[i]] == S[ind[i - 1]] ? rnk[ind[i - 1]] : i; } for (int h = 1; h < N; h += h) for (int l = 0, r = 1; r <= N; r++) { if (rnk[ind[r - 1]] != rnk[ind[r]] && l + 1 < r) { sort(ind.begin() + l, ind.begin() + r, [&] (int a, int b) { return rnk[h + a] < rnk[h + b]; }); tmp[l] = l; for (int j = l + 1; j < r; j++) tmp[j] = rnk[h + ind[j - 1]] < rnk[h + ind[j]] ? j : tmp[j - 1]; for (l++; l < r; l++) rnk[ind[l]] = tmp[l]; } else if (rnk[ind[r - 1]] != rnk[ind[r]]) l++; } ind.pop_back(); rnk.pop_back(); tmp.pop_back(); for (int i = 0, k = 0; i < N; i++) { if (rnk[i] == N - 1) { LCP[rnk[i]] = k = 0; continue; } int j = ind[rnk[i] + 1]; while (i + k < N && j + k < N && S[i + k] == S[j + k]) k++; if ((LCP[rnk[i]] = k) > 0) k--; } } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Finds the longest common subarray of two arrays // Indices are 0-indexed // Template Arguments: // SuffixArray: a generic suffix array to be used (should be either // SuffixArray or SAISSuffixArray) // Required Fields: // N: the length of the array // rnk: a vector of the ranks of the suffixes (rnk[i] is the rank of the // suffix starting from index i) // ind: a vector of the indices in the original array of the suffixes // sorted in lexicographical order (ind[i] is the index in original // array of the ith lexicographically smallest suffix) // LCP: a vector of the longest common prefixes between the suffixes when // sorted in lexicographical order (LCP[i] is the longest common prefix // of the ith and (i + 1)th lexicographically smallest suffix, with // LCP[N - 1] being 0) // Required Functions: // constructor(S): construts a suffix array from the array S // Constructor Arguments: // A: the first vector of type SuffixArray::T // B: the second vector of type SuffixArray::T // sep: a separator character that does not appear in either array // Fields: // SA: the associated suffix array constructed from the array A, // concatenated with the separator, conatenated with the array B // lcs: the longest common subarray of A and B // In practice, the constructor has a very small constant // Time Complexity: // constructor: time complexity of SuffixArray for an array of // length N + M + 1 // Memory Complexity: memory complexity of SuffixArray for an array of // length N + M + 1 // Tested: // https://www.spoj.com/problems/LCS/ template <class SuffixArray> struct LongestCommonSubstringOfTwo { using T = typename SuffixArray::T; SuffixArray SA; vector<T> lcs; vector<T> init(vector<T> A, const vector<T> &B, T sep) { A.reserve(A.size() + B.size() + 1); A.push_back(sep); A.insert(A.end(), B.begin(), B.end()); return A; } LongestCommonSubstringOfTwo(const vector<T> &A, const vector<T> &B, T sep) : SA(init(A, B, sep)) { pair<int, int> mx(-1, -1); int N = A.size(); for (int i = 0; i < N + int(B.size()); i++) if (SA.ind[i] != N && SA.ind[i + 1] != N && (SA.ind[i] < N) != (SA.ind[i + 1] < N)) mx = max(mx, make_pair(SA.LCP[i], SA.ind[i])); if (mx.first != -1) { lcs.reserve(mx.first); for (int i = 0; i < mx.first; i++) { int j = mx.second + i; lcs.push_back(j < N ? A[j] : B[j - 1 - N]); } } } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../math/ModularArithmetic.h" #include "../utils/Random.h" using namespace std; // Computes the hash of a 2D array to allow for easy computation of // submatrix hashes // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // HTYPE: the type of the hash // HASHES: the number of hashes to compute // Construtor Arguments: // A: the elements in the 2D array // offset: the amount to subtract from each element, a - offset + 1 should be // positive // ROWBASE: array<HTYPE, HASHES> that contains the base for the rows for // each hash, must be less than the repective mod and positive (preferably // in the range [mod / 4, mod / 4 * 3]) // COLBASE: array<HTYPE, HASHES> that contains the base for the columns for // each hash, must be less than the repective mod and positive (preferably // in the range [mod / 4, mod / 4 * 3]) // MOD: array<HTYPE, HASHES> that contains the mods for each hash, should // be large (products should be least (NM)^2) and prime // Fields: // N: the number of rows in the 2D array // M: the number of columns in the 2D array // ROWBASE: array<HTYPE, HASHES> with the bases for the rows for each hash // COLBASE: array<HTYPE, HASHES> with the bases for the columns for each hash // MOD: array<HTYPE, HASHES> with the mods for each hash // H: a vector of vectors of array<HTYPE, HASHES> of size N + 1 by M + 1 with // the suffix hashes starting at each cell // ROWPOW: a vector of array<HTYPE, HASHES> of size N + 1 with the ith // representing row_base^i modulo mod // COLPOW: a vector of array<HTYPE, HASHES> of size M + 1 with the jth // representing col_base^j modulo mod // Functions: // initBase(MOD): returns an array<HTYPE, HASHES> with randomly initialized // values for the bases for each mod in the range [mod / 4, mod / 4 * 3] // getHash(u, d, l, r): returns a type HASH with the hashes in the submatrix // [u, d] x [l, r] // In practice, has a moderate constant // Time Complexity: // constructor: O(NM HASHES) // getHash: O(HASHES) // Memory Complexity: O(N HASHES) template <class T, class HTYPE, const int HASHES> struct Hashing2D { using arr = array<HTYPE, HASHES>; int N, M; arr ROWBASE, COLBASE, MOD; vector<vector<arr>> H; vector<arr> ROWPOW, COLPOW; struct HASH : public arr { int rows, cols; }; Hashing2D(const vector<vector<T>> &A, T offset, const arr &ROWBASE, const arr &COLBASE, const arr &MOD) : N(A.size()), M(N == 0 ? 0 : A[0].size()), ROWBASE(ROWBASE), COLBASE(COLBASE), MOD(MOD), H(N + 1, vector<arr>(M + 1)), ROWPOW(N + 1), COLPOW(M + 1) { ROWPOW[0].fill(HTYPE(1)); COLPOW[0].fill(HTYPE(1)); for (int i = 0; i <= N; i++) H[i][M].fill(HTYPE()); for (int j = 0; j <= M; j++) H[N][j].fill(HTYPE()); for (int i = 1; i <= N; i++) for (int h = 0; h < HASHES; h++) ROWPOW[i][h] = mulMod(ROWPOW[i - 1][h], ROWBASE[h], MOD[h]); for (int j = 1; j <= M; j++) for (int h = 0; h < HASHES; h++) COLPOW[j][h] = mulMod(COLPOW[j - 1][h], COLBASE[h], MOD[h]); for (int i = N - 1; i >= 0; i--) for (int j = M - 1; j >= 0; j--) for (int h = 0; h < HASHES; h++) { H[i][j][h] = posMod(HTYPE(A[i][j] - offset) + HTYPE(1), MOD[h]); H[i][j][h] = addMod(H[i][j][h], mulMod(H[i + 1][j][h], ROWBASE[h], MOD[h]), MOD[h]); H[i][j][h] = addMod(H[i][j][h], mulMod(H[i][j + 1][h], COLBASE[h], MOD[h]), MOD[h]); H[i][j][h] = subMod(H[i][j][h], mulMod(mulMod(H[i + 1][j + 1][h], ROWBASE[h], MOD[h]), COLBASE[h], MOD[h]), MOD[h]); } } static arr initBase(const arr &MOD) { arr base; for (int h = 0; h < HASHES; h++) base[h] = uniform_int_distribution<HTYPE>( MOD[h] / 4, MOD[h] / 4 * 3)(rng64); return base; } Hashing2D(const vector<vector<T>> &A, T offset, const arr &MOD) : Hashing2D(A, offset, initBase(MOD), initBase(MOD), MOD) {} HASH getHash(int u, int d, int l, int r) { HASH ret; ret.rows = ++d - u; ret.cols = ++r - l; for (int h = 0; h < HASHES; h++) { ret[h] = H[u][l][h]; ret[h] = subMod(ret[h], mulMod(H[d][l][h], ROWPOW[d - u][h], MOD[h]), MOD[h]); ret[h] = subMod(ret[h], mulMod(H[u][r][h], COLPOW[r - l][h], MOD[h]), MOD[h]); ret[h] = addMod(ret[h], mulMod(mulMod(H[d][r][h], ROWPOW[d - u][h], MOD[h]), COLPOW[r - l][h], MOD[h]), MOD[h]); } return ret; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Trie Node backed by a map // Template Arguments: // _T: the type of the element in the string/array for the Trie // Fields: // T: the data type of each element in the string/array // link: a link to the parent in the trie // Functions: // hasEdge(a): returns whether there exists an edge to an adjacent node // with the element a // getEdge(a): returns the index of the other node on the // incident edge with the element a // setEdge(a, n): sets the other node on the incident edge // with the element a to n // Time Complexity: // constructor: O(1) // hasEdge, getEdge, setEdge: O(log E) where E is the number of edges // incident to this node // Memory Complexity: O(E) where E is the number of edges incident to this node // Tested: // https://csacademy.com/contest/round-77/task/expected-lcp/ template <class _T> struct TrieMapNode { using T = _T; int link; map<T, int> to; TrieMapNode() : link(-1) {} bool hasEdge(const T &a) const { return to.count(a); } int getEdge(const T &a) const { return to.at(a); } void setEdge(const T &a, int n) { to[a] = n; } }; // Trie Node backed by an array // Template Arguments: // _T: the type of the element in the string/array for the Trie // ALPHABET_SIZE: the size of the alphabet // OFFSET: the offset for the start of the alphabet // Fields: // T: the data type of each element in the string/array // link: a link to the parent in the trie // Functions: // hasEdge(a): returns whether there exists an edge to an adjacent node // with the element a // getEdge(a): returns the index of the other node on the // incident edge with the element a // setEdge(a, n): sets the other node on the incident edge // with the element a to n // Time Complexity: // constructor: O(ALPHABET_SIZE) // hasEdge, getEdge, setEdge: O(1) // Memory Complexity: O(ALPHABET_SIZE) // Tested: // https://csacademy.com/contest/round-77/task/expected-lcp/ template <class _T, const int ALPHABET_SIZE, const int OFFSET> struct TrieArrayNode { using T = _T; int link; array<int, ALPHABET_SIZE> to; TrieArrayNode() : link(-1) { to.fill(-1); } bool hasEdge(const T &a) const { return to[a - OFFSET] != -1; } int getEdge(const T &a) const { return to[a - OFFSET]; } void setEdge(const T &a, int n) { to[a - OFFSET] = n; } }; // Trie with the root node at 0 // Template Arguments: // Node: a node class // Required Fields: // T: the data type of each element in the string/array // link: a link to the parent in the trie // Required Functions: // constructor(): initializes the node with a with no links or edges // hasEdge(a): returns whether there exists an edge to an adjacent node // with the element a // getEdge(a): returns the index of the other node on the // incident edge with the element a // setEdge(a, n): sets the other node on the incident edge // with the element a to n // Fields: // TR: the vector of all nodes in the automaton // last: the last node representing the current string // Functions: // add(a): adds the element a to the trie // terminate(): terminates the current word, returning to the root (which // allows for another word to be added with add(a)) // Time Complexity: // constructor: time complexity of node constructor // add: O(1) + time complexity of node constructor // + time complexity of getEdge in Node // terminate: O(1) // Memory Complexity: O(N) * memory complexity of node, after N calls to add // Tested: // https://csacademy.com/contest/round-77/task/expected-lcp/ template <class Node> struct Trie { using T = typename Node::T; vector<Node> TR; int last; Trie() : TR(1, Node()), last(0) {} void add(const T &a) { if (TR[last].hasEdge(a)) last = TR[last].getEdge(a); else { int u = TR.size(); TR.emplace_back(); TR[TR[u].link = last].setEdge(a, u); last = u; } } void terminate() { last = 0; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Suffix Automaton Node backed by a map // Template Arguments: // _T: the type of the element in the string/array for the Suffix Automaton // Constructor Arguments: // len: the length of the longest substring represented by this node // Fields: // T: the data type of each element in the string/array // len: the length of the longest substring this node represents // link: the index of the suffix link of this node (the node with the // longest suffix of this node) // Functions: // hasEdge(a): returns whether there exists an edge to an adjacent node // with the element a // getEdge(a): returns the index of the other node on the // incident edge with the element a // setEdge(a, n): sets the other node on the incident edge // with the element a to n // Time Complexity: // constructor: O(1) // hasEdge, getEdge, setEdge: O(log E) where E is the number of edges // incident to this node // Memory Complexity: O(E) where E is the number of edges incident to this node // Tested: // https://www.spoj.com/problems/LCS/ // https://open.kattis.com/problems/stringmultimatching template <class _T> struct SAMMapNode { using T = _T; int len, link; map<T, int> to; SAMMapNode(int len) : len(len), link(-1) {} bool hasEdge(const T &a) const { return to.count(a); } int getEdge(const T &a) const { return to.at(a); } void setEdge(const T &a, int n) { to[a] = n; } }; // Suffix Automaton Node backed by an array // Template Arguments: // _T: the type of the element in the string/array for the Suffix Automaton // ALPHABET_SIZE: the size of the alphabet // OFFSET: the offset for the start of the alphabet // Constructor Arguments: // len: the length of the longest substring represented by this node // Fields: // T: the data type of each element in the string/array // len: the length of the longest substring this node represents // link: the index of the suffix link of this node (the node with the // longest suffix of this node) // Functions: // hasEdge(a): returns whether there exists an edge to an adjacent node // with the element a // getEdge(a): returns the index of the other node on the // incident edge with the element a // setEdge(a, n): sets the other node on the incident edge // with the element a to n // Time Complexity: // constructor: O(ALPHABET_SIZE) // hasEdge, getEdge, setEdge: O(1) // Memory Complexity: O(ALPHABET_SIZE) // Tested: // https://www.spoj.com/problems/LCS/ // https://dmoj.ca/problem/coci14c5p6 // https://dmoj.ca/problem/coci11c5p6 template <class _T, const int ALPHABET_SIZE, const _T OFFSET> struct SAMArrayNode { using T = _T; int len, link; array<int, ALPHABET_SIZE> to; SAMArrayNode(int len) : len(len), link(-1) { to.fill(-1); } bool hasEdge(const T &a) const { return to[a - OFFSET] != -1; } int getEdge(const T &a) const { return to[a - OFFSET]; } void setEdge(const T &a, int n) { to[a - OFFSET] = n; } }; // Suffix Automaton with the root node at 0 // Each distinct path from the root is a substring of the set of words inserted // Template Arguments: // Node: a node class // Required Fields: // T: the data type of each element in the string/array // len: the length of the longest substring this node represents // link: the index of the suffix link of this node (the node with the // longest suffix of this node) // Required Functions: // constructor(len): initializes the node with a length of len with no // links or edges // hasEdge(a): returns whether there exists an edge to an adjacent node // with the element a // getEdge(a): returns the index of the other node on the // incident edge with the element a // setEdge(a, n): sets the other node on the incident edge // with the element a to n // Fields: // TR: the vector of all nodes in the automaton // last: the last node representing the current string // Functions: // add(a): adds the element a to the automaton // terminate(): terminates the current word, returning to the root (which // allows for another word to be added with add(a)) // In practice, has a moderate constant // Time Complexity: // constructor: time complexity of node constructor // add: O(1) amortized + time complexity of node constructor // + time complexity of getEdge in Node // terminate: O(1) // Memory Complexity: O(N) * memory complexity of node, after N calls to add // Tested: // https://www.spoj.com/problems/LCS/ // https://dmoj.ca/problem/coci14c5p6 // https://open.kattis.com/problems/stringmultimatching // https://dmoj.ca/problem/coci11c5p6 template <class Node> struct SuffixAutomaton { using T = typename Node::T; vector<Node> TR; int last; SuffixAutomaton() : TR(1, Node(0)), last(0) {} void add(const T &a) { int u = -1; if (!TR[last].hasEdge(a)) { u = TR.size(); TR.emplace_back(TR[last].len + 1); for (; last != -1 && !TR[last].hasEdge(a); last = TR[last].link) TR[last].setEdge(a, u); if (last == -1) { TR[last = u].link = 0; return; } } int p = TR[last].getEdge(a); if (TR[p].len == TR[last].len + 1) { (u == -1 ? last : TR[last = u].link) = p; return; } int q = TR.size(); TR.push_back(TR[p]); TR[q].len = TR[last].len + 1; TR[p].link = q; if (u != -1) TR[u].link = q; while (last != -1 && TR[last].hasEdge(a) && TR[last].getEdge(a) == p) { TR[last].setEdge(a, q); last = TR[last].link; } last = u == -1 ? q : u; } void terminate() { last = 0; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Finds the minimum lexicographical rotation of an array // Template Arguments: // T: the type of each element in the array // Function Arguments: // S: a vector of type T // Return Value: the index of the first element of the minimum // lexicographical rotation of the array // In practice, has a small constant // Time Complexity: O(N) // Memory Complexity: O(1) // Tested: // https://cses.fi/problemset/task/1110/ template <class T> int minRotation(const vector<T> &S) { int N = S.size(), i = 0; auto ind = [&] (int i) { return i < N ? i : i - N; }; for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) { auto &a = S[ind(i + k)], &b = S[ind(j + k)]; if (i + k == j || a < b) { j += max(0, k - 1); break; } if (a > b) { i = j; break; } } return i; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../math/ModularArithmetic.h" #include "../utils/Random.h" using namespace std; // Computes the hash of an array to allow for easy computation of // subarray hashes // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // HTYPE: the type of the hash // HASHES: the number of hashes to compute // Construtor Arguments: // S: the elements in the array // offset: the amount to subtract from each element, a - offset + 1 should be // positive // BASE: array<HTYPE, HASHES> that contains the base for each hash, must // be less than the repective mod and positive (preferably in the range // [mod / 4, mod / 4 * 3]) // MOD: array<HTYPE, HASHES> that contains the mods for each hash, should // be large (products should be least N^2) and prime // Fields: // N: the length of the array // BASE: array<HTYPE, HASHES> with the bases for each hash // MOD: array<HTYPE, HASHES> with the mods for each hash // H: a vector of array<HTYPE, HASHES> of size N + 1 with the suffix hashes // starting at each index // POW: a vector of array<HTYPE, HASHES> of size N + 1 with the ith // representing base^i modulo mod // Functions: // initBase(MOD): returns an array<HTYPE, HASHES> with randomly initialized // values for the bases for each mod in the range [mod / 4, mod / 4 * 3] // getHash(l, r): returns a type HASH with the hashes in the subarray [l, r] // merge(h1, h2): returns a type HASH of 2 hashes merged together as if // the subarray represented by h2 was immediately after h1 // concat(l1, r1, l2, r2): returns a type HASH of // the subarray [l1, r1] contactenated with the subarray [l2, r2] // In practice, has a moderate constant // Time Complexity: // constructor: O(N HASHES) // getHash, merge, concat: O(HASHES) // Memory Complexity: O(N HASHES) // Tested: // https://dmoj.ca/problem/globexcup19j5hard template <class T, class HTYPE, const int HASHES> struct Hashing { using arr = array<HTYPE, HASHES>; int N; arr BASE, MOD; vector<arr> H, POW; struct HASH : public arr { int len; }; Hashing(const vector<T> &S, T offset, const arr &BASE, const arr &MOD) : N(S.size()), BASE(BASE), MOD(MOD), H(N + 1), POW(N + 1) { POW[0].fill(HTYPE(1)); H[N].fill(HTYPE()); for (int i = 1; i <= N; i++) for (int h = 0; h < HASHES; h++) POW[i][h] = mulMod(POW[i - 1][h], BASE[h], MOD[h]); for (int i = N - 1; i >= 0; i--) for (int h = 0; h < HASHES; h++) H[i][h] = addMod(mulMod(H[i + 1][h], BASE[h], MOD[h]), posMod(HTYPE(S[i] - offset) + HTYPE(1), MOD[h]), MOD[h]); } static arr initBase(const arr &MOD) { arr base; for (int h = 0; h < HASHES; h++) base[h] = uniform_int_distribution<HTYPE>( MOD[h] / 4, MOD[h] / 4 * 3)(rng64); return base; } Hashing(const vector<T> &S, T offset, const arr &MOD) : Hashing(S, offset, initBase(MOD), MOD) {} HASH getHash(int l, int r) { HASH ret; ret.len = ++r - l; for (int h = 0; h < HASHES; h++) ret[h] = subMod(H[l][h], mulMod(H[r][h], POW[r - l][h], MOD[h]), MOD[h]); return ret; } HASH merge(const HASH &h1, const HASH &h2) { HASH ret; ret.len = h1.len + h2.len; for (int h = 0; h < HASHES; h++) ret[h] = addMod(h1[h], mulMod(h2[h], POW[h1.len][h], MOD[h]), MOD[h]); return ret; } HASH concat(int l1, int r1, int l2, int r2) { return merge(getHash(l1, r1), getHash(l2, r2)); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Finds the longest common subarray of multiple arrays // Indices are 0-indexed // Template Arguments: // SuffixArray: a generic suffix array to be used (should be either // SuffixArray or SAISSuffixArray) // Required Fields: // N: the length of the array // rnk: a vector of the ranks of the suffixes (rnk[i] is the rank of the // suffix starting from index i) // ind: a vector of the indices in the original array of the suffixes // sorted in lexicographical order (ind[i] is the index in original // array of the ith lexicographically smallest suffix) // LCP: a vector of the longest common prefixes between the suffixes when // sorted in lexicographical order (LCP[i] is the longest common prefix // of the ith and (i + 1)th lexicographically smallest suffix, with // LCP[N - 1] being 0) // Required Functions: // constructor(S): construts a suffix array from the array S // Constructor Arguments: // A: a vector of the arrays // sep: a vector of max(0, A.size() - 1) different separator character // that do not appear in any of the arrays // Fields: // SA: the associated suffix array constructed from the arrays // concatenated together, separated by the separator character // lcs: the longest common subarray of all arrays // In practice, the constructor has a very small constant // Time Complexity: // constructor: time complexity of SuffixArray for the length of the // concatenated array // Memory Complexity: memory complexity of SuffixArray for the length of the // concatenated array // Tested: // https://www.spoj.com/problems/LCS2/ // https://open.kattis.com/problems/longestcommonsubstring template <class SuffixArray> struct LongestCommonSubstring { using T = typename SuffixArray::T; vector<int> ind; vector<T> lcs; vector<T> S; SuffixArray SA; vector<T> init(const vector<vector<T>> &A, const vector<T> &sep) { int len = max(0, int(A.size()) - 1); for (auto &&a : A) len += a.size(); vector<T> S; S.reserve(len); ind.resize(len, -1); for (int i = 0; i < int(A.size()); i++) { if (i > 0) S.push_back(sep[i - 1]); fill(ind.begin() + S.size(), ind.begin() + S.size() + A[i].size(), i); S.insert(S.end(), A[i].begin(), A[i].end()); } return S; } LongestCommonSubstring(const vector<vector<T>> &A, const vector<T> &sep) : ind(), S(init(A, sep)), SA(S) { int K = A.size(); if (K == 0) return; if (K == 1) { lcs = A[0]; return; } vector<int> freq(K, 0), dq(SA.N); pair<int, int> mx(-1, -1); for (int l = 0, r = 0, front = 0, back = 0, cnt = 0; r < SA.N; r++) { if (ind[SA.ind[r]] != -1) { cnt += freq[ind[SA.ind[r]]]++ == 0; if (cnt == K) { while (true) { int i = ind[SA.ind[l]]; if (i != -1 && freq[i] == 1) break; l++; if (i != -1) freq[i]--; } while (dq[front] < l) front++; mx = max(mx, make_pair(SA.LCP[dq[front]], SA.ind[dq[front]])); } } while (front < back && SA.LCP[dq[back - 1]] >= SA.LCP[r]) back--; dq[back++] = r; } if (mx.first != -1) { lcs.reserve(mx.first); for (int i = 0; i < mx.first; i++) lcs.push_back(S[mx.second + i]); } } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Computes the longest palindromic subarray centered at each half index // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element in the array // Constructor Arguments: // S: a vector of type T // Fields: // N: the length of the array // p: the length of the longest palindromic substring/subarray centered // at each half index (including paddings at each end) // Functions: // lps(): returns a pair containing the starting index and length (in the // original string) of the longest palindromic substring/subarray, picking // the earliest string if there are multiple of the same length // lps(i): returns a pair containing the starting index and length (in the // original string) of the longest palindromic substring/subarray centered // at index i/2.0 // In practice, has a moderate constant // Time Complexity: // constructor: O(N) // lps(): O(N) // lps(i): O(1) // Memory Complexity: O(S) // Tested: // https://judge.yosupo.jp/problem/enumerate_palindromes // https://www.spoj.com/problems/LPS/ template <class T> struct ManacherPalindrome { int N; vector<int> p; ManacherPalindrome(const vector<T> &S) : N(S.size()), p(N * 2 + 1, 0) { vector<T> SS(N * 2 + 1, T()); for (int i = 0; i < N; i++) SS[i * 2 + 1] = S[i]; for (int i = 0, cen = 0, mxr = 0; i < N * 2 + 1; i++) { if (mxr > i) p[i] = min(mxr - i, p[cen * 2 - i]); int l = i - p[i], r = i + p[i]; for (; l > 0 && r < N * 2 && SS[l - 1] == SS[r + 1]; l--, r++) p[i]++; if (r > mxr) { cen = i; mxr = r; } } } pair<int, int> lps() { int len = 0, cen = 0; for (int i = 0; i < N * 2 + 1; i++) if (p[i] > len) len = p[cen = i]; return make_pair((cen - len) / 2, len); } pair<int, int> lps(int i) { int len = p[i + 1], cen = i + 1; return make_pair((cen - len) / 2, len); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Two players alternate taking coins from either end of a row. If both players // play optimally, what is the value of player 1's total minus // player 2's total? // The standard dp recurrence is // dp[l][r] = l > r ? 0 : max(A[l] - dp[l + 1][r], A[r] - dp[l][r - 1]) // This implementation is generalized to support any number of rows, possibly // with a fixed endpoint on the right // The value of a single player can be recovered by solving the system of // equations: P1 + P2 = A, P1 - P2 = B // Template Arguments: // T: the type of the value of each coin // Function Arguments: // A: a vector of vectors of type T, with each vector representing a row // fixed: a vector of booleans of the same length of A representing whether // the right endpoint of that row is fixed // Return Value: player 1's total minus player 2's total // In practice, has a small constant // Time Complexity: O(N log N) for N total coins or O(N) if there is a // single row // Memory Complexity: O(N) for N total coins // Tested: // https://dmoj.ca/problem/ahardergame // https://atcoder.jp/contests/dp/tasks/dp_l template <class T> T termity(const vector<vector<T>> &A, const vector<bool> &fixed) { int N = 0; T ret = T(); for (auto &&a : A) N += a.size(); int mult = N % 2 == 0 ? 1 : -1; vector<T> B; B.reserve(N); for (int i = 0; i < int(A.size()); i++) { int front = B.size(); for (auto &&a : A[i]) { B.push_back(a); while (int(B.size()) - front >= 3 && B[B.size() - 3] <= B[B.size() - 2] && B[B.size() - 2] >= B[B.size() - 1]) { B[B.size() - 3] -= B[B.size() - 2] - B[B.size() - 1]; B.pop_back(); B.pop_back(); } } if (fixed[i]) while (int(B.size()) - front >= 2 && B[B.size() - 2] <= B[B.size() - 1]) { ret += mult * (B[B.size() - 2] - B[B.size() - 1]); B.pop_back(); B.pop_back(); } } if (int(A.size()) == 1) { for (int l = 0, r = int(B.size()) - 1, m = 1; l <= r; m *= -1) { if (B[l] >= B[r]) ret += m * B[l++]; else ret += m * B[r--]; } } else { sort(B.begin(), B.end(), greater<T>()); for (int i = 0, m = 1; i < int(B.size()); i++, m *= -1) ret += m * B[i]; } return ret; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Solves the maximum disjoint intervals problem // Given a set of intervals in the form [L, R], find the maximum number of // disjoint intervals // Maximum number of disjoint intervals is equivalent to the minimum number of // points to cover each interval (with the points being the right endpoints // of the disjoint intervals) // Range is modified in-place // Template Arguments: // T: the type of the endpoints of the intervals // Cmp: the comparator to compare two points // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Function Arguments: // A: a reference to a vector of pairs with the first element being the // inclusive left bound of the interval and the second element being the // inclusive right bound of the interval // cmp: an instance of the Cmp struct // Return Value: a reference to the modified vector // In practice, has a very small constant // Time Complexity: O(N log N) // Memory Complexity: O(1) // Tested: // https://codeforces.com/contest/1141/problem/F2 // https://oj.uz/problem/view/COCI21_planine template <class T, class Cmp = less<T>> vector<pair<T, T>> &maxDisjointIntervals(vector<pair<T, T>> &A, Cmp cmp = Cmp()) { sort(A.begin(), A.end(), [&] (const pair<T, T> &a, const pair<T, T> &b) { return cmp(a.second, b.second); }); int i = 0; for (int l = 0, r = 0, N = A.size(); l < N; l = r, i++) { A[i] = A[l]; for (r = l + 1; r < N && !cmp(A[i].second, A[r].first); r++); } A.erase(A.begin() + i, A.end()); return A; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Solves the minimum interval cover problem // Given a set of intervals in the form [L, R], find the minimum number of // intervals to cover a target interval // Range is modified in-place // Template Arguments // T: the type of the endpoints of the intervals // Cmp: the comparator to compare two points // Required Functions: // operator (a, b): returns true if and only if a compares less than b // T: the type of the points // Function Arguments: // A: a reference to a vector of pairs with the first element being the // inclusive left bound of the interval and the second element being the // inclusive right bound of the interval // target: the target interval to cover with the first element being the // inclusive left bound of the target interval and the second element // being the inclusive right bound of the interval // cmp: an instance of the Cmp struct // Return Value: a reference to the modified vector // In practice, has a very small constant // Time Complexity: O(N log N) // Memory Complexity: O(1) // Tested: // https://open.kattis.com/problems/intervalcover template <class T, class Cmp = less<T>> vector<pair<T, T>> &minIntervalCover(vector<pair<T, T>> &A, pair<T, T> target, Cmp cmp = Cmp()) { sort(A.begin(), A.end(), [&] (const pair<T, T> &a, const pair<T, T> &b) { return cmp(a.first, b.first); }); bool first = true; int i = 0, N = A.size(); for (int j = 0; j < N && (first || cmp(target.first, target.second));) { if (cmp(target.first, A[j].first)) { A.clear(); return A; } else { for (A[i] = A[j]; j < N && !cmp(target.first, A[j].first); j++) if (cmp(A[i].second, A[j].second)) A[i] = A[j]; target.first = A[i++].second; first = false; } } if (first || cmp(target.first, target.second)) i = 0; A.erase(A.begin() + i, A.end()); return A; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> // Unsyncs the C++ and C std output streams and unties cin to // speed up standard input void unSyncUntie() { std::ios::sync_with_stdio(0); std::cin.tie(0); } // Functions for fast IO namespace IO { #define INTERACTIVE_INPUT 0 template <class T> struct is_iterator { template <class U, typename std::enable_if< !std::is_convertible<U, const char *>::value, int>::type = 0> static constexpr auto has_indirection(int) ->decltype(*std::declval<U>(), bool()) { return true; } template <class> static constexpr bool has_indirection(long) { return false; } static constexpr bool value = has_indirection<T>(0); }; constexpr const int _bufSize = 1 << 16, _maxNumLength = 128; char _inputBuf[_bufSize + 1], *_inputPtr = _inputBuf, _sign, _c, _last = -1; char *_tempInputBuf = nullptr, _tempOutputBuf[_maxNumLength]; char _outputBuf[_bufSize], _numBuf[_maxNumLength], _fill = ' '; int _cur, _tempOutputPtr = 0, _outputPtr = 0, _cnt, _numPtr = 0; int _width = 0, _precision = 9; const char *_delimiter = " "; unsigned long long _precisionBase = 1000000000; FILE *_input = stdin, *_output = stdout, *_error = stderr; #if INTERACTIVE_INPUT char _getchar() { return _last = getchar(); } #else char _getchar() { if (!*_inputPtr) _inputBuf[fread(_inputPtr = _inputBuf, 1, _bufSize, _input)] = '\0'; return _last = *_inputPtr++; } #endif char _getcharskipr() { while (_getchar() == '\r'); return _last; } template <class I> void _readSigned(I &x) { while ((x = _getchar()) <= ' '); if ((_sign = x == '-')) x = _getchar(); for (x -= '0'; (_c = _getchar()) >= '0'; x = x * 10 + _c - '0'); if (_sign) x = -x; } template <class UI> void _readUnsigned(UI &x) { while ((x = _getchar()) <= ' '); for (x -= '0'; (_c = _getchar()) >= '0'; x = x * 10 + _c - '0'); } template <class F> void _readFloatingPoint(F &x) { for (x = 0; (_c = _getchar()) <= ' ';); if ((_sign = _c == '-')) _c = _getchar(); if (_c >= '0') for (x = _c - '0'; (_c = _getchar()) >= '0'; x = x * 10 + _c - '0'); if (_c == '.') { F _div = 1.0; for (; (_c = _getchar()) >= '0'; x += (_c - '0') / (_div *= 10)); } if (_sign) x = -x; } void setLength(int x) { if (_tempInputBuf) delete[](_tempInputBuf); _tempInputBuf = new char[x + 1]; } template <class I> typename std::enable_if<std::is_integral<I>::value && std::is_signed<I>::value>::type read(I &x) { _readSigned(x); } template <class UI> typename std::enable_if<std::is_integral<UI>::value && std::is_unsigned<UI>::value>::type read(UI &x) { _readUnsigned(x); } #if __SIZEOF_INT128__ void read(__int128_t &x) { _readSigned(x); } void read(__uint128_t &x) { _readUnsigned(x); } #endif template <class F> typename std::enable_if<std::is_floating_point<F>::value>::type read(F &x) { _readFloatingPoint(x); } void read(char &x) { while ((x = _getchar()) <= ' '); } void read(char *x) { _cur = 0; do { _c = _getchar(); } while (_c <= ' '); do { x[_cur++] = _c; } while ((_c = _getchar()) > ' '); x[_cur] = '\0'; } void readln(char *x) { if (_last == '\r') _getcharskipr(); for (_cur = 0; (_c = _getcharskipr()) != '\n' && _c; x[_cur++] = _c); x[_cur] = '\0'; } void read(std::string &x) { if (!_tempInputBuf) assert(0); read(_tempInputBuf); x = std::string(_tempInputBuf, _cur); } void readln(std::string &x) { if (!_tempInputBuf) assert(0); readln(_tempInputBuf); x = std::string(_tempInputBuf, _cur); } template <class T> typename std::enable_if< is_iterator<typename T::iterator>::value>::type read(T &x); template <class T1, class T2> void read(std::pair<T1, T2> &x) { read(x.first); read(x.second); } template <class T> void read(std::complex<T> &x) { T _re, _im; read(_re); read(_im); x.real(_re); x.imag(_im); } template <class T, class ...Ts> void read(T &x, Ts &&...xs); template <class It> typename std::enable_if<is_iterator<It>::value>::type read(It st, It en) { for (It _i = st; _i != en; _i++) read(*_i); } template <class It, class ...Ts> typename std::enable_if<is_iterator<It>::value>::type read( It st, It en, Ts &&...xs) { read(st, en); read(std::forward<Ts>(xs)...); } template <class T> typename std::enable_if< is_iterator<typename T::iterator>::value>::type read(T &x) { for (auto &&_i : x) read(_i); } template <class T, class...Ts> void read(T &x, Ts &&...xs) { read(x); read(std::forward<Ts>(xs)...); } void setInput(FILE *file) { *(_inputPtr = _inputBuf) = 0; _input = file; } void setInput(const std::string &s) { *(_inputPtr = _inputBuf) = 0; _input = fopen(s.c_str(), "r"); } int _flushBuf() { fwrite(_outputBuf, 1, _outputPtr, _output); return _outputPtr = 0; } void flush() { _flushBuf(); fflush(_output); } int _putchar(char x) { _outputBuf[_outputPtr == _bufSize ? _flushBuf() : _outputPtr] = x; return _outputPtr++; } void _writeTempBuf(char x) { _tempOutputBuf[_tempOutputPtr++] = x; } void _writeOutput() { for (int _i = 0; _i < _tempOutputPtr; _putchar(_tempOutputBuf[_i++])); _tempOutputPtr = 0; } void _fillBuf(int x) { for (int _i = 0; _i < x; _i++) _putchar(_fill); } void _flushNumBuf() { for (; _numPtr; _writeTempBuf(_numBuf[--_numPtr])); } void _flushTempBuf() { int _tempLen = _tempOutputPtr; _fillBuf(_width - _tempLen); _writeOutput(); _fillBuf(-_width - _tempLen); } void setPrecision(int x) { _precision = x; _precisionBase = 1; for (int _i = 0; _i < x; _i++, _precisionBase *= 10); } void setWidth(int x) { _width = x; } void setFill(char x) { _fill = x; } void setDelimiter(const char *x) { _delimiter = x; } void setDelimiter(const std::string &x) { _delimiter = x.c_str(); } void writeDelimiter() { for (const char *_p = _delimiter; *_p; _putchar(*_p++)); } template <class T> void _writeNum(const T &x, int digits) { _cnt = 0; for (T _y = x; _y; _y /= 10, _cnt++) _numBuf[_numPtr++] = '0' + _y % 10; for (; _cnt < digits; _cnt++) _numBuf[_numPtr++] = '0'; _flushNumBuf(); } template <class F> void _writeFloatingPoint(const F &x) { unsigned long long _I = x, _F = (x - _I) * _precisionBase + F(0.5); if (_F >= _precisionBase) { _I++; _F = 0; } _writeNum(_I, 1); _writeTempBuf('.'); _writeNum(_F, _precision); } void write(const bool &x) { if (x) _writeTempBuf('1'); else _writeTempBuf('0'); _flushTempBuf(); } void write(const char &x) { _writeTempBuf(x); _flushTempBuf(); } void write(const char *x) { int _slen = strlen(x); _fillBuf(_width - _slen); for (const char *_p = x; *_p; _putchar(*_p++)); _fillBuf(-_width - _slen); } void write(const std::string &x) { _fillBuf(_width - int(x.length())); for (int _i = 0; _i < int(x.length()); _putchar(x[_i++])); _fillBuf(-_width - int(x.length())); } template <class I> typename std::enable_if<std::is_integral<I>::value && std::is_signed<I>::value>::type write(const I &x) { using UI = typename std::make_unsigned<I>::type; if (x < 0) { _writeTempBuf('-'); _writeNum(UI(-x), 1); } else { _writeNum(UI(x), 1); } _flushTempBuf(); } template <class UI> typename std::enable_if<std::is_integral<UI>::value && std::is_unsigned<UI>::value >::type write(const UI &x) { _writeNum(x, 1); _flushTempBuf(); } template <class F> typename std::enable_if<std::is_floating_point<F>::value>::type write( const F &x) { if (std::isnan(x)) write("NaN"); else if (std::isinf(x)) write("Inf"); else if (x < 0) { _writeTempBuf('-'); _writeFloatingPoint(-x); } else _writeFloatingPoint(x); _flushTempBuf(); } #if __SIZEOF_INT128__ void write(const __int128_t &x) { if (x < 0) { _writeTempBuf('-'); _writeNum(__uint128_t(-x), 1); } else _writeNum(__uint128_t(x), 1); _flushTempBuf(); } void write(const __uint128_t &x) { _writeNum(x, 1); _flushTempBuf(); } #endif template <class T> typename std::enable_if< is_iterator<typename T::iterator>::value>::type write(const T &x); template <class T1, class T2> void write(const std::pair<T1, T2> &x) { write(x.first); writeDelimiter(); write(x.second); } template <class T> void write(const std::complex<T> &x) { write(x.real()); writeDelimiter(); write(x.imag()); } template <class T, class ...Ts> void write(const T &x, Ts &&...xs); template <class It> typename std::enable_if<is_iterator<It>::value>::type write(It st, It en) { bool _first = 1; for (It _i = st; _i != en; _i++) { if (_first) _first = 0; else writeDelimiter(); write(*_i); } } template <class It, class ...Ts> typename std::enable_if<is_iterator<It>::value>::type write( It st, It en, Ts &&...xs) { write(st, en); writeDelimiter(); write(std::forward<Ts>(xs)...); } template <class T> typename std::enable_if< is_iterator<typename T::iterator>::value>::type write(const T &x) { bool _first = 1; for (auto &&_i : x) { if (_first) _first = 0; else writeDelimiter(); write(_i); } } template <class T, class ...Ts> void write(const T &x, Ts &&...xs) { write(x); writeDelimiter(); write(std::forward<Ts>(xs)...); } void writeln() { _putchar('\n'); } template <class ...Ts> void writeln(Ts &&...xs) { write(std::forward<Ts>(xs)...); _putchar('\n'); } struct IOManager { ~IOManager() { flush(); if (_tempInputBuf) delete[](_tempInputBuf); } }; std::unique_ptr<IOManager> iomanager = std::unique_ptr<IOManager>( new IOManager()); void setOutput(FILE *file) { flush(); _output = file; } void setOutput(const std::string &s) { flush(); _output = fopen(s.c_str(), "w"); } template <class ...Ts> void debug(Ts &&...xs) { FILE *_temp = _output; setOutput(_error); write(std::forward<Ts>(xs)...); setOutput(_temp); } template <class...Ts> void debugln(Ts &&...xs) { FILE *_temp = _output; setOutput(_error); writeln(std::forward<Ts>(xs)...); setOutput(_temp); } void setError(FILE *file) { flush(); _error = file; } void setError(const std::string &s) { flush(); _error = fopen(s.c_str(), "w"); } #undef INTERACTIVE_INPUT }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // With C++ 11 not having std::make_unique defined, a simple implementation // of make_unique is provided // Template Arguments: // T: the type of the object to construct // ...Args: variadic arguments of the types of the arguments being passed to // the object being constructor // Return Value: // a unique_ptr of type T // Tested: // https://dmoj.ca/problem/set template <class T, class ...Args> unique_ptr<T> _make_unique(Args &&...args) { return unique_ptr<T>(new T(forward<Args>(args)...)); } #define make_unique _make_unique
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Functions for __int128_t __int128_t abs(__int128_t a) { return a >= 0 ? a : -a; } #define FUN(name) \ long double name(__int128_t a) { return name((long double)(a)); } FUN(sqrt) FUN(sin) FUN(cos) FUN(tan) FUN(asin) FUN(acos) FUN(atan) #undef FUN long double atan2(__int128_t y, __int128_t x) { return atan2((long double)(y), (long double)(x)); } // 128-bit integers IO operations __uint128_t stoui128(const string &s) { __uint128_t x = 0; for (int i = 0; i < int(s.length()); i++) x = x * 10 + (s[i] - '0'); return x; } __int128_t stoi128(const string &s) { __int128_t x = 0; int i = 0; bool neg = false; if (s[0] == '-') { neg = true; i++; } for (; i < int(s.length()); i++) x = x * 10 + (s[i] - '0'); if (neg) x *= -1; return x; } istream &operator >> (istream &stream, __uint128_t &x) { string s; stream >> s; x = stoui128(s); return stream; } istream &operator >> (istream &stream, __int128_t &x) { string s; stream >> s; x = stoi128(s); return stream; } string to_string(__uint128_t x) { if (x == 0) return string("0"); string s; for (; x > 0; x /= 10) s.push_back('0' + x % 10); reverse(s.begin(), s.end()); return s; } string to_string(__int128_t x) { string s = to_string(__uint128_t(x >= 0 ? x : -x)); if (x < 0) s.insert(s.begin(), '-'); return s; } ostream &operator << (ostream &stream, __uint128_t x) { return stream << to_string(x); } ostream &operator << (ostream &stream, __int128_t x) { return stream << to_string(x); }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Static allocator to improve the speed of memory access // Tested: // https://dmoj.ca/problem/ioi12p3 constexpr const int MB = 200; char buf[MB << 20]; size_t buf_ind = sizeof(buf); // Overloading new and delete operators void *operator new (size_t n) { return (void *) &buf[buf_ind -= n]; } void *operator new[] (size_t n) { return (void *) &buf[buf_ind -= n]; } void operator delete (void *) {} void operator delete[] (void *) {} void operator delete (void *, size_t) {} void operator delete[] (void *, size_t) {} // Allocator class to be used with stl data structures template <class T> struct StaticAllocator { typedef T value_type; StaticAllocator() {} template <class U> StaticAllocator(const U &) {} T *allocate(size_t n) { (buf_ind -= n * sizeof(T)) &= 0 - alignof(T); return (T*) (buf + buf_ind); } void deallocate(T *, size_t) {} }; // 32-bit pointer #define CMP(op, body) bool operator op (small_ptr p) const { return body; } template <class T> struct small_ptr { unsigned ind; small_ptr(T *p = 0) : ind(p ? unsigned((char *) p - buf) : 0) {} T &operator * () const { return *(T *) (buf + ind); } T *operator -> () const { return &**this; } T &operator [] (int a) const { return (&**this)[a]; } explicit operator bool () const { return ind; } bool operator < (small_ptr p) const { return ind < p.ind; } CMP(<=, !(p < *this)) CMP(>, p < *this) CMP(>=, !(*this < p)) CMP(==, !(*this < p) && !(p < *this)) CMP(!=, *this < p || p < *this) }; #undef CMP
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Functions for epsilon comparison of floating points using T = long double; constexpr const T EPS = 1e-9; bool lt(T a, T b) { return a + EPS < b; } bool le(T a, T b) { return !lt(b, a); } bool gt(T a, T b) { return lt(b, a); } bool ge(T a, T b) { return !lt(a, b); } bool eq(T a, T b) { return !lt(a, b) && !lt(b, a); } bool ne(T a, T b) { return lt(a, b) || lt(b, a); } int sgn(T a) { return lt(a, 0) ? -1 : lt(0, a) ? 1 : 0; } struct eps_lt { bool operator () (T a, T b) const { return lt(a, b); } }; struct eps_le { bool operator () (T a, T b) const { return !lt(b, a); } }; struct eps_gt { bool operator () (T a, T b) const { return lt(b, a); } }; struct eps_ge { bool operator () (T a, T b) const { return !lt(a, b); } }; struct eps_eq { bool operator () (T a, T b) const { return !lt(a, b) && !lt(b, a); } }; struct eps_ne { bool operator () (T a, T b) const { return lt(a, b) || lt(b, a); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #if __cplusplus < 201402L #include "MakeUnique.h" #endif using namespace std; // 32-bit and 64-bit random number generators using a time-based seed sequence // Tested: // https://dmoj.ca/problem/set // https://atcoder.jp/contests/agc026/tasks/agc026_c // https://dmoj.ca/problem/ds4 // https://judge.yosupo.jp/problem/associative_array seed_seq seq { uint64_t(chrono::duration_cast<chrono::nanoseconds>( chrono::steady_clock::now().time_since_epoch()).count()), uint64_t(__builtin_ia32_rdtsc()), uint64_t(uintptr_t(make_unique<char>().get())) }; mt19937 rng(seq); mt19937_64 rng64(seq);
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Combine struct used for maximum non empty subarray // for Segment Trees, Dynamic Range Operations, Link Cut Trees, etc // Template Arguments: // T: the type of the element // Functions: // makeData(v): returns a MaxSubarraySumCombine<T>::Data initialized with v // Time Complexity: // all functions: O(1) // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // https://www.spoj.com/problems/GSS1/ // https://dmoj.ca/problem/dmpg17g2 // https://mcpt.ca/problem/seq3 // https://dmoj.ca/problem/acc1p1 // https://dmoj.ca/problem/noi05p2 template <class T> struct MaxSubarraySumCombine { struct Data { T pre, suf, sum, maxSum; }; using Lazy = T; static Data makeData(const T &v) { Data ret; ret.pre = ret.suf = ret.sum = ret.maxSum = v; return ret; } static Data qdef() { Data ret = makeData(numeric_limits<T>::lowest()); ret.sum = T(); return ret; } static Lazy ldef() { return numeric_limits<T>::lowest(); } static Data merge(const Data &l, const Data &r) { if (l.maxSum == numeric_limits<T>::lowest()) return r; if (r.maxSum == numeric_limits<T>::lowest()) return l; Data ret; ret.pre = max(l.pre, l.sum + r.pre); ret.suf = max(l.suf + r.sum, r.suf); ret.sum = l.sum + r.sum; ret.maxSum = max(max(l.maxSum, r.maxSum), l.suf + r.pre); return ret; } template <class IndexType> static Data applyLazy(const Data &, const Lazy &r, IndexType k) { Data ret; ret.pre = ret.suf = ret.maxSum = max(Lazy(r * k), r); ret.sum = r * k; return ret; } static Lazy mergeLazy(const Lazy &, const Lazy &r) { return r; } static void revData(Data &v) { swap(v.pre, v.suf); } template <class IndexType> static Data getSegmentVdef(IndexType) { return makeData(IndexType()); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Maintains the aggregate value of a sequence of elements over an associative // operation where elements can be pushed to the back and popped from the // front of the queue // Template Arguments: // T: the type of each element // Op: a struct with the operation (can also be of type // std::function<T(T, T)>); in practice, custom struct is faster than /// std::function // Required Functions: // operator (l, r): merges the values l and r, must be associative // Constructor Arguments: // qdef: the query default value // op: an instance of the Op struct // Functions: // reserve(v): reserves space for N elements // push(v): pushes the value v into the queue // getAgg(): returns the aggregate value of the elements in the queue // aggregated in the order they were pushed // pop(): pops from the front of the queue // In practice, has a moderate constant // Time Complexity: // constructor, getAgg: O(1) // reserve: O(N) // push: O(1) if reserved is called beforehand, O(1) amortized otherwise // pop: O(1) amortized // Memory Complexity: O(N) // Tested: // https://judge.yosupo.jp/problem/queue_operate_all_composite template <class T, class Op> struct SWAG { vector<T> q; T qdef, backAgg; int front, mid; Op op; SWAG(const T &qdef, Op op = Op()) : qdef(qdef), backAgg(qdef), front(0), mid(0), op(op) {} void reserve(int N) { q.reserve(N); } void push(const T &v) { q.push_back(v); backAgg = op(backAgg, v); } T getAgg() const { return front == mid ? backAgg : op(q[front], backAgg); } void pop() { if (front++ < mid) return; for (int i = int(q.size()) - 2; i >= mid; i--) q[i] = op(q[i], q[i + 1]); mid = q.size(); backAgg = qdef; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/priority_queue.hpp> #include <ext/pb_ds/tree_policy.hpp> #include "RandomizedHash.h" using namespace std; using namespace __gnu_pbds; // Policy-based data structures for ordered and unordered sets and maps, // as well as priority queues // Unordered hashmap with randomized hash // API is similar to set and map in C++ 03, // except there is no count function (use member function find instead) // https://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/gp_hash_table.html // and https://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/container_base.html // contain most of the public methods // In practice, has a moderate constant, faster than unordered_set // and unordered_map (at the expense of using more memory), but slower than // a sorted vector + binary search // Time Complexity: O(1) on average, O(N) worst case // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/set // https://atcoder.jp/contests/agc026/tasks/agc026_c // https://judge.yosupo.jp/problem/associative_array template <class K, class H = rand_hash, class ...Ts> using hashset = gp_hash_table<K, null_type, H, Ts ...>; template <class K, class V, class H = rand_hash, class ...Ts> using hashmap = gp_hash_table<K, V, H, Ts ...>; // Ordered treeset and treemap // API is similar to set and map in C++ 03 // There are additional functions to find the kth element with find_by_order(k) // and find the 0-indexed rank of a key with order_of_key(key) // https://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/tree.html // https://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/basic_tree.html // and https://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/container_base.html // contain most of the public methods // In practice, has a moderate constant, slower that set and map as well as // custom written balanced binary search trees // Time Complexity: O(log N) // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/ds4 // https://codeforces.com/contest/1093/problem/E // http://www.usaco.org/index.php?page=viewproblem2&cpid=898 template <class K, class C = less<K>, class ...Ts> using treeset = tree<K, null_type, C, rb_tree_tag, tree_order_statistics_node_update, Ts ...>; template <class K, class V, class C = less<K>, class ...Ts> using treemap = tree<K, V, C, rb_tree_tag, tree_order_statistics_node_update, Ts ...>; // Priority Queue // API is similar to std::priority_queue in C++ 03 // There are additional functions to modify an existing key with // PQ.modify(iter, key) where ptr is an iterator returned from push, // and merge heap B into A with A.join(B) // https://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/priority_queue.html // contains most of the public methods // There are 5 different types of tags to specify the underlying data structure // of the heap, which can be seen at // https://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/pq_design.html // https://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/pq_performance_tests.html // contains a summary of the time complexities of each tag // On average, pairing_heap_tag performs the best out of all tags // In practice, has a moderate constant, slower than std::priority_queue // join is only slightly faster than small to large merging when // amortization applies // Time Complexity (for pairing_heap_tag): // push, join: O(1) // pop: O(log N) // modify, erase: O(log N) amortized, O(N) worst case // Memory Complexity (for pairing_heap_tag): O(N) // Tested: // https://dmoj.ca/problem/apio16p2 template <class T, class C = less<T>, class Tag = pairing_heap_tag> using pbdsheap = __gnu_pbds::priority_queue<T, C, Tag>;
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Maintains the difference between adjacent elements in a sorted multiset // Template Arguments: // T: the type of the elements being stored // Fields: // vals: a mapping from the values in the multiset to its frequency // diffs: a mapping from the difference of each pair of adjacent elements in // the multiset to its frequency // Functions: // insert(v): inserts the value v into the multiset // erase(v); erases the value of v from the multiset assuming v exists // In practice, has a moderate constant // Time Complexity: // insert, erase: O(log N) // Memory Complexity: O(N) // Tested: // https://codeforces.com/contest/1418/problem/D // https://dmoj.ca/problem/coci19c3p3 // https://dmoj.ca/problem/year2018p6 template <class T> struct SetDifferenceMaintenance { map<T, int> vals, diffs; void insert(T v) { auto nxt = vals.lower_bound(v); if (nxt != vals.end() && nxt->first == v) { ++nxt->second; ++diffs[T()]; return; } if (nxt != vals.begin()) { auto prv = prev(nxt); diffs[v - prv->first]++; if (nxt != vals.end()) { auto it = diffs.find(nxt->first - prv->first); if (--it->second == 0) diffs.erase(it); } } if (nxt != vals.end()) ++diffs[nxt->first - v]; vals.emplace_hint(nxt, v, 1); } void erase(T v) { auto cur = vals.find(v); if (cur->second >= 2) { --cur->second; auto it = diffs.find(T()); if (--it->second == 0) diffs.erase(it); return; } auto nxt = vals.erase(cur); if (nxt != vals.end()) { auto it = diffs.find(nxt->first - v); if (--it->second == 0) diffs.erase(it); } if (nxt != vals.begin()) { auto prv = prev(nxt); auto it = diffs.find(v - prv->first); if (--it->second == 0) diffs.erase(it); if (nxt != vals.end()) ++diffs[nxt->first - prv->first]; } } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Sparse Table supporting associative and idempotent range queries on // a static array // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // Op: a struct with the operation (can also be of type // std::function<T(T, T)>); in practice, custom struct is faster than /// std::function // Required Functions: // operator (l, r): combines the values l and r, must be // associative and idempotent // Constructor Arguments: // A: a vector of type T // op: an instance of the Op struct // Functions: // query(l, r): returns the aggregate value of the elements in // the range [l, r] // In practice, the constructor has a small constant, // query has a moderate constant, but still faster than segment trees, // slightly faster than Fischer Heun Structure, and performs similarly to // disjoint sparse tables // Time Complexity: // constructor: O(N log N) // query: O(1) // Memory Complexity: O(N log N) // Tested: // Fuzz and Stress Tested // https://dmoj.ca/problem/ncco3d2p1 // https://www.spoj.com/problems/RMQSQ/ // https://judge.yosupo.jp/problem/staticrmq template <class T, class Op> struct SparseTable { int N; vector<vector<T>> ST; Op op; SparseTable(vector<T> A, Op op = Op()) : N(A.size()), ST(N == 0 ? 0 : __lg(N) + 1, move(A)), op(op) { for (int i = 0; i < int(ST.size()) - 1; i++) { ST[i + 1] = ST[0]; for (int j = 0; j < N; j++) ST[i + 1][j] = op(ST[i][j], ST[i][min(j + (1 << i), N - 1)]); } } T query(int l, int r) { int i = __lg(r - l + 1); return op(ST[i][l], ST[i][r - (1 << i) + 1]); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Helper struct to compare two pairs template <class Cmp> struct PairCmp { Cmp cmp; PairCmp(Cmp cmp = Cmp()) : cmp(cmp) {} template <class T> bool operator () (const pair<T, T> &a, const pair<T, T> &b) const { if (cmp(a.first, b.first)) return true; if (cmp(b.first, a.first)) return false; return cmp(a.second, b.second); } }; // Struct representing no operation struct NoOp { template <class T> void operator () (const T &, const T &) const {} }; // Adding and removing half-open intervals from a set such that the combined // intervals are disjoint // Template Arguments: // T: the type of the endpoints of the intervals // Cmp: the comparator to compare two points // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Add: a struct with a callback function (can also be of type // std::function<T(T, T)>); in practice, custom struct is faster than // std::function // Required Functions: // operator (l, r): adds the interval [l, r) to the set of // disjoint intervals // Rem: a struct with a callback function (can also be of type // std::function<T(T, T)>); in practice, custom struct is faster than // std::function // Required Functions: // operator (l, r): removes the interval [l, r) from the set of // disjoint intervals // Constructor Arguments: // cmp: an instance of Cmp // add: an instance of Add // rem: an instance of Rem // Functions: // addInterval(L, R): adds an interval [L, R) to the set // removeInterval(L, R): removes the interval [L, R) from the set // In practice, has a moderate constant // Time Complexity: // addInterval, removeInterval: O(log N) amortized // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/art6 // http://www.usaco.org/index.php?page=viewproblem2&cpid=973 template <class T, class Cmp = less<T>, class Add = NoOp, class Rem = NoOp> struct IntervalUnion : public set<pair<T, T>, PairCmp<Cmp>> { Cmp cmp; Add add; Rem rem; IntervalUnion(Cmp cmp = Cmp(), Add add = Add(), Rem rem = Rem()) : set<pair<T, T>, PairCmp<Cmp>>(PairCmp<Cmp>(cmp)), cmp(cmp), add(add), rem(rem) {} typename set<pair<T, T>, PairCmp<Cmp>>::iterator addInterval(T L, T R) { if (!cmp(L, R) && !cmp(R, L)) return this->end(); auto it = this->lower_bound(make_pair(L, R)), before = it; while (it != this->end() && !cmp(R, it->first)) { R = max(R, it->second, cmp); rem(it->first, it->second); before = it = this->erase(it); } if (it != this->begin() && !cmp((--it)->second, L)) { L = min(L, it->first, cmp); R = max(R, it->second, cmp); rem(it->first, it->second); this->erase(it); } add(L, R); return this->emplace_hint(before, L, R); } void removeInterval(T L, T R) { if (!cmp(L, R) && !cmp(R, L)) return; auto it = addInterval(L, R); auto r2 = it->second; if (!cmp(it->first, L) && !cmp(L, it->first)) { rem(it->first, it->second); this->erase(it); } else (T &) it->second = L; if (cmp(R, r2) || cmp(r2, R)) { add(R, r2); this->emplace(R, r2); } } }; // Given a set of intervals (by the PairCmp struct), combine // them into disjoint half-open intervals of the form [L, R) // Range is modified in-place // Template Arguments: // T: the type of the endpoints of the intervals // Cmp: the comparator to compare two points // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Function Arguments: // A: a reference to a vector of pairs with the first element being the // inclusive left bound of the interval and the second element being the // exclusive right bound of the interval // cmp: an instance of the Cmp struct // Return Value: a reference to the modified vector // In practice, has a small constant // Time Complexity: O(N log N) // Memory Complexity: O(1) // Tested: // https://dmoj.ca/problem/art6 // https://open.kattis.com/problems/drawingcircles template <class T, class Cmp = less<T>> vector<pair<T, T>> &intervalUnion(vector<pair<T, T>> &A, Cmp cmp = Cmp()) { sort(A.begin(), A.end(), [&] (const pair<T, T> &a, const pair<T, T> &b) { if (cmp(a.first, b.first)) return true; if (cmp(b.first, a.first)) return false; return cmp(a.second, b.second); }); int i = 0; for (int l = 0, r = 0, N = A.size(); l < N; l = r, i++) { A[i] = A[l]; for (r = l + 1; r < N && !cmp(A[i].second, A[r].first); r++) A[i].second = max(A[i].second, A[r].second, cmp); } A.erase(A.begin() + i, A.end()); return A; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "FischerHeunStructure.h" using namespace std; // Fischer Heun Structure in 2 dimensions supporting range maximum queries on // a static 2D array // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // Cmp: the comparator to compare two values, // convention is same as std::priority_queue in STL // Required Functions: // operator (a, b): returns true if and only if a compares less than b // mask_t: the type to store a bitmask, should have around log(N) bits // Constructor Arguments: // A: a 2D vector of elements of type T // cmp: an instance of the Cmp struct // Functions: // query(u, d, l, r): returns the maximum element (based on the comparator) // in the range [u, d] in the first dimension and [l, r] in // the second dimension // In practice, the constructor has a moderate constant and is significantly // faster than sparse table's constructor, query has a moderate constant and // is slightly slower than sparse table's query // Time Complexity: // constructor: O(N log (N) (M + M / B log (M / B))), where B is // the number of bits in mask_t // queryInd, query: O(1) assuming bitshift for mask_t is O(1) // Memory Complexity: O(N log (N) (M + M / B log (M / B))) assuming mask_t is // O(1) memory // Tested: // Fuzz and Stress Tested // http://www.usaco.org/index.php?page=viewproblem2&cpid=972 template <class T, class Cmp = less<T>, class mask_t = uint32_t> struct FischerHeunStructure2D { int N, M, lgN; vector<vector<FischerHeunStructure<T, Cmp, mask_t>>> FHS; Cmp cmp; T cmpVal(const T &a, const T &b) { return cmp(a, b) ? b : a; } FischerHeunStructure2D(vector<vector<T>> A, Cmp cmp = Cmp()) : N(A.size()), M(N == 0 ? 0 : A[0].size()), lgN(N == 0 ? 0 : __lg(N) + 1), FHS(lgN), cmp(cmp) { for (int i = 0; i < lgN; i++) { FHS[i].reserve(N); for (int j = 0; j < N; j++) FHS[i].emplace_back(A[j], cmp); if (i < lgN - 1) for (int j = 0; j < N; j++) for (int k = 0; k < M; k++) A[j][k] = cmpVal(A[j][k], A[min(j + (1 << i), N - 1)][k]); } } T query(int u, int d, int l, int r) { int i = __lg(d - u + 1); return cmpVal(FHS[i][u].query(l, r), FHS[i][d - (1 << i) + 1].query(l, r)); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // A map that supports insertions of a key value pair (k, v) and // queries for the maximum value (based on VCmp) of v for // all keys less than or equal to (based on KCmp) k // Template Arguments: // K: the type of the key // V: the type of the value // KCmp: the comparator for the key, convention is the same as // std::map in STL // Required Functions: // operator (a, b): returns true if and only if a compares less than b // VCmp: the comparator for the value, convention is the same as // std::priority_queue in STL // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Constructor Arguments: // kcmp: an instance of KCmp // vcmp: an instance of VCmp // NEG_INF: a value for negative infinity // Functions: // add(k, v): adds the key value pair (k, v) and maintains the pareto // optimums // queryPrefix(k): returns the maximum value (based on VCmp) of v for // all keys less than or equal to (based on KCmp) k, or NEG_INF if no such // keys exist // queryProperPrefix(k): returns the maximum value (based on VCmp) of v for // all keys less than or equal to (based on KCmp) k, or NEG_INF if no such // keys exist // In practice, has a moderate constant // Time Complexity: // constructor: O(1) // add: O(log N) amortized // queryPrefix, queryProperPrefix: O(log N) // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/dpq template <class K, class V, class KCmp = less<K>, class VCmp = less<V>> struct ParetoMap : public map<K, V, KCmp> { using M = map<K, V, KCmp>; VCmp vcmp; V NEG_INF; ParetoMap(KCmp kcmp = KCmp(), VCmp vcmp = VCmp(), V NEG_INF = numeric_limits<V>::lowest()) : M(kcmp), vcmp(vcmp), NEG_INF(NEG_INF) {} void add(K k, V v) { auto it = M::lower_bound(k); if (it != M::begin() && !VCmp()(prev(it)->second, v)) return; while (it != M::end() && !VCmp()(v, it->second)) it = M::erase(it); M::emplace_hint(it, k, v); } V queryPrefix(K k) const { auto it = M::upper_bound(k); return it == M::begin() ? NEG_INF : prev(it)->second; } V queryProperPrefix(K k) const { auto it = M::lower_bound(k); return it == M::begin() ? NEG_INF : prev(it)->second; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "BitPrefixSumArray.h" using namespace std; // Wavelet Matrix supporting rank and select operations for a subarray // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of the element of the array // Cmp: the comparator to compare two elements // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Constructor Arguments: // A: a vector of type T of the values in the array // cmp: an instance of the Cmp struct // Functions: // rank(l, r, k): returns the number of elements less than k (using the // comparator) in the range [l, r] // count(l, r, lo, hi) returns the number of elements not less than lo and // not greater than hi (using the comparator) in the range [l, r] // select(l, r, k): returns the kth element (0-indexed) sorted by the // comparator if the range [l, r] was sorted // In practice, has a moderate constant // Time Complexity: // constructor: O(N log N) // rank, count, select: O(log N) // Memory Complexity: O(N + (N log N) / 64) // Tested: // https://www.spoj.com/problems/KQUERY/ (rank/count) // https://www.spoj.com/problems/KQUERYO/ (rank/count) // https://codeforces.com/contest/1284/problem/D (rank/count) // https://www.spoj.com/problems/MKTHNUM/ (select) // https://judge.yosupo.jp/problem/range_kth_smallest (select) template <class T, class Cmp = less<T>> struct WaveletMatrix { #define clt [&] (const T &a, const T &b) { return cmp(a, b); } #define cle [&] (const T &a, const T &b) { return !cmp(b, a); } int N, H; Cmp cmp; vector<int> mid; vector<BitPrefixSumArray> B; vector<T> S; WaveletMatrix(vector<T> A, Cmp cmp = Cmp()) : N(A.size()), H(N == 0 ? 0 : __lg(N) + 1), cmp(cmp), mid(H), B(H, BitPrefixSumArray(N)), S(move(A)) { vector<T> temp = S; sort(S.begin(), S.end(), cmp); vector<int> C(N); for (int i = 0; i < N; i++) C[i] = lower_bound(S.begin(), S.end(), temp[i], cmp) - S.begin(); for (int h = H - 1; h >= 0; h--) { int ph = 1 << h; for (int i = 0; i < N; i++) B[h].set(i, C[i] <= ph - 1); mid[h] = stable_partition(C.begin(), C.end(), [&] (int v) { return v <= ph - 1; }) - C.begin(); B[h].build(); for (int i = mid[h]; i < N; i++) C[i] -= ph; } } template <class F> int cnt(int l, int r, const T &v, F f) { int ret = 0; for (int cur = 0, h = H - 1; h >= 0; h--) { int ph = 1 << h, ql = B[h].query(l - 1), qr = B[h].query(r); if (cur + ph - 1 >= N || f(v, S[cur + ph - 1])) { l = ql; r = qr - 1; } else { cur += ph; ret += qr - ql; l += mid[h] - ql; r += mid[h] - qr; } } return ret; } int rank(int l, int r, const T &v) { return cnt(l, r, v, cle); } int count(int l, int r, const T &lo, const T &hi) { return cnt(l, r, hi, clt) - cnt(l, r, lo, cle); } T select(int l, int r, int k) { int cur = 0; for (int h = H - 1; h >= 0; h--) { int ql = B[h].query(l - 1), qr = B[h].query(r); if (k < qr - ql) { l = ql; r = qr - 1; } else { cur += 1 << h; k -= qr - ql; l += mid[h] - ql; r += mid[h] - qr; } } return S[cur]; } #undef clt #undef cle };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // 2D Sparse Table supporting associative and idempotent range queries on // a static 2D array // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // Op: a struct with the operation (can also be of type // std::function<T(T, T)>); in practice, custom struct is faster than /// std::function // Required Functions: // operator (l, r): combines the values l and r, must be // associative and idempotent // Constructor Arguments: // A: a 2D vector of elements of type T // op: an instance of the Op struct // Functions: // query(u, d, l, r): returns the aggregate value of the elements in // the range [u, d] in the first dimension and [l, r] in // the second dimension // In practice, the constructor has a small constant, // query has a moderate constant, but still faster than segment trees // Time Complexity: // constructor: O(NM log N log M) // query: O(1) // Memory Complexity: O(NM log N log M) // Tested: // Fuzz and Stress Tested // https://dmoj.ca/problem/2drmq // http://www.usaco.org/index.php?page=viewproblem2&cpid=972 template <class T, class Op> struct SparseTable2D { int N, M, lgN, lgM; vector<vector<vector<vector<T>>>> ST; Op op; SparseTable2D(vector<vector<T>> A, Op op = Op()) : N(A.size()), M(N == 0 ? 0 : A[0].size()), lgN(N == 0 ? 0 : __lg(N) + 1), lgM(M == 0 ? 0 : __lg(M) + 1), ST(lgN, vector<vector<vector<T>>>(lgM, move(A))), op(op) { for (int ir = 0; ir < lgN; ir++) { for (int ic = 0; ic < lgM - 1; ic++) for (int jr = 0; jr < N; jr++) for (int jc = 0; jc < M; jc++) ST[ir][ic + 1][jr][jc] = op( ST[ir][ic][jr][jc], ST[ir][ic][jr][min(jc + (1 << ic), M - 1)]); if (ir < lgN - 1) for (int jr = 0; jr < N; jr++) for (int jc = 0; jc < M; jc++) ST[ir + 1][0][jr][jc] = op( ST[ir][0][jr][jc], ST[ir][0][min(jr + (1 << ir), N - 1)][jc]); } } T query(int u, int d, int l, int r) { int ir = __lg(d - u + 1), ic = __lg(r - l + 1); return op(op(ST[ir][ic][u][l], ST[ir][ic][d - (1 << ir) + 1][r - (1 << ic) + 1]), op(ST[ir][ic][d - (1 << ir) + 1][l], ST[ir][ic][u][r - (1 << ic) + 1])); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Disjoint Sparse Table supporting associative range queries on a static array // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // Op: a struct with the operation (can also be of type // std::function<T(T, T)>); in practice, custom struct is faster than /// std::function // Required Functions: // operator (l, r): combines the values l and r, must be associative // Constructor Arguments: // A: a vector of type T // op: an instance of the Op struct // Functions: // query(l, r): returns the aggregate value of the elements in // the range [l, r] // In practice, the constructor has a small constant, // query has a moderate constant, but still faster than segment trees, // slightly faster than Fischer Heun Structure, and performs similarly to // sparse tables // Time Complexity: // constructor: O(N log N) // query: O(1) // Memory Complexity: O(N log N) // Tested: // Fuzz and Stress Tested // https://www.spoj.com/problems/GSS1/ // https://www.spoj.com/problems/GSS5/ // https://judge.yosupo.jp/problem/staticrmq template <class T, class Op> struct DisjointSparseTable { int N; vector<vector<T>> ST; Op op; DisjointSparseTable(vector<T> A, Op op = Op()) : N(A.size()), ST(N == 0 ? 0 : __lg(N * 2 - 1) + 1, move(A)), op(op) { for (int i = 1; i < int(ST.size()); i++) { ST[i] = ST[0]; for (int j = 0, len = 1 << i; j < N; j += len) { int k = min(j + len / 2, N) - 1; T agg = ST[i][k] = ST[0][k]; for (k--; k >= j; k--) agg = ST[i][k] = op(ST[0][k], agg); k = j + len / 2; if (k < N) agg = ST[i][k] = ST[0][k]; for (k++; k < min(j + len, N); k++) agg = ST[i][k] = op(agg, ST[0][k]); } } } T query(int l, int r) { if (l == r) return ST[0][l]; int i = __lg(l ^ r) + 1; return op(ST[i][l], ST[i][r]); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Prefix Sum Array supporting range sum queries where all values are 0 or 1, // and all values are set before all queries // Indices are 0-indexed and ranges are inclusive // Constructor Arguments: // N: the size of the array // Functions: // set(i, v): sets the index i with the boolean value v // get(i): gets the value of index i // build(): builds the prefix sum array, must be called before query can // be called after a set operation // query(r): queries the sum of the range [0, r] // query(l, r): queries the sum of the range [l, r] // In practice, has a moderate constant, performs faster than a regular prefix // sum array and uses less memory // Time Complexity: // constructor, set, get, query: O(1) // build: O(N / 64) // Memory Complexity: O(N / 64) // Tested: // Fuzz and Stress Tested struct BitPrefixSumArray { int M; vector<uint64_t> mask; vector<int> pre; BitPrefixSumArray(int N) : M((N >> 6) + 1), mask(M, 0), pre(M + 1, 0) {} void set(int i, bool v) { int j = i >> 6, k = i & 63; mask[j] = (mask[j] & ~(uint64_t(1) << k)) | (uint64_t(v) << k); } bool get(int i) { return (mask[i >> 6] >> (i & 63)) & 1; } void build() { for (int j = 0; j < M; j++) pre[j + 1] = pre[j] + __builtin_popcountll(mask[j]); } int query(int r) { r++; int j = r >> 6, k = r & 63; return pre[j] + __builtin_popcountll(mask[j] & ((uint64_t(1) << k) - 1)); } int query(int l, int r) { return query(r) - query(l - 1); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Supports online queries and FIFO operations on a multiset of elements, // where the underlying data structure only supports LIFO operations // Template Arguments: // S: struct to maintain a multiset of elements // Required Fields: // T: the type of each element // Required Functions: // constructor(...args): takes any number of arguments (arguments are // passed from constructor of FIFOWithLIFO) // push(v): pushes the value v into the multiset // pop(): pops the most recent element pushed to the multiset // query(...args): queries the multiset // Sample Struct: supports queries for graph connectivity // struct S { // using T = pair<int, int>; // UnionFindUndo uf; // S(int V) : uf(V) {} // void push(const T &e) { uf.join(e.first, e.second); } // void pop() { uf.undo(); } // bool query(int v, int w) { return uf.connected(v, w); } // }; // Constructor Arguments: // ...args: arguments to be forwarded to the constructor of S // Functions: // push(v): pushes the value v into the multiset // pop(): pops the least recent element pushed into the multiset // query(...args): inheirited from S, queries the multiset // In practice, has a small constant // Time Complexity: // push: O(P) where P is the time complexity of S.push // pop: O(P log N) amortized where P is the time complexity of // S.push and S.pop, with S.push and S.pop being called at most O(log N) // times in total for each element, over all operations // query: O(T) where T is the time complexity of S.query // Memory Complexity: O(N) // Tested: // https://codeforces.com/contest/1386/problem/C template <class S> struct FIFOWithLIFO : public S { using T = typename S::T; vector<pair<T, bool>> stk; vector<T> A, B; int cntA; template <class ...Args> FIFOWithLIFO(Args &&...args) : S(forward<Args>(args)...), cntA(0) {} void push(const T &v, bool a = false) { stk.emplace_back(v, a); S::push(v); } void pop() { if (cntA == 0) { reverse(stk.begin(), stk.end()); cntA = stk.size(); for (int i = 0; i < cntA; i++) S::pop(); for (auto &&s : stk) { S::push(s.first); s.second = true; } } for (; !stk.back().second; stk.pop_back(), S::pop()) B.push_back(stk.back().first); int m = cntA & -cntA; for (int i = 0; i < m; i++, stk.pop_back(), S::pop()) A.push_back(stk.back().first); for (; !B.empty(); B.pop_back()) push(B.back()); for (; !A.empty(); A.pop_back()) push(A.back(), true); stk.pop_back(); S::pop(); cntA--; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../utils/Random.h" using namespace std; const size_t RANDOM = uniform_int_distribution<size_t>( 0, numeric_limits<size_t>::max())(rng64); // Randomized hash for types with std::hash defined and for pairs // Tested: // https://dmoj.ca/problem/set // https://atcoder.jp/contests/agc026/tasks/agc026_c // https://judge.yosupo.jp/problem/associative_array struct rand_hash { static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } template <class T> size_t operator () (const T &x) const { return splitmix64(hash<T>()(x) + RANDOM); } template <class T1, class T2> size_t operator () (const pair<T1, T2> &p) const { return 31 * operator ()(p.first) + operator ()(p.second); } }; // unordered_set and unordered_map with a randomized hash // In practice, has a moderate constant, but still slower than // pbds::gp_hash_table // Tested: // https://dmoj.ca/problem/set // https://atcoder.jp/contests/agc026/tasks/agc026_c // https://judge.yosupo.jp/problem/associative_array template <class K, class H = rand_hash, class ...Ts> using uset = unordered_set<K, H, Ts ...>; template <class K, class V, class H = rand_hash, class ...Ts> using umap = unordered_map<K, V, H, Ts ...>;
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Fischer Heun Structure supporting range maximum queries on a static array // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of each element // Cmp: the comparator to compare two values, // convention is same as std::priority_queue in STL // Required Functions: // operator (a, b): returns true if and only if a compares less than b // mask_t: the type to store a bitmask, should have around log(N) bits // Constructor Arguments: // A: a vector of type T of the values in the array // cmp: an instance of the Cmp struct // Functions: // queryInd(l, r): returns the index of the maximum element in // the subarray [l, r], breaking ties by selecting the first such index; // the last such index can be obtained by using less_equal or greater_equal // as the Cmp struct // query(l, r): returns the maximum element (based on the comparator) in // the subarray [l, r] // In practice, the constructor has a moderate constant and is significantly // faster than sparse table's constructor, query has a moderate constant and // is slightly slower than sparse table's query // Time Complexity: // constructor: O(N + N / B log (N / B)), where B is // the number of bits in mask_t // queryInd, query: O(1) assuming bitshift for mask_t is O(1) // Memory Complexity: O(N + N / B log (N / B)) assuming mask_t is O(1) memory // Tested: // Fuzz and Stress Tested // https://dmoj.ca/problem/ncco3d2p1 // https://www.spoj.com/problems/RMQSQ/ // https://judge.yosupo.jp/problem/staticrmq template <class T, class Cmp = less<T>, class mask_t = uint32_t> struct FischerHeunStructure { static_assert(is_integral<mask_t>::value, "mask_t must be integral"); static_assert(is_unsigned<mask_t>::value, "mask_t must be unsigned"); static constexpr const int B = __lg(numeric_limits<mask_t>::max()) + 1; int N, M; vector<T> A; vector<mask_t> mask; vector<vector<int>> ST; Cmp cmp; int cmpInd(int i, int j) { return cmp(A[i], A[j]) ? j : i; } int small(int r, int sz = B) { return r - __lg(sz == B ? mask[r] : mask[r] & ((mask_t(1) << sz) - 1)); } FischerHeunStructure(vector<T> A, Cmp cmp = Cmp()) : N(A.size()), M(N / B), A(move(A)), mask(N), ST(M == 0 ? 0 : __lg(M) + 1, vector<int>(M)), cmp(cmp) { mask_t k = 0; for (int i = 0; i < N; mask[i++] = k |= 1) for (k <<= 1; k && cmpInd(i - __lg(k & -k), i) == i;) k ^= k & -k; for (int i = 0; i < M; i++) ST[0][i] = small(B * (i + 1) - 1); for (int i = 0; i < int(ST.size()) - 1; i++) for (int j = 0; j < M; j++) ST[i + 1][j] = cmpInd(ST[i][j], ST[i][min(j + (1 << i), M - 1)]); } int queryInd(int l, int r) { if (r - l + 1 <= B) return small(r, r - l + 1); int ql = small(l + B - 1), qr = small(r); l = l / B + 1; r = r / B - 1; if (l <= r) { int i = __lg(r - l + 1); ql = cmpInd(ql, cmpInd(ST[i][l], ST[i][r - (1 << i) + 1])); } return cmpInd(ql, qr); } T query(int l, int r) { return A[queryInd(l, r)]; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "WaveletMatrixAggregation.h" using namespace std; // Wavelet Matrix supporting 2D aggregation queries where the data can change, // and the indices and the keys that are updated are known beforehand // Indices are 0-indexed and ranges are inclusive // Queries bounded by 3 indices require a commutative operation, while queries // bounded by 4 indices also requires the data to be invertible // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of the element of the array // R: struct supporting point updates and range queries on indices // Required Fields: // Data: the data type // Lazy: the lazy type // Required Functions: // static qdef(): returns the query default value // static merge(l, r): returns the values l of type Data merged with // r of type Data, must be associative and commutative // static applyLazy(l, r): returns the value r of type Lazy applied to // l of type Data // constructor(A): takes a vector A of type Data with the initial // value of each index // update(i, val): updates the index i with the value val // query(l, r): queries the range [l, r] // Sample Struct: supporting point increments updates and range sum queries // struct R { // using Data = int; // using Lazy = int; // static Data qdef() { return 0; } // static Data merge(const Data &l, const Data &r) { return l + r; } // static Data applyLazy(const Data &l, const Lazy &r) { // return l + r; // } // FenwickTree1D<Data> FT; // R(vector<Data> A) : FT(move(A)) {} // void update(int i, const Lazy &val) { FT.update(i, val); } // Data query(int l, int r) { return FT.query(l, r); } // }; // Cmp: the comparator to compare two elements of type T // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Constructor Arguments: // A: a vector of type T containing the initial keys of the array // D: a vector of type R::Data containing the initial data of the array // updates: a vector of vectors of type T containing the sequence of updates // to each index in the order they are updated // cmp: an instance of the Cmp struct // Functions: // updateToNextKey(i): updates the ith key to the next key in the update // sequence // update(i, v): updates the ith data with the lazy value v // query(l, r, hi): returns the aggregate value of the data associated with // all elements with a key less than or equal to hi (using the comparator) // in the range [l, r] // query(l, r, lo, hi): returns the aggregate value of the data associated // with all elements with a key of not less than lo and not greater than hi // (using the comparator) in the range [l, r] // bsearch(l, r, f): over all keys in the array, finds the first key k such // that query(l, r, k) returns true // In practice, has a small constant, faster than using an // Offline or Online 2D Sparse Fenwick Tree or Segment Tree // Time Complexity: // constructor: O((N + K + C) log N + K) where C is the time complexity of // R's constructor for K total updates // updateToNextKey: O(U log (N + K)) where U is the time complexity of R's // update function for K total updates // update: O(U log (N + K)) where U is the time complexity of R's update // function for K total updates // query, bsearch: O(Q log N) where Q is the time complexity of // R's query function for K total updates // Memory Complexity: O(N + K + ((N + K) log (N + K)) / 64 + M log (N + K)) // where M is the memory complexity of R for K total updates // Tested: // https://dmoj.ca/problem/oly19practice4 template <class T, class R, class Cmp = less<T>> struct WaveletMatrixAggregationOfflineUpdates { using Data = typename R::Data; using Lazy = typename R::Lazy; vector<int> cur; vector<Data> D; WaveletMatrixAggregation<T, R, Cmp> wm; WaveletMatrixAggregation<T, R, Cmp> init( const vector<T> &A, const vector<Data> &D, const vector<vector<T>> &updates, Cmp cmp) { assert(A.size() == D.size()); assert(A.size() == updates.size()); int N = A.size(); for (int i = 0; i < N; i++) cur[i + 1] = updates[i].size() + 1; partial_sum(cur.begin(), cur.end(), cur.begin()); vector<T> ret; ret.reserve(cur[N]); for (int i = 0; i < N; i++) { ret.push_back(A[i]); ret.insert(ret.end(), updates[i].begin(), updates[i].end()); } vector<Data> temp(ret.size(), R::qdef()); for (int i = 0; i < N; i++) temp[cur[i]] = D[i]; return WaveletMatrixAggregation<T, R, Cmp>(move(ret), temp, cmp); } WaveletMatrixAggregationOfflineUpdates( const vector<T> &A, const vector<Data> &D, const vector<vector<T>> &updates, Cmp cmp = Cmp()) : cur(A.size() + 1, 0), D(D), wm(init(A, D, updates, cmp)) {} void updateToNextKey(int i) { wm.update(cur[i], R::qdef()); wm.update(++cur[i], D[i]); } void update(int i, const Lazy &v) { D[i] = R::applyLazy(D[i], v); wm.update(cur[i], v); } Data query(int l, int r, const T &hi) { return wm.query(cur[l], cur[r], hi); } Data query(int l, int r, const T &lo, const T &hi) { return wm.query(cur[l], cur[r], lo, hi); } template <class F> pair<bool, T *> bsearch(int l, int r, F f) { return wm.bsearch(cur[l], cur[r], f); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // A collections of functions for 2D prefix sum and difference arrays // Creates a prefix sum array pre from the 2D array A of size N x M // pre[i][j] is the sum of all elements in the subarray A[0..i][0..j] // Indices are 0-indexed // In practice, has a small constant // Time Complexity: O(NM) // Memory Complexity: O(1) // Tested: // Fuzz and Stress Tested // https://codeforces.com/contest/635/problem/A // https://dmoj.ca/problem/dmpg15s5 template <class C> void partial_sum_2d(const C &A, int N, int M, C &pre) { for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { pre[i][j] = A[i][j]; if (i > 0) pre[i][j] += pre[i - 1][j]; if (j > 0) pre[i][j] += pre[i][j - 1]; if (i > 0 && j > 0) pre[i][j] -= pre[i - 1][j - 1]; } } // Creates a difference array diff from the 2D array A of size N x M // A[i][j] is the sum of all elements in the subarray diff[0..i][0..j] // Indices are 0-indexed // In practice, has a small constant // Time Complexity: O(NM) // Memory Complexity: O(1) // Tested: // Fuzz and Stress Tested template <class C> void adjacent_difference_2d(const C &A, int N, int M, C &diff) { for (int i = N - 1; i >= 0; i--) for (int j = M - 1; j >= 0; j--) { diff[i][j] = A[i][j]; if (i > 0) diff[i][j] -= A[i - 1][j]; if (j > 0) diff[i][j] -= A[i][j - 1]; if (i > 0 && j > 0) diff[i][j] += A[i - 1][j - 1]; } } // Computes the sum of a subarray A[u..d][l..r] with prefix sum array pre // Indices are 0-indexed and ranges are inclusive // In practice, has a moderate constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // Fuzz and Stress Tested // https://codeforces.com/contest/635/problem/A template <class C> auto rsq(const C &pre, int u, int d, int l, int r) -> typename decay<decltype(pre[d][r])>::type { typename decay<decltype(pre[d][r])>::type v = pre[d][r]; if (u > 0) v -= pre[u - 1][r]; if (l > 0) v -= pre[d][l - 1]; if (u > 0 && l > 0) v += pre[u - 1][l - 1]; return v; } // Adds v to the subarray A[u..d][l..r] with difference array diff // of size N x M // Indices are 0-indexed and ranges are inclusive // In practice, has a moderate constant // Time Complexity: O(1) // Memory Complexity: O(1) // Tested: // Fuzz and Stress Tested // https://dmoj.ca/problem/dmpg15s5 template <class C, class T> void add(C &diff, int N, int M, int u, int d, int l, int r, T v) { diff[u][l] += v; if (d + 1 < N) diff[d + 1][l] -= v; if (r + 1 < M) diff[u][r + 1] -= v; if (d + 1 < N && r + 1 < M) diff[d + 1][r + 1] += v; }
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "BitPrefixSumArray.h" using namespace std; // Wavelet Matrix supporting 2D aggregation queries where the data can change, // but not the keys // Indices are 0-indexed and ranges are inclusive // Queries bounded by 3 indices require a commutative operation, while queries // bounded by 4 indices also requires the data to be invertible // Template Arguments: // T: the type of the element of the array // R: struct supporting point updates and range queries on indices // Required Fields: // Data: the data type // Lazy: the lazy type // Required Functions: // static qdef(): returns the query default value // static merge(l, r): returns the values l of type Data merged with // r of type Data, must be associative and commutative // constructor(A): takes a vector A of type Data with the initial // value of each index // update(i, val): updates the index i with the value val // query(l, r): queries the range [l, r] // Sample Struct: supporting point increments updates and range sum queries // struct R { // using Data = int; // using Lazy = int; // static Data qdef() { return 0; } // static Data merge(const Data &l, const Data &r) { return l + r; } // FenwickTree1D<Data> FT; // R(const vector<Data> &A) : FT(A) {} // void update(int i, const Lazy &val) { FT.update(i, val); } // Data query(int l, int r) { return FT.query(l, r); } // }; // Cmp: the comparator to compare two elements of type T // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Constructor Arguments: // A: a vector of type T containing the initial keys of the array // X: a vector of type R::Data containing the initial data of the array // cmp: an instance of the Cmp struct // Functions: // update(i, v): updates the ith data with the lazy value v // query(l, r, hi): returns the aggregate value of the data associated with // all elements with a key less than or equal to hi (using the comparator) // in the range [l, r] // query(l, r, lo, hi): returns the aggregate value of the data associated // with all elements with a key of not less than lo and not greater than hi // (using the comparator) in the range [l, r] // bsearch(l, r, f): over all keys in the array, finds the first key k such // that query(l, r, k) returns true // In practice, has a small constant, faster than using a // 2D Sparse Fenwick Tree or Segment Tree // Time Complexity: // constructor: O((N + C) log N) where C is the time complexity of // R's constructor // update: O(U log N) where U is the time complexity of R's update function // query, bsearch: O(Q log N) where Q is the time complexity of // R's query function // Memory Complexity: O(N + (N log N) / 64 + M log N) where M is the memory // complexity of R // Tested: // Fuzz and Stress Tested // https://dmoj.ca/problem/dmopc19c7p5 template <class T, class R, class Cmp = less<T>> struct WaveletMatrixAggregation { #define clt [&] (const T &a, const T &b) { return cmp(a, b); } #define cle [&] (const T &a, const T &b) { return !cmp(b, a); } using Data = typename R::Data; using Lazy = typename R::Lazy; int N, H; Cmp cmp; vector<int> mid; vector<BitPrefixSumArray> B; vector<R> D; vector<T> S; WaveletMatrixAggregation(vector<T> A, const vector<Data> &X, Cmp cmp = Cmp()) : N(A.size()), H(N == 0 ? 0 : __lg(N) + 1), cmp(cmp), mid(H), B(H, BitPrefixSumArray(N)), S(move(A)) { vector<T> temp = S; sort(S.begin(), S.end(), cmp); vector<int> C(N), ind(N); for (int i = 0; i < N; i++) C[i] = lower_bound(S.begin(), S.end(), temp[i], cmp) - S.begin(); iota(ind.begin(), ind.end(), 0); D.reserve(H); vector<Data> Y = X; for (int h = H - 1; h >= 0; h--) { int ph = 1 << h; for (int i = 0; i < N; i++) B[h].set(i, C[ind[i]] <= ph - 1); mid[h] = stable_partition(ind.begin(), ind.end(), [&] (int i) { return C[i] <= ph - 1; }) - ind.begin(); B[h].build(); for (int i = 0; i < N; i++) Y[i] = X[ind[i]]; D.emplace_back(Y); for (int i = mid[h]; i < N; i++) C[ind[i]] -= ph; } reverse(D.begin(), D.end()); } void update(int i, const Lazy &v) { for (int h = H - 1; h >= 0; h--) { if (B[h].get(i)) i = B[h].query(i - 1); else i += mid[h] - B[h].query(i - 1); D[h].update(i, v); } } template <class F> Data qryPre(int h, int cur, int l, int r, const T &v, F f) { Data ret = R::qdef(); for (; h >= 0; h--) { int ph = 1 << h, ql = B[h].query(l - 1), qr = B[h].query(r); if (cur + ph - 1 >= N || f(v, S[cur + ph - 1])) { l = ql; r = qr - 1; } else { if (ql < qr) ret = R::merge(ret, D[h].query(ql, qr - 1)); cur += ph; l += mid[h] - ql; r += mid[h] - qr; } } return ret; } template <class F> Data qrySuf(int h, int cur, int l, int r, const T &v, F f) { Data ret = R::qdef(); for (; h >= 0; h--) { int ph = 1 << h, ql = B[h].query(l - 1), qr = B[h].query(r); if (cur + ph - 1 >= N || f(v, S[cur + ph - 1])) { if (l - ql <= r - qr) ret = R::merge(ret, D[h].query(l + mid[h] - ql, r + mid[h] - qr)); if (h == 0 && ql < qr) ret = R::merge(ret, D[h].query(ql, qr - 1)); l = ql; r = qr - 1; } else { if (h == 0 && l - ql <= r - qr) ret = R::merge(ret, D[h].query(l + mid[h] - ql, r + mid[h] - qr)); cur += ph; l += mid[h] - ql; r += mid[h] - qr; } } return ret; } Data query(int l, int r, const T &hi) { return qryPre(H - 1, 0, l, r, hi, clt); } Data query(int l, int r, const T &lo, const T &hi) { for (int cur = 0, h = H - 1; h >= 0; h--) { int ph = 1 << h, ql = B[h].query(l - 1), qr = B[h].query(r); bool loLeft = cur + ph - 1 >= N || !cmp(S[cur + ph - 1], lo); bool hiLeft = cur + ph - 1 >= N || cmp(hi, S[cur + ph - 1]); if (loLeft != hiLeft) { Data ret = R::merge(qrySuf(h - 1, cur, ql, qr - 1, lo, cle), qryPre(h - 1, cur + ph, l + mid[h] - ql, r + mid[h] - qr, hi, clt)); return h == 0 && ql < qr ? R::merge(ret, D[h].query(ql, qr - 1)) : ret; } else if (loLeft) { l = ql; r = qr - 1; } else { cur += ph; l += mid[h] - ql; r += mid[h] - qr; } } return R::qdef(); } template <class F> pair<bool, T *> bsearch(int l, int r, F f) { int cur = 0; Data agg = R::qdef(); for (int h = H - 1; h >= 0; h--) { int ql = B[h].query(l - 1), qr = B[h].query(r); Data val = ql < qr ? D[h].query(ql, qr - 1) : R::qdef(); if (f(R::merge(agg, val))) { l = ql; r = qr - 1; } else { cur += 1 << h; agg = R::merge(agg, val); l += mid[h] - ql; r += mid[h] - qr; } } return make_pair(cur < N, cur < N ? &S[cur] : nullptr); } #undef clt #undef cle };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Maintains the rank of an element in a multiset // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of the values being stored // Cmp: the comparator to compare two f(x) values, // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Constructor Arguments: // v: a vector of type T to initialize the structure // SCALE: the value to scale sqrt by // cmp: an instance of the Cmp struct // Functions: // rebuild(): rebuilds the multiset by moving all elements in the small // container to the large container // insert(val): inserts val into the multiset // aboveInd(val): returns the index of the smallest element where // val compares less than that element // ceilingInd(val): returns the index of the smallest element that // does not compare less than val // floorInd(val): returns the index of the largest element where // val does not compare less than that element // belowInd(val): returns the index of the largest element that // compares less than val // aboveVal(val): returns a pointer to the smallest element where // val compares less than that element, nullptr if it does not exist // ceilingVal(val): returns a pointer to the smallest element that // does not compare less than val, nullptr if it does not exist // floorVal(val): returns a pointer to the largest element where val does not // compare less than that element, nullptr if it does not exist // belowVal(val): returns a pointer to the largest element that // compares less than val, nullptr if it does not exist // above(val): returns a pair containing the index and a pointer to the // smallest element where val compares less than that element, // pointer is nullptr if it does not exist // ceiling(val): returns a pair containing the index and a pointer to the // smallest element that does not compare less than val, // pointer is nullptr if it does not exist // floor(val): returns a pair containing the index and a pointer to the // largest element where val does not compare less than that element, // pointer is nullptr if it does not exist // below(val): returns a pair containing the index and a pointer to the // largest element that compares less than val, // pointer is nullptr if it does not exist // contains(val): returns whether val is in the multiset or not // count(lo, hi): returns the number of values in the range [lo, hi] // empty(): returns whether the multiset is empty or not // size(): returns the number of elements the multiset // clear(): clears the multiset // values(): returns a vector of the sorted values in the multiset // In practice, has a very small constant, performs similarly to RootArray, // and is faster than balanced binary search trees // Time Complexity: // constructor: O(N) // insert: O(1) amortized // rebuild: O(sqrt N) // empty, size, clear: O(1) // floorInd, ceilingInd, aboveInd, belowInd: O(sqrt N) amortized // floorVal, ceilingVal, aboveVal, belowVal: O(sqrt N) amortized // floor, ceiling, above, below, contains, count: O(sqrt N) amortized // values: O(N) // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/dmopc19c3p3 // https://dmoj.ca/problem/ccc05s5 // https://mcpt.ca/problem/lcc18c5s3 // https://codeforces.com/contest/1093/problem/E template <class T, class Cmp = less<T>> struct SqrtBufferSimple { double SCALE; Cmp cmp; vector<T> small, large; SqrtBufferSimple(double SCALE = 1, Cmp cmp = Cmp()) : SCALE(SCALE), cmp(cmp) {} SqrtBufferSimple(vector<T> v, double SCALE = 1, Cmp cmp = Cmp()) : SCALE(SCALE), cmp(cmp), large(move(v)) { assert(is_sorted(large.begin(), large.end(), cmp)); } bool rebuild() { if (int(small.size()) > SCALE * sqrt(small.size() + large.size())) { int lSz = large.size(); sort(small.begin(), small.end(), cmp); for (auto &&x : small) large.push_back(x); inplace_merge(large.begin(), large.begin() + lSz, large.end(), cmp); small.clear(); return true; } return false; } void insert(const T &val) { small.push_back(val); } int aboveInd(const T &val) { rebuild(); int ret = upper_bound(large.begin(), large.end(), val, cmp) - large.begin(); for (auto &&x : small) ret += !cmp(val, x); return ret; } int ceilingInd(const T &val) { rebuild(); int ret = lower_bound(large.begin(), large.end(), val, cmp) - large.begin(); for (auto &&x : small) ret += cmp(x, val); return ret; } int floorInd(const T &val) { return aboveInd(val) - 1; } int belowInd(const T &val) { return ceilingInd(val) - 1; } T *aboveVal(const T &val) { rebuild(); T *y = nullptr; auto it = upper_bound(large.begin(), large.end(), val, cmp); if (it != large.end()) y = &*it; for (auto &&x : small) if (cmp(val, x) && (!y || cmp(x, *y))) y = &x; return y; } T *ceilingVal(const T &val) { rebuild(); T *y = nullptr; auto it = lower_bound(large.begin(), large.end(), val, cmp); if (it != large.end()) y = &*it; for (auto &&x : small) if (!cmp(x, val) && (!y || cmp(x, *y))) y = &x; return y; } T *floorVal(const T &val) { rebuild(); T *y = nullptr; auto it = upper_bound(large.begin(), large.end(), val, cmp); if (it != large.begin()) y = &*--it; for (auto &&x : small) if (!cmp(val, x) && (!y || cmp(*y, x))) y = &x; return y; } T *belowVal(const T &val) { rebuild(); T *y = nullptr; auto it = lower_bound(large.begin(), large.end(), val, cmp); if (it != large.begin()) y = &*--it; for (auto &&x : small) if (cmp(x, val) && (!y || cmp(*y, x))) y = &x; return y; } pair<int, T *> above(const T &val) { rebuild(); T *y = nullptr; auto it = upper_bound(large.begin(), large.end(), val, cmp); int cnt = it - large.begin(); if (it != large.end()) y = &*it; for (auto &&x : small) { if (!cmp(val, x)) cnt++; else if (!y || cmp(x, *y)) y = &x; } return make_pair(cnt, y); } pair<int, T *> ceiling(const T &val) { rebuild(); T *y = nullptr; auto it = lower_bound(large.begin(), large.end(), val, cmp); int cnt = it - large.begin(); if (it != large.end()) y = &*it; for (auto &&x : small) { if (cmp(x, val)) cnt++; else if (!y || cmp(x, *y)) y = &x; } return make_pair(cnt, y); } pair<int, T *> floor(const T &val) { rebuild(); T *y = nullptr; auto it = upper_bound(large.begin(), large.end(), val, cmp); int cnt = it - large.begin(); if (it != large.begin()) y = &*--it; for (auto &&x : small) if (!cmp(val, x)) { cnt++; if (!y || cmp(*y, x)) y = &x; } return make_pair(--cnt, y); } pair<int, T *> below(const T &val) { rebuild(); T *y = nullptr; auto it = lower_bound(large.begin(), large.end(), val, cmp); int cnt = it - large.begin(); if (it != large.begin()) y = &*--it; for (auto &&x : small) if (cmp(x, val)) { cnt++; if (!y || cmp(*y, x)) y = &x; } return make_pair(--cnt, y); } bool contains(const T &val) { if (binary_search(large.begin(), large.end(), val, cmp)) return true; if (rebuild() && binary_search(large.begin(), large.end(), val, cmp)) return true; for (auto &&x : small) if (!cmp(val, x) && !cmp(x, val)) return true; return false; } int count(const T &lo, const T &hi) { rebuild(); int ret = upper_bound(large.begin(), large.end(), hi, cmp) - lower_bound(large.begin(), large.end(), lo, cmp); for (auto &&x : small) ret += !cmp(x, lo) && !cmp(hi, x); return ret; } bool empty() const { return small.empty() && large.empty(); } int size() const { return int(small.size() + large.size()); } void clear() { small.clear(); large.clear(); } vector<T> values() const { vector<T> ret; ret.reserve(size()); for (auto &&x : small) ret.push_back(x); int mid = int(ret.size()); for (auto &&x : large) ret.push_back(x); inplace_merge(ret.begin(), ret.begin() + mid, ret.end(), cmp); return ret; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Decomposes the array recursively into N ^ (1 / R) containers of // size N ^ ((R - 1) / R) multiplied by a scale factor // Indices are 0-indexed and ranges are inclusive // Template Arguments: // R: the number of recursive levels // T: the type of data being stored // Constructor Arguments: // v: a vector of type T to initialize the structure // SCALE: the value to scale N ^ ((R - 1) / R) by // Functions: // insert(val, cmp): inserts val before the first index i where // cmp(at(i), val) is false assuming the data is sorted by cmp // insert_at(k, val): inserts val before index k (0 <= k <= N) // erase(val, cmp): erases the element at the first index i where // where cmp(at(i), val) and cmp(val, at(i)) are false, if it exists, // returns true if the element was erased, false otherwise // erase_at(k): erases the element at index k (0 <= k < N) // size(): returns the size of the array // empty(): returns whether or not the array is empty // front(): accessor or modifier for the first element in the array // back(): accessor or modifier for the first element in the array // push_front(val): adds the val to the front of the array // push_back(val): adds the val to the back of the array // pop_front(): removes the first element in the array // pop_back(): removes the last element in the array // at(k): accessor or modifier for the element at index k (0 <= k < N) // below(val, cmp): returns the index and a pointer to // the last element x where cmp(x, val) is true, // or (-1, nullptr) if none exist // floor(val, cmp): returns the index and a pointer to // the last element x where cmp(val, x) is false, // or (-1, nullptr) if none exist // ceiling(val, cmp): returns the index and a pointer to // the first element x where cmp(x, val) is false, // or (N, nullptr) if none exist // above(val, cmp): returns the index and a pointer to // the first element x where cmp(val, x) is true, // or (N, nullptr) if none exist // find(val, cmp): returns the index and a pointer to // the first element x where cmp(val, x) and cmp(x, val) are false, // or (N, nullptr) if none exist // values(): returns a vector of all values in the array // clear(): clears the array // In practice, has a very small constant, and is faster than balanced binary // search trees when R = 3, and SCALE = 6, even for N >= 1e7 // Time Complexity: // constructor: O(N) // insert, insert_at, erase, erase_at, push_front, pop_front, at: // O(R (I ^ (1 / R))) where I is the total number of insertions // below, floor, ceiling, above, find: // O(R (I ^ (1 / R))) where I is the total number of insertions // front, back, empty, size, pop_back: O(1) // push_back: O(1) amortized // values, clear: O(N) // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/ds4 // https://dmoj.ca/problem/cco10p3 // https://dmoj.ca/problem/ccc05s5 // https://dmoj.ca/problem/wc18c4s4 // https://judge.yosupo.jp/problem/predecessor_problem template <const int R, class T> struct RootArray { static_assert(R > 0, "R must be positive"); int N; vector<RootArray<R - 1, T>> A; double SCALE; int getRootN() { if (N == 0) return 0; int lg = __lg(N); lg -= lg / R; return SCALE * (1 << lg); } RootArray(double SCALE = 6) : N(0), SCALE(SCALE) { assert(SCALE > 0); } RootArray(const vector<T> &v, double SCALE = 6) : N(v.size()), SCALE(SCALE) { assert(SCALE > 0); if (N == 0) return; int rootN = getRootN(); A.reserve((N - 1) / rootN + 1); for (int i = 0; i < N; i += rootN) { int en = min(i + rootN, N); A.emplace_back(vector<T>(make_move_iterator(v.begin() + i), make_move_iterator(v.begin() + en)), SCALE); } } void split(int i) { int rootN = getRootN(); if (int(A[i].size()) > 2 * rootN) { vector<T> tmp; tmp.reserve(int(A[i].size()) - rootN); while (int(A[i].size()) > rootN) { tmp.push_back(move(A[i].back())); A[i].pop_back(); } reverse(tmp.begin(), tmp.end()); A.emplace(A.begin() + i + 1, move(tmp), SCALE); } } template <class Comp> void insert(const T &val, Comp cmp) { if (N++ == 0) { A.emplace_back(SCALE); A.back().insert(val, cmp); return; } int i = 0; while (i < int(A.size()) && cmp(A[i].back(), val)) i++; if (i >= int(A.size())) i = int(A.size()) - 1; A[i].insert(val, cmp); split(i); } void insert_at(int k, const T &val) { if (k == N) { push_back(val); return; } N++; int i = 0; while (int(A[i].size()) <= k) k -= int(A[i++].size()); A[i].insert_at(k, val); split(i); } template <class Comp> bool erase(const T &val, Comp cmp) { int i = 0; while (i < int(A.size()) && cmp(A[i].back(), val)) i++; if (i >= int(A.size()) || !A[i].erase(val, cmp)) return false; if (A[i].empty()) A.erase(A.begin() + i); N--; return true; } void erase_at(int k) { int i = 0; while (int(A[i].size()) <= k) k -= int(A[i++].size()); N--; A[i].erase_at(k); if (A[i].empty()) A.erase(A.begin() + i); } int size() const { return N; } bool empty() const { return N == 0; } const T &front() const { return A.front().front(); } T &front() { return A.front().front(); } const T &back() const { return A.back().back(); } T &back() { return A.back().back(); } void push_front(const T &val) { if (N++ == 0) { A.emplace_back(SCALE); A.back().push_back(val); return; } A.front().push_front(val); split(0); } void push_back(const T &val) { if (N++ == 0) { A.emplace_back(SCALE); A.back().push_back(val); return; } A.back().push_back(val); split(int(A.size()) - 1); } void pop_front() { N--; A.front().pop_front(); if (A.front().empty()) A.erase(A.begin()); } void pop_back() { N--; A.back().pop_back(); if (A.back().empty()) A.pop_back(); } const T &at(int k) const { int i = 0; while (int(A[i].size()) <= k) k -= int(A[i++].size()); return A[i].at(k); } T &at(int k) { int i = 0; while (int(A[i].size()) <= k) k -= int(A[i++].size()); return A[i].at(k); } template <class Comp> pair<int, T *> below(const T &val, Comp cmp) { int i = 0, k = 0; while (i < int(A.size()) && cmp(A[i].front(), val)) k += int(A[i++].size()); if (--i >= 0) k -= int(A[i].size()); else return make_pair(-1, nullptr); pair<int, T *> ret = A[i].below(val, cmp); ret.first += k; return ret; } template <class Comp> pair<int, T *> floor(const T &val, Comp cmp) { int i = 0, k = 0; while (i < int(A.size()) && !cmp(val, A[i].front())) k += int(A[i++].size()); if (--i >= 0) k -= int(A[i].size()); else return make_pair(-1, nullptr); pair<int, T *> ret = A[i].floor(val, cmp); ret.first += k; return ret; } template <class Comp> pair<int, T *> ceiling(const T &val, Comp cmp) { int i = 0, k = 0; while (i < int(A.size()) && cmp(A[i].back(), val)) k += int(A[i++].size()); if (i >= int(A.size())) return make_pair(N, nullptr); pair<int, T *> ret = A[i].ceiling(val, cmp); ret.first += k; return ret; } template <class Comp> pair<int, T *> above(const T &val, Comp cmp) { int i = 0, k = 0; while (i < int(A.size()) && !cmp(val, A[i].back())) k += int(A[i++].size()); if (i >= int(A.size())) return make_pair(N, nullptr); pair<int, T *> ret = A[i].above(val, cmp); ret.first += k; return ret; } template <class Comp> pair<int, T *> find(const T &val, Comp cmp) { pair<int, T *> ret = ceiling(val, cmp); if (!ret.second || cmp(val, *(ret.second)) || cmp(*(ret.second), val)) return make_pair(N, nullptr); return ret; } vector<T> values() const { vector<T> ret; ret.reserve(N); for (auto &&ai : A) for (auto &&aij : ai.values()) ret.push_back(aij); return ret; } void clear() { N = 0; A.clear(); } }; template <class T> struct RootArray<1, T> : public vector<T> { using vector<T>::begin; using vector<T>::end; using vector<T>::size; using vector<T>::at; RootArray(double = 6) {} RootArray(const vector<T> &v, double = 6) : vector<T>(v) {} template <class Comp> void insert(const T &val, Comp cmp) { vector<T>::insert(lower_bound(begin(), end(), val, cmp), val); } void insert_at(int k, const T &val) { vector<T>::insert(begin() + k, val); } template <class Comp> bool erase(const T &val, Comp cmp) { auto it = lower_bound(begin(), end(), val, cmp); if (it == end() || cmp(*it, val) || cmp(val, *it)) return false; vector<T>::erase(it); return true; } void erase_at(int k) { vector<T>::erase(begin() + k); } void push_front(const T &val) { vector<T>::insert(begin(), val); } void pop_front() { vector<T>::erase(begin()); } template <class Comp> pair<int, T *> below(const T &val, Comp cmp) { int i = lower_bound(begin(), end(), val, cmp) - begin() - 1; return make_pair(i, i < 0 ? nullptr : &at(i)); } template <class Comp> pair<int, T *> floor(const T &val, Comp cmp) { int i = upper_bound(begin(), end(), val, cmp) - begin() - 1; return make_pair(i, i < 0 ? nullptr : &at(i)); } template <class Comp> pair<int, T *> ceiling(const T &val, Comp cmp) { int i = lower_bound(begin(), end(), val, cmp) - begin(); return make_pair(i, i >= int(size()) ? nullptr : &at(i)); } template <class Comp> pair<int, T *> above(const T &val, Comp cmp) { int i = upper_bound(begin(), end(), val, cmp) - begin(); return make_pair(i, i >= int(size()) ? nullptr : &at(i)); } template <class Comp> pair<int, T *> find(const T &val, Comp cmp) { pair<int, T *> ret = ceiling(val, cmp); if (!ret.second || cmp(val, *(ret.second)) || cmp(*(ret.second), val)) return make_pair(size(), nullptr); return ret; } RootArray<1, T> values() const { return *this; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> using namespace std; // Maintains the rank of an element in a multiset, allowing for multiple // insertions of the same element at the same time (including negative) // Note that elements with a count of 0 or negative are still in the multiset // as elements cannot be removed // Indices are 0-indexed and ranges are inclusive // Template Arguments: // T: the type of the values being stored // CountType: the type of the count of elements in the set // Cmp: the comparator to compare two f(x) values, // Required Functions: // operator (a, b): returns true if and only if a compares less than b // Constructor Arguments: // v: a vector of type pair<T, CountType> to initialize the structure // SCALE: the value to scale sqrt by // cmp: an instance of the Cmp struct // Functions: // rebuild(): rebuilds the multiset by moving all elements in the small // container to the large container // insert(p): inserts the element p.first with a count of p.second // into the multiset // emplace(v, c): inserts the element v with a count of c // into the multiset // aboveInd(val): returns the index of the smallest element where // val compares less than that element // ceilingInd(val): returns the index of the smallest element that // does not compare less than val // floorInd(val): returns the index of the largest element where // val does not compare less than that element // belowInd(val): returns the index of the largest element that // compares less than val // contains(val): returns whether val is in the multiset or not // count(lo, hi): returns the number of values in the range [lo, hi] // empty(): returns whether the multiset is empty or not // count(): returns the number of elements the multiset // clear(): clears the multiset // values(): returns a vector of pairs containing the sorted values and // their count in the multiset // In practice, has a very small constant, performs similarly to RootArray, // and is faster than balanced binary search trees // Time Complexity: // constructor: O(N) // insert: O(1) amortized // rebuild: O(sqrt N) // count(): O(1) // floor, ceiling, above, below, contains, count(val), count(lo, hi): // O(sqrt N) amortized // valuesAndCount: O(N) // Memory Complexity: O(N) // Tested: // https://dmoj.ca/problem/apio19p3 // https://dmoj.ca/problem/ioi01p1 template <class T, class CountType, class Cmp = less<T>> struct SqrtBuffer { struct PairCmp { Cmp cmp; PairCmp(Cmp cmp) : cmp(cmp) {} bool operator () (const pair<T, CountType> &a, const pair<T, CountType> &b) const { return cmp(a.first, b.first); } }; CountType tot; double SCALE; PairCmp pcmp; vector<pair<T, CountType>> small, large; SqrtBuffer(double SCALE = 1, Cmp cmp = Cmp()) : tot(CountType()), SCALE(SCALE), pcmp(PairCmp(cmp)) {} SqrtBuffer(vector<pair<T, CountType>> v, double SCALE = 1, Cmp cmp = Cmp()) : tot(CountType()), SCALE(SCALE), pcmp(PairCmp(cmp)), large(move(v)) { assert(is_sorted(large.begin(), large.end(), pcmp)); resizeUnique(large); for (auto &&p : large) tot += p.second; } void resizeUnique(vector<pair<T, CountType>> &v) { if (!v.empty()) { int j = 0; for (int i = 1; i < int(v.size()); i++) { if (Cmp()(v[i].first, v[j].first) || Cmp()(v[j].first, v[i].first)) { v[++j] = v[i]; v[j].second += v[j - 1].second; } else v[j].second += v[i].second; } v.erase(v.begin() + j + 1, v.end()); } } bool rebuild() { if (int(small.size()) > SCALE * sqrt(small.size() + large.size())) { int lSz = large.size(); sort(small.begin(), small.end(), pcmp); for (int i = lSz - 1; i > 0; i--) large[i].second -= large[i - 1].second; for (auto &&p : small) large.push_back(p); inplace_merge(large.begin(), large.begin() + lSz, large.end(), pcmp); resizeUnique(large); small.clear(); return true; } return false; } void insert(const pair<T, CountType> &p) { small.push_back(p); tot += p.second; } void emplace(const T &v, const CountType &c) { small.emplace_back(v, c); tot += c; } CountType aboveInd(const T &val) { rebuild(); int ind = upper_bound(large.begin(), large.end(), make_pair(val, CountType()), pcmp) - large.begin(); CountType ret = ind == 0 ? CountType() : large[ind - 1].second; for (auto &&p : small) if (!Cmp()(val, p.first)) ret += p.second; return ret; } CountType ceilingInd(const T &val) { rebuild(); int ind = lower_bound(large.begin(), large.end(), make_pair(val, CountType()), pcmp) - large.begin(); CountType ret = ind == 0 ? CountType() : large[ind - 1].second; for (auto &&p : small) if (Cmp()(p.first, val)) ret += p.second; return ret; } CountType floorInd(const T &val) { return aboveInd(val) - 1; } CountType belowInd(const T &val) { return ceilingInd(val) - 1; } bool contains(const T &val) { if (binary_search(large.begin(), large.end(), make_pair(val, CountType()), pcmp)) return true; if (rebuild() && binary_search(large.begin(), large.end(), make_pair(val, CountType()), pcmp)) return true; for (auto &&p : small) if (!Cmp()(val, p.first) && !Cmp()(p.first, val)) return true; return false; } CountType count(const T &lo, const T &hi) { rebuild(); int ind = upper_bound(large.begin(), large.end(), make_pair(hi, CountType()), pcmp) - large.begin(); CountType ret = ind == 0 ? CountType() : large[ind - 1].second; ind = lower_bound(large.begin(), large.end(), make_pair(lo, CountType()), pcmp) - large.begin(); ret -= ind == 0 ? CountType() : large[ind - 1].second; for (auto &&p : small) if (!Cmp()(p.first, lo) && !Cmp()(hi, p.first)) ret += p.second; return ret; } CountType count() const { return tot; } void clear() { tot = CountType(); small.clear(); large.clear(); } vector<pair<T, CountType>> valuesAndCount() const { vector<pair<T, CountType>> ret; ret.reserve(large.size() + small.size()); for (auto &&p : small) ret.push_back(p); int mid = int(ret.size()); for (auto &&p : large) ret.push_back(p); inplace_merge(ret.begin(), ret.begin() + mid, ret.end(), pcmp); resizeUnique(ret); return ret; } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }
#pragma once #include <bits/stdc++.h> #include "../trees/PersistentArray.h" using namespace std; // Persistent Union Find by size where copy assignment/constructor creates // a new version of the data structure // Indices are 0-indexed // Constructor Arguments: // N: the number of elements in the set // Fields: // UF: a vector of integers representing the parent of each element in the // tree, or the negative of the size of the set if that element is a root // cnt: the current number of disjoint sets // Functions: // find(v): finds the root of the set containing element v in the // current version // join(v, w): merges the sets containing v and w, returns true if they // were originally disjoint before the merge in the current version, // false otherwise // connected(v, w): returns true if v and w are in the same set in the // current version, false otherwise // getSize(v): returns the size of the set containing element v in the // current version // In practice, has a moderate constant // Time Complexity: // constructor: O(N) // find, join, connected, getSize: O((log N)^2) // Memory Complexity: O(N log N) // Tested: // https://judge.yosupo.jp/problem/persistent_unionfind struct PersistentUnionFind { PersistentArray<int> UF; int cnt; PersistentUnionFind(int N) : UF(N, -1), cnt(N) {} int find(int v) { int ufv = UF.get(v); return ufv < 0 ? v : find(ufv); } bool join(int v, int w) { if ((v = find(v)) == (w = find(w))) return false; int ufv = UF.get(v), ufw = UF.get(w); if (ufv > ufw) { swap(v, w); swap(ufv, ufw); } UF.set(v, ufv + ufw); UF.set(w, v); cnt--; return true; } bool connected(int v, int w) { return find(v) == find(w); } int getSize(int v) { return -UF.get(find(v)); } };
{ "repo_name": "wesley-a-leung/Resources", "stars": "34", "repo_language": "C++", "file_name": "SkewHeapIncremental.h", "mime_type": "text/x-c++" }