From d76602e86ac6888ae8fe00e584366133c9d47a33 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Wed, 25 Mar 2020 01:39:46 +0530 Subject: [PATCH 01/47] refactoring my coding library --- .gitignore | 32 ++ IterativeTreeTraversal_JAVA_1.java | 76 ---- IterativeTreeTraversal_JAVA_2.java | 67 ---- .../DP/dp-on-digits-tutorial.cpp | 0 .../DP/dp-on-digits.cpp | 0 Library/DS/2DBIT.cpp | 50 +++ Library/DS/2dSparseTable.cpp | 95 +++++ Library/DS/ConvexHulDynamicMin.cpp | 94 +++++ Library/DS/ConvexHull.cpp | 104 +++++ Library/DS/ConvexHullDynamicMax.cpp | 35 ++ Library/DS/ConvexHullDynamicMinMax.cpp | 143 +++++++ Library/DS/HV-Intersection-PBDS.cpp | 163 ++++++++ Library/DS/MaxBIT_with_pos_track.cpp | 125 ++++++ Library/DS/UnionFind.cpp | 36 ++ Library/DS/bit.cpp | 53 +++ Library/DS/bitset.cpp | 65 +++ Library/DS/convex-hull-min-nikalsb.cpp | 40 ++ Library/DS/heap.cpp | 54 +++ Library/DS/points-in-rectangle-KDTREE.cpp | 225 +++++++++++ Library/DS/policy-based-set.cpp | 40 ++ Library/DS/segment_tree_point_update.cpp | 79 ++++ Library/DS/sparse_table_2d.cpp | 49 +++ Library/DS/treap_reversal.cpp | 193 +++++++++ Library/DS/treaps.cpp | 199 ++++++++++ Library/Graph/BCC.cpp | 56 +++ Library/Graph/Dijkstra.cpp | 103 +++++ Library/Graph/Dijkstra_Khattar_Style.cpp | 150 +++++++ Library/Graph/Euler_Circuit.cpp | 102 +++++ Library/Graph/MST.cpp | 65 +++ Library/Graph/MinCostMaxFlow.cpp | 143 +++++++ Library/Math/FibGP.cpp | 24 ++ Library/Math/GP.cpp | 24 ++ Library/Math/MatrixPow.cpp | 15 + Library/Math/Seive/euler_phi.cpp | 21 + Library/Math/Seive/extended_gcd.cpp | 42 ++ Library/Math/Seive/seive_totient.cpp | 36 ++ Library/Math/SmallestPrimeSeive.cpp | 17 + Library/Math/bigint.cpp | 25 ++ Library/Math/dec2bin.cpp | 13 + Library/Math/fact_ncr.cpp | 20 + Library/Math/geometry.cpp | 374 ++++++++++++++++++ Library/Math/linear_recurrence.cpp | 234 +++++++++++ Library/Math/matrix.cpp | 114 ++++++ Library/Math/matrix_math_operations.cpp | 99 +++++ Library/Math/projecteuelr/Euler.py | 329 +++++++++++++++ .../Miller-rabin-primality-test.cpp | 78 ++++ Library/Math/vector_physics.cpp | 33 ++ Library/Miscellanious/2-sat.cpp | 92 +++++ Library/Miscellanious/MosMaxFrequency.cpp | 171 ++++++++ .../Miscellanious}/SmallToLarge.cpp | 0 Library/Miscellanious/hash_adjaceny_list.cpp | 148 +++++++ Library/Miscellanious/hash_unordered_map.cpp | 22 ++ Library/Miscellanious/meet-in-middle.cpp | 113 ++++++ Library/Miscellanious/normal_round.cpp | 13 + .../Miscellanious/overlapping_intervals.cpp | 86 ++++ .../Miscellanious}/parallel_binary_search.cpp | 0 Library/Miscellanious/popcount.cpp | 20 + Library/Miscellanious/range_sum.cpp | 98 +++++ .../Miscellanious}/sliding_window.cpp | 0 Library/Miscellanious/sliding_window_2.cpp | 38 ++ Library/Miscellanious/sos_dp.cpp | 72 ++++ Library/Miscellanious/template.cpp | 73 ++++ .../Miscellanious}/ternary_search.cpp | 0 Library/Miscellanious/z-algo.cpp | 26 ++ Library/Tree/Centroid.cpp | 113 ++++++ {Tree => Library/Tree}/HLD.cpp | 0 .../Tree}/centroid_decomposition.cpp | 0 {Tree => Library/Tree}/centroid_example.cpp | 0 .../Tree/dp-on-tree-type-c-LCA.cpp | 0 Library/Tree/lca.cpp | 99 +++++ Library/Tree/lca_in_out_dp.cpp | 144 +++++++ {Tree => Library/Tree}/lca_sparse_min.cpp | 0 {Trie => Library/Tree}/trie-xor.cpp | 0 Library/galt/2Dsparse_table.cpp | 222 +++++++++++ .../Codechef}/DEC17/CHEFEXQ.cpp | 0 .../Codechef}/NOV17/CSUBQ.cpp | 0 .../2019/QualificationRound/Problem A.cpp | 0 .../2019/QualificationRound/Problem B.cpp | 0 .../2019/QualificationRound/Problem C.cpp | 0 .../Problem A[Robot Programming Strategy].cpp | 0 .../Round1C/Problem B[Power Arrangers].cpp | 0 .../CacheStoreWithTTL.cpp | 0 .../iterative-tree-traversal-1.cpp | 0 .../iterative-tree-traversal-2.cpp | 0 .../tricky-oops-problem.cpp | 0 85 files changed, 5541 insertions(+), 143 deletions(-) create mode 100644 .gitignore delete mode 100644 IterativeTreeTraversal_JAVA_1.java delete mode 100644 IterativeTreeTraversal_JAVA_2.java rename dp-on-matrices.cpp => Library/DP/dp-on-digits-tutorial.cpp (100%) rename dp-on-digits.cpp => Library/DP/dp-on-digits.cpp (100%) create mode 100755 Library/DS/2DBIT.cpp create mode 100755 Library/DS/2dSparseTable.cpp create mode 100755 Library/DS/ConvexHulDynamicMin.cpp create mode 100755 Library/DS/ConvexHull.cpp create mode 100755 Library/DS/ConvexHullDynamicMax.cpp create mode 100755 Library/DS/ConvexHullDynamicMinMax.cpp create mode 100755 Library/DS/HV-Intersection-PBDS.cpp create mode 100755 Library/DS/MaxBIT_with_pos_track.cpp create mode 100755 Library/DS/UnionFind.cpp create mode 100755 Library/DS/bit.cpp create mode 100755 Library/DS/bitset.cpp create mode 100755 Library/DS/convex-hull-min-nikalsb.cpp create mode 100755 Library/DS/heap.cpp create mode 100755 Library/DS/points-in-rectangle-KDTREE.cpp create mode 100755 Library/DS/policy-based-set.cpp create mode 100755 Library/DS/segment_tree_point_update.cpp create mode 100755 Library/DS/sparse_table_2d.cpp create mode 100755 Library/DS/treap_reversal.cpp create mode 100755 Library/DS/treaps.cpp create mode 100755 Library/Graph/BCC.cpp create mode 100755 Library/Graph/Dijkstra.cpp create mode 100755 Library/Graph/Dijkstra_Khattar_Style.cpp create mode 100755 Library/Graph/Euler_Circuit.cpp create mode 100755 Library/Graph/MST.cpp create mode 100755 Library/Graph/MinCostMaxFlow.cpp create mode 100755 Library/Math/FibGP.cpp create mode 100755 Library/Math/GP.cpp create mode 100755 Library/Math/MatrixPow.cpp create mode 100755 Library/Math/Seive/euler_phi.cpp create mode 100755 Library/Math/Seive/extended_gcd.cpp create mode 100755 Library/Math/Seive/seive_totient.cpp create mode 100755 Library/Math/SmallestPrimeSeive.cpp create mode 100755 Library/Math/bigint.cpp create mode 100755 Library/Math/dec2bin.cpp create mode 100755 Library/Math/fact_ncr.cpp create mode 100755 Library/Math/geometry.cpp create mode 100755 Library/Math/linear_recurrence.cpp create mode 100755 Library/Math/matrix.cpp create mode 100755 Library/Math/matrix_math_operations.cpp create mode 100755 Library/Math/projecteuelr/Euler.py create mode 100755 Library/Math/projecteuelr/Miller-rabin-primality-test.cpp create mode 100755 Library/Math/vector_physics.cpp create mode 100755 Library/Miscellanious/2-sat.cpp create mode 100755 Library/Miscellanious/MosMaxFrequency.cpp rename {Tree => Library/Miscellanious}/SmallToLarge.cpp (100%) mode change 100644 => 100755 create mode 100755 Library/Miscellanious/hash_adjaceny_list.cpp create mode 100755 Library/Miscellanious/hash_unordered_map.cpp create mode 100755 Library/Miscellanious/meet-in-middle.cpp create mode 100755 Library/Miscellanious/normal_round.cpp create mode 100755 Library/Miscellanious/overlapping_intervals.cpp rename {Miscellanious => Library/Miscellanious}/parallel_binary_search.cpp (100%) mode change 100644 => 100755 create mode 100755 Library/Miscellanious/popcount.cpp create mode 100755 Library/Miscellanious/range_sum.cpp rename {Miscellanious => Library/Miscellanious}/sliding_window.cpp (100%) mode change 100644 => 100755 create mode 100755 Library/Miscellanious/sliding_window_2.cpp create mode 100755 Library/Miscellanious/sos_dp.cpp create mode 100644 Library/Miscellanious/template.cpp rename {Miscellanious => Library/Miscellanious}/ternary_search.cpp (100%) mode change 100644 => 100755 create mode 100755 Library/Miscellanious/z-algo.cpp create mode 100755 Library/Tree/Centroid.cpp rename {Tree => Library/Tree}/HLD.cpp (100%) mode change 100644 => 100755 rename {Tree => Library/Tree}/centroid_decomposition.cpp (100%) mode change 100644 => 100755 rename {Tree => Library/Tree}/centroid_example.cpp (100%) mode change 100644 => 100755 rename dp-on-tree-type-c-LCA.cpp => Library/Tree/dp-on-tree-type-c-LCA.cpp (100%) create mode 100755 Library/Tree/lca.cpp create mode 100755 Library/Tree/lca_in_out_dp.cpp rename {Tree => Library/Tree}/lca_sparse_min.cpp (100%) mode change 100644 => 100755 rename {Trie => Library/Tree}/trie-xor.cpp (100%) mode change 100644 => 100755 create mode 100755 Library/galt/2Dsparse_table.cpp rename {Codechef => MyOnlineSubmissions/Codechef}/DEC17/CHEFEXQ.cpp (100%) rename {Codechef => MyOnlineSubmissions/Codechef}/NOV17/CSUBQ.cpp (100%) rename {Google-CodeJam => MyOnlineSubmissions/Google-CodeJam}/2019/QualificationRound/Problem A.cpp (100%) rename {Google-CodeJam => MyOnlineSubmissions/Google-CodeJam}/2019/QualificationRound/Problem B.cpp (100%) rename {Google-CodeJam => MyOnlineSubmissions/Google-CodeJam}/2019/QualificationRound/Problem C.cpp (100%) rename {Google-CodeJam => MyOnlineSubmissions/Google-CodeJam}/2019/Round1C/Problem A[Robot Programming Strategy].cpp (100%) rename {Google-CodeJam => MyOnlineSubmissions/Google-CodeJam}/2019/Round1C/Problem B[Power Arrangers].cpp (100%) rename CacheStoreWithTTL.cpp => Tricks/CacheStoreWithTTL.cpp (100%) rename iterative-tree-traversal-1.cpp => Tricks/iterative-tree-traversal-1.cpp (100%) rename iterative-tree-traversal-2.cpp => Tricks/iterative-tree-traversal-2.cpp (100%) rename tricky-oops-problem.cpp => Tricks/tricky-oops-problem.cpp (100%) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d99efa9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app \ No newline at end of file diff --git a/IterativeTreeTraversal_JAVA_1.java b/IterativeTreeTraversal_JAVA_1.java deleted file mode 100644 index e86da51..0000000 --- a/IterativeTreeTraversal_JAVA_1.java +++ /dev/null @@ -1,76 +0,0 @@ - -// ? ============= USING HASH-MAP ============= - -import java.util.*; - -// ! NOTE : while using this don'toverride the equals()&hashCode()method in Node Class - -class Node { - int val; - Node left, right; - - Node(int val) { - this.val = val; - left = right = null; - } -} - -class IterativeMagic { - - public static void traversalTrick(Node root) { // postorder - - HashMap state = new HashMap(); - Stack s = new Stack(); - s.push(root); - - while (!s.empty()) { - Node curNode = s.peek(); - - if (curNode == null) { - s.pop(); - continue; - } - - int curState; - if (!state.containsKey(curNode))// if no state exits till now - give it a state 0 - state.put(curNode, 0); - - curState = state.get(curNode); - - switch (curState) { - case 0: - s.push(curNode.left); - break; - case 1: - s.push(curNode.right); - break; - case 2: - System.out.print(curNode.val + " "); - break; - default: - s.pop(); - } - - state.put(curNode, curState + 1); // change its current state : previous state's task done - } - } - -} - -public class IterativeTreeTraversal_JAVA_1 { - - public static void main(String... args) { - Node tmp = new Node(7); - Node root = tmp; - - root.left = new Node(3); - root.right = new Node(10); - root.left.left = new Node(2); - root.left.right = new Node(5); - root.left.left.left = new Node(1); - root.right.left = new Node(8); - root.right.right = new Node(5); - - IterativeMagic.traversalTrick(tmp); - } -} diff --git a/IterativeTreeTraversal_JAVA_2.java b/IterativeTreeTraversal_JAVA_2.java deleted file mode 100644 index 3bb332e..0000000 --- a/IterativeTreeTraversal_JAVA_2.java +++ /dev/null @@ -1,67 +0,0 @@ - -// ? ============= WITHOUT HASH-MAP ============= - -import java.util.*; -import javafx.util.Pair; //? *** - -// ! NOTE : while using this don'toverride the equals()&hashCode()method in Node Class -class Node { - int val; - Node left, right; - - Node(int val) { - this.val = val; - left = right = null; - } -} - -class IterativeMagic { - - public static void traversalTrick(Node root) { // ! inorder - - Stack> s = new Stack>(); - s.push(new Pair<>(root, 0)); - - while (!s.empty()) { - Pair p = s.pop(); - Node curNode = p.getKey(); - int state = p.getValue(); - - if (curNode == null || state == 3) { - continue; - } - - s.push(new Pair<>(curNode, state + 1)); // new State - - switch (state) { - case 0: - s.push(new Pair<>(curNode.left, 0)); - break; - case 1: - System.out.print(curNode.val + " "); - break; - case 2: - s.push(new Pair<>(curNode.right, 0)); - break; - } - } - } -} - -public class IterativeTreeTraversal_JAVA_2 { - - public static void main(String... args) { - Node t = new Node(7); - Node root = t; - - t.left = new Node(3); - t.right = new Node(10); - t.left.left = new Node(2); - t.left.right = new Node(5); - t.left.left.left = new Node(1); - t.right.left = new Node(8); - t.right.right = new Node(12); - - IterativeMagic.traversalTrick(root); - } -} diff --git a/dp-on-matrices.cpp b/Library/DP/dp-on-digits-tutorial.cpp similarity index 100% rename from dp-on-matrices.cpp rename to Library/DP/dp-on-digits-tutorial.cpp diff --git a/dp-on-digits.cpp b/Library/DP/dp-on-digits.cpp similarity index 100% rename from dp-on-digits.cpp rename to Library/DP/dp-on-digits.cpp diff --git a/Library/DS/2DBIT.cpp b/Library/DS/2DBIT.cpp new file mode 100755 index 0000000..e95078d --- /dev/null +++ b/Library/DS/2DBIT.cpp @@ -0,0 +1,50 @@ +const int N = 305, M = 305; +class BIT_2D{ + int bit[N][M]; + int inf; + public: + BIT_2D(){ + inf = 1e9; + int i, j; + fo(i, N) fo(j, M) bit[i][j] = inf; + } + int f(int x){ + return x&(-x); + } + void add(int x, int y, int val){ + int Y = y; + while(x <= N){ + y = Y; + while(y <= M){ + bit[x][y] = min(bit[x][y], val); + y += f(y); + } + x += f(x); + } + } + int get(int x, int y){ + int Y = y; + int ans = mod; + while(x){ + y = Y; + while(y){ + ans = min(bit[x][y], ans); + y -= f(y); + } + x -= f(x); + } + return ans; + } + void clear(int x, int y){ + int Y = y; + while(x <= N){ + y = Y; + while(y <= M){ + bit[x][y] = inf; + y += f(y); + } + x += f(x); + } + } + +}; diff --git a/Library/DS/2dSparseTable.cpp b/Library/DS/2dSparseTable.cpp new file mode 100755 index 0000000..d68b8f2 --- /dev/null +++ b/Library/DS/2dSparseTable.cpp @@ -0,0 +1,95 @@ +//second file is better +//ye codechef wala submission h mera +const int N = 1003; +int a[N][N], dp[N][N][10][10]; +const int lg = 10; +//lg is 1 power greater than N +ll dpp[N][N]; + +int st[N]; +int max(int a, int b, int c, int d){ + return max(a, max(b, max(c, d))); +} +int n, m; +void mem(){ + int i,j,x,y,k; + st[1] = 0; + int c = 0; + Fo(i, 2, N) + { + int v = (1 << c); + if (v + v < i) + c++; + st[i] = c; + } + fo(i, n) + fo(j, m) + dp[i][j][0][0] = a[i][j]; + + Fo(i, 0, n) + { + Fo(k, 1, lg) + { + int val = (1 << k); + int nval = val / 2; + Fo(j, 0, m) + { + if (j + val > m) + break; + dp[i][j][k][0] = max(dp[i][j][k - 1][0], dp[i][j + nval][k - 1][0]); + } + } + } + Fo(j, 0, m) + { + Fo(k, 1, lg) + { + int val = (1 << k); + int nval = val / 2; + Fo(i, 0, n) + { + if (i + val > n) + break; + dp[i][j][0][k] = max(dp[i][j][0][k - 1], dp[i + nval][j][0][k - 1]); + } + } + } + int k1,k2,st2; + + int st1=st2=lg-1; + + Fo(k1, 1, st1 + 1) + { + int val1 = (1 << k1); + int nval1 = val1 / 2; + Fo(k2, 1, st2 + 1) + { + int val2 = (1 << k2); + int nval2 = val2 / 2; + Fo(i, 0, n) + { + Fo(j, 0, m) + { + if ((j + val1 > m) || (i + val2 > n)) + continue; + + dp[i][j][k1][k2] = max(dp[i][j][k1 - 1][k2 - 1], dp[i + nval2][j][k1 - 1][k2 - 1], dp[i][j+nval1][k1 - 1][k2 - 1], dp[i + nval2][j+nval1][k1 - 1][k2 - 1]); + } + } + } + } + +} + +int query(int i, int j, int down, int k){ + int dx = down - i + 1; + int dy = k - j + 1; + int k1 = st[dy]; + int k2 = st[dx]; + int val1 = (1 << k1); + int val2 = (1 << k2); + int dp1 = max(dp[i][j][k1][k2], dp[i][k-val1+1][k1][k2]); + int dp2 = max(dp[down - val2 + 1][j][k1][k2], dp[down - val2 + 1][k - val1 + 1][k1][k2]); + return max(dp1,dp2); + +} diff --git a/Library/DS/ConvexHulDynamicMin.cpp b/Library/DS/ConvexHulDynamicMin.cpp new file mode 100755 index 0000000..0bf5f7a --- /dev/null +++ b/Library/DS/ConvexHulDynamicMin.cpp @@ -0,0 +1,94 @@ +struct cht{ + struct Line{ + int a; + long long b; + long long val; + double xLeft; + bool type; + Line(long long _a = 0 , long long _b = 0){ + a = _a; + b = _b; + xLeft = -1e16; + type = 0; + val = 0; + } + long long valueAt(int x) const{ + return 1LL * a * x + b; + } + friend bool areParallel(const Line &l1, const Line &l2){ + return l1.a == l2.a; + } + friend double intersectX(const Line &l1 , const Line &l2){ + return areParallel(l1 , l2) ? 1e16 : 1.0 * (l2.b - l1.b) / (l1.a - l2.a); + } + bool operator < (const Line &l2) const{ + if(!l2.type) + return a < l2.a; + return xLeft > l2.val; + } + }; + set < Line > hull; + bool hasPrev(set < Line > :: iterator it){ + return it != hull.begin(); + } + bool hasNext(set < Line > :: iterator it){ + return it != hull.end() && next(it) != hull.end(); + } + bool irrelevant(const Line &l1 , const Line &l2 , const Line &l3){ + return intersectX(l1,l3) <= intersectX(l1,l2); + } + bool irrelevant(set < Line > :: iterator it){ + return hasPrev(it) && hasNext(it) && (irrelevant(*next(it) , *it , *prev(it))); + } + set < Line > :: iterator updateLeftBorder(set < Line > :: iterator it){ + if(!hasNext(it)){ + return it; + } + double val = intersectX(*it , *next(it)); + Line buf(*it); + it = hull.erase(it); + buf.xLeft = val; + it = hull.insert(it, buf); + return it; + } + void addLine(int a , long long b){ + Line l3 = Line(a, b); + auto it = hull.lower_bound(l3); + if(it != hull.end() && areParallel(*it , l3)){ + if(it -> b > b){ + it = hull.erase(it); + } + else{ + return; + } + } + it = hull.insert(it, l3); + if(irrelevant(it)){ + hull.erase(it); + return; + } + while(hasPrev(it) && irrelevant(prev(it))){ + hull.erase(prev(it)); + } + while(hasNext(it) && irrelevant(next(it))){ + hull.erase(next(it)); + } + it = updateLeftBorder(it); + if(hasPrev(it)){ + updateLeftBorder(prev(it)); + } + if(hasNext(it)){ + updateLeftBorder(next(it)); + } + } + long long getBest(int x){ + Line q; + q.val = x; + q.type = 1; + auto bestLine = hull.lower_bound(q); + if(bestLine == hull.end()){ + return 1e16; + } + return bestLine -> valueAt(x); + } +}; diff --git a/Library/DS/ConvexHull.cpp b/Library/DS/ConvexHull.cpp new file mode 100755 index 0000000..f2bf953 --- /dev/null +++ b/Library/DS/ConvexHull.cpp @@ -0,0 +1,104 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;i pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 2e5; +vi g[N]; +int a[N]; +//Takes query values in increasing order +//Add lines in sorted order +class ConvexHull{ + int ptr; + typedef pii Line; + vector lines; + public: + ConvexHull(){ + ptr = 0; + lines.clear(); + } + int f(Line l, int x){ + return l.F*x+l.S; + } + bool bad(Line l1, Line l2, Line l3){ + return (l3.S-l1.S)*(l1.F-l2.F) <= (l1.F-l3.F)*(l2.S-l1.S); + } + void addLine(Line l3){ + lines.pb(l3); + while(lines.size()>=3){ + int tot = lines.size(); + Line l3 = lines[tot-1]; + Line l2 = lines[tot-2]; + Line l1 = lines[tot-3]; + if (bad(l1, l2, l3)){ + lines.erase(lines.end()-2); + } + else break; + } + } + //Returns Minimum + //Query values must be in non-decreasing order + //Otherwise use Binary Search (Maintain the end points of lines) + int get(int x){ + if (ptr >= lines.size()) ptr = lines.size()-1; + while(ptr < lines.size()-1 and f(lines[ptr], x) > f(lines[ptr+1], x)) + ptr++; + return f(lines[ptr], x); + } +}; +//END +bool f(pii a, pii b){ + if (a.F != b.F) return a.F > b.F; + return a.S < b.S; +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,n; + vpii data; + cin>>n; + fo(i, n){ + int m, c; + cin>>m>>c; + data.pb({m, c}); + } + sort(data.begin(), data.end(), f); + ConvexHull A; + fo(i, n) A.addLine(data[i]); + cin>>n; + vi points; + fo(i, n){ + int x; + cin>>x; + points.pb(x); + } + sort(points.begin(), points.end()); + for(int x: points) + cout< succ; + bool operator<(const Line& rhs) const { + if (rhs.b != is_query) return m < rhs.m; + const Line* s = succ(); + if (!s) return 0; + ll x = rhs.m; + return b - s->b < (s->m - m) * x; + } +}; +struct HullDynamic : public multiset { // will maintain upper hull for maximum + bool bad(iterator y) { + auto z = next(y); + if (y == begin()) { + if (z == end()) return 0; + return y->m == z->m && y->b <= z->b; + } + auto x = prev(y); + if (z == end()) return y->m == x->m && y->b <= x->b; + return (x->b - y->b)*(z->m - y->m) >= (y->b - z->b)*(y->m - x->m); + } + void insert_line(ll m, ll b) { + auto y = insert({ m, b }); + y->succ = [=] { return next(y) == end() ? 0 : &*next(y); }; + if (bad(y)) { erase(y); return; } + while (next(y) != end() && bad(next(y))) erase(next(y)); + while (y != begin() && bad(prev(y))) erase(prev(y)); + } + ll eval(ll x) { + auto l = *lower_bound((Line) { x, is_query }); + return l.m * x + l.b; + } +}; diff --git a/Library/DS/ConvexHullDynamicMinMax.cpp b/Library/DS/ConvexHullDynamicMinMax.cpp new file mode 100755 index 0000000..a5f2889 --- /dev/null +++ b/Library/DS/ConvexHullDynamicMinMax.cpp @@ -0,0 +1,143 @@ +// NOTE : This problem requres implementation of Standard convex hull trick which I have copied from : +// http://codeforces.com/blog/entry/11339 + +// SOURCE : http://codeforces.com/blog/entry/11339 + +/* + * Dynamic version of data structure + * to be used in dynamic programming optimisation + * called "Convex Hull trick" + * 'Dynamic' means that there is no restriction on adding lines order + */ +class ConvexHullDynamic +{ + typedef long long coef_t; + typedef long long coord_t; + typedef long long val_t; + + /* + * Line 'y=a*x+b' represented by 2 coefficients 'a' and 'b' + * and 'xLeft' which is intersection with previous line in hull(first line has -INF) + */ +private: + struct Line + { + coef_t a, b; + double xLeft; + + enum Type {line, maxQuery, minQuery} type; + coord_t val; + + explicit Line(coef_t aa=0, coef_t bb=0) : a(aa), b(bb), xLeft(-INFINITY), type(Type::line), val(0) {} + val_t valueAt(coord_t x) const { return a*x+b; } + friend bool areParallel(const Line& l1, const Line& l2) { return l1.a==l2.a; } + friend double intersectX(const Line& l1, const Line& l2) { return areParallel(l1,l2)?INFINITY:1.0*(l2.b-l1.b)/(l1.a-l2.a); } + bool operator<(const Line& l2) const + { + if (l2.type == line) + return this->a < l2.a; + if (l2.type == maxQuery) + return this->xLeft < l2.val; + if (l2.type == minQuery) + return this->xLeft > l2.val; + } + }; + +private: + bool isMax; //whether or not saved envelope is top(search of max value) + std::set hull; //envelope itself + +private: + /* + * INFO: Check position in hull by iterator + * COMPLEXITY: O(1) + */ + bool hasPrev(std::set::iterator it) { return it!=hull.begin(); } + bool hasNext(std::set::iterator it) { return it!=hull.end() && std::next(it)!=hull.end(); } + + /* + * INFO: Check whether line l2 is irrelevant + * NOTE: Following positioning in hull must be true + * l1 is next left to l2 + * l2 is right between l1 and l3 + * l3 is next right to l2 + * COMPLEXITY: O(1) + */ + bool irrelevant(const Line& l1, const Line& l2, const Line& l3) { return intersectX(l1,l3) <= intersectX(l1,l2); } + bool irrelevant(std::set::iterator it) + { + return hasPrev(it) && hasNext(it) + && ( isMax && irrelevant(*std::prev(it), *it, *std::next(it)) + || !isMax && irrelevant(*std::next(it), *it, *std::prev(it)) ); + } + + /* + * INFO: Updates 'xValue' of line pointed by iterator 'it' + * COMPLEXITY: O(1) + */ + std::set::iterator updateLeftBorder(std::set::iterator it) + { + if (isMax && !hasPrev(it) || !isMax && !hasNext(it)) + return it; + + double val = intersectX(*it, isMax?*std::prev(it):*std::next(it)); + Line buf(*it); + it = hull.erase(it); + buf.xLeft = val; + it = hull.insert(it, buf); + return it; + } + +public: + explicit ConvexHullDynamic(bool isMax): isMax(isMax) {} + + /* + * INFO: Adding line to the envelope + * Line is of type 'y=a*x+b' represented by 2 coefficients 'a' and 'b' + * COMPLEXITY: Adding N lines(N calls of function) takes O(N*log N) time + */ + void addLine(coef_t a, coef_t b) + { + //find the place where line will be inserted in set + Line l3 = Line(a, b); + auto it = hull.lower_bound(l3); + + //if parallel line is already in set, one of them becomes irrelevant + if (it!=hull.end() && areParallel(*it, l3)) + { + if (isMax && it->b < b || !isMax && it->b > b) + it = hull.erase(it); + else + return; + } + + //try to insert + it = hull.insert(it, l3); + if (irrelevant(it)) { hull.erase(it); return; } + + //remove lines which became irrelevant after inserting line + while (hasPrev(it) && irrelevant(std::prev(it))) hull.erase(std::prev(it)); + while (hasNext(it) && irrelevant(std::next(it))) hull.erase(std::next(it)); + + //refresh 'xLine' + it = updateLeftBorder(it); + if (hasPrev(it)) + updateLeftBorder(std::prev(it)); + if (hasNext(it)) + updateLeftBorder(std::next(it)); + } + /* + * INFO: Query, which returns max/min(depends on hull type - see more info above) value in point with abscissa 'x' + * COMPLEXITY: O(log N), N-amount of lines in hull + */ + val_t getBest(coord_t x) const + { + Line q; + q.val = x; + q.type = isMax ? Line::Type::maxQuery : Line::Type::minQuery; + + auto bestLine = hull.lower_bound(q); + if (isMax) --bestLine; + return bestLine->valueAt(x); + } +}; diff --git a/Library/DS/HV-Intersection-PBDS.cpp b/Library/DS/HV-Intersection-PBDS.cpp new file mode 100755 index 0000000..98d20f6 --- /dev/null +++ b/Library/DS/HV-Intersection-PBDS.cpp @@ -0,0 +1,163 @@ +//intersection of horizontal and vertical lines https://www.codechef.com/NOV16/problems/URBANDEV +#include +#include +#include +#include +using namespace std; +using namespace __gnu_pbds; +typedef tree,rb_tree_tag,tree_order_statistics_node_update> ordered_set; +typedef tree,null_type,less>,rb_tree_tag,tree_order_statistics_node_update> ordered_mset; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pll; +typedef vector vi; +typedef vector vll; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 1e5+12; +using namespace std; + int cnt[N]; +typedef pair pii; + +class CBF +{ +public: + bool operator()(const pii& p1, const pii& p2)const + { + return p1.first < p2.first; + } +}; + + +vi lo[N], hi[N]; +vector< pair > ver[N]; +set events; +unordered_map hai[2][N]; +#define x1 u.F +#define y1 u.S +#define x2 v.F +#define y2 v.S +int n; + +struct node{ + pii u,v; + int o; + void read(int i){ + si(u.F); si(u.S); + si(v.F); si(v.S); + events.insert(x1); + events.insert(x2); + if(u.S > v.S or u.F > v.F) swap(u, v); + find(i); + } + void find(int pos){ + if(u.F==v.F){ + o=1; + ver[u.F].pb({pos, {u.S, v.S}}); + } + else{ + o=0; + lo[u.F].pb(u.S); + hi[v.F].pb(v.S); + } + hai[o][u.F][u.S] = 1; + + hai[o][v.F][v.S] = 1; + } + void change(int i){ + swap(x1, y1); swap(x2, y2); + if(u.S > v.S or u.F > v.F) swap(u, v); + find(i); + } +}seg[N]; + +void input(){ + int i; + si(n); + fo(i, n){ + seg[i].read(i); cnt[i] = 0; + } + +} +void reset(){ + int i; + // fo(i, N) hai[0][i].clear(), hai[1][i].clear(); + fo(i, N) lo[i].clear(), hi[i].clear(), ver[i].clear(); + events.clear(); + fo(i, n) seg[i].change(i), events.insert(seg[i].x1), events.insert(seg[i].x2); + +} +int T = 1; +int inf = mod; +void solve(){ + int i; + + ll ans = 0; + + ordered_mset con; + int xx; + + for(int xx: events){ + //cout<<"AT "< line: ver[xx]){ + int j = line.F; + pii span = line.S; + cnt[j] += con.order_of_key({span.S, inf}) + - con.order_of_key({span.F-1, inf}); + //cout<<"LINE "< +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;i pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 2e6; +vi g[N]; +int pos_; +ll a[N], MX; +int dp[N], b1[N], b2[N], p1[N], p2[N], from[N]; +int L, R; +//http://codeforces.com/problemset/problem/474/E +//pos_ is the 'i' in a[i] while adding a[i] to BIT. +//p1[pos] represents what position in array gives the max till pos. +void add1(int pos, int val){ + while(pos < N){ + if (b1[pos] <= val) b1[pos] = val, p1[pos] = pos_; + pos += pos&-pos; + } +} +void add2(int pos, int val){ + pos = MX-pos+1; + while(pos < N){ + if (b2[pos] <= val) b2[pos] = val, p2[pos] = pos_; + pos += pos&-pos; + } +} +int get1(int pos){ + int ans = -1; + while(pos){ + if (b1[pos] > ans) ans = b1[pos], L = p1[pos]; + ans = max(b1[pos], ans); + pos -= pos&-pos; + } + return ans; +} +int get2(int pos){ + pos = MX-pos+1; + int ans = -1; + while(pos){ + if (b2[pos] > ans) ans = b2[pos], R = p2[pos]; + pos -= pos&-pos; + } + return ans; +} +set sett; +map mep; +map at; +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,n,k,j,d; + cin >> n >> d; + fo(i, n){ + cin>>a[i]; + sett.insert(a[i]); + } + int pos = 0; + tr(it, sett) mep[*it] = ++pos, at[pos] = *it; + i = 0; + MX = mep[*sett.rbegin()]; + pos_ = 1; + fo(i, n) + add1(mep[a[i]], 1), + add2(mep[a[i]], 1); + Fo(i, 1, n){ + pos_ = i+1; L = R = 0; + auto it = sett.lower_bound(a[i]-d); + int left = 1, right = 1; + if (*it != a[i]-d){ + if (it == sett.begin()) left = 0; + else it--; + } + if (left) left = get1( mep[*it]); + it = sett.lower_bound(a[i]+d); + if (it == sett.end()) right = 0; + if (right) right = get2(mep[*it]); + int cur = max(left, right); + + if (cur>-1){ + from[i+1] = cur==left?L:R; + cur++; + dp[i] = cur; + add1(mep[a[i]], cur); + add2(mep[a[i]], cur); + } + } + + int cur = n, res = -1; + fo(i, n) if (res < dp[i]) res = dp[i], cur = i+1; + cout< z[v]) p[v] = u; + else p[u] = v, z[v]++; + return 1; + } + + int get(int v){ + if (v == p[v]) return v; + return p[v] = get(p[v]); + } + int com(){ + int i; + int ans = 0; + Fo(i, 1, n+1) ans += p[i] == i; + return ans; + } +}; diff --git a/Library/DS/bit.cpp b/Library/DS/bit.cpp new file mode 100755 index 0000000..c834961 --- /dev/null +++ b/Library/DS/bit.cpp @@ -0,0 +1,53 @@ +//1-d bit +int valR[N], valL[N], bit[N]; +map id; +void add(int x){ + while(x no; + //for suffix queries + //add all no's in the set that you will add + query + //otherwise use lower_bound to find the correct id + fo(i, n) no.insert(valL[i]); + fo(i, n) no.insert(valR[i]); + int pos = 1; + //give IDs in descending order so that + //suffix is handles as prefix + for(auto it = no.rbegin(); it != no.rend(); ++it) + id[*it] = pos++; +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,k,j; + clr(bit); + cin>>n; + fo(i, n)cin>>a[i]; + map cnt; + Fo(i, n-1, -1) valR[i] = 1+cnt[a[i]]++; + cnt.clear(); + Fo(i, 0, n) valL[i] = 1+cnt[a[i]]++; + suffix(); + ll ans = 0; + fo(i,n){ + //since suffix stored as prefix + //[1,x-1] represent ans for >x + ans += query(id[valR[i]]-1); + add(id[valL[i]]); + } + cout< { + bool bad (iterator y) { + iterator z = next(y), x; + if (y == begin()) { + if (z == end()) return 0; + return y->a == z->a && y->b <= z->b; + } + x = prev(y); + if (z == end()) { + return y->a == x->a && y->b <= x->b; + } + return 1.0L * (x->b - y->b) * (z->a - y->a) >= 1.0L * (y->b - z->b) * (y->a - x->a); + } + + void add (ll a, ll b) { + a*=-1; + b*=-1; + cmpA = 1; + iterator y = insert((Line){a,b,-INF}); + if (bad(y)) { erase(y); return; } + while (next(y) != end() && bad(next(y))) erase(next(y)); + while (y != begin() && bad(prev(y))) erase(prev(y)); + if (next(y) != end()) next(y)->xl = 1.0L * (y->b - next(y)->b) / (next(y)->a - y->a); + if (y != begin()) y->xl = 1.0L * (y->b - prev(y)->b) / (prev(y)->a - y->a); + } + + ll eval (ll x) { + if (empty()) return -(-INF); + cmpA = 0; + iterator it = prev(lower_bound((Line){0,0,1.0L*x})); + return -(it->a * x + it->b); + } +}; diff --git a/Library/DS/heap.cpp b/Library/DS/heap.cpp new file mode 100755 index 0000000..0b0a986 --- /dev/null +++ b/Library/DS/heap.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; +class heap{ + vector a; + #define l(x) 2*x+1 + #define r(x) 2*x+2 + #define p(x) (x-1)/2 + #define null -INT_MAX + public: + void add(int x){ + a.push_back(x); + go(a.size()-1); + } + void go(int u){ + if(u == 0) return; + int P = p(u); + if(a[P]>a[u]) swap(a[P], a[u]), go(P); + } + void heapify(int u){ + int L = l(u), R = r(u), n = a.size(); + if(L>=n and R>=n) return; + int v = (La[v]) swap(a[u], a[v]), heapify(v); + } + int extract(){ + if (a.empty()){ + cout << "Oops! heap is empty!" << endl; + return null; + } + int ans = a[0]; + if(a.size() == 1) { + a.clear(); + return ans; + } + a[0] = a.back(); + a.pop_back(); + heapify(0); + return ans; + } +}; + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,n,k,j; + heap H; + vector a{13, 1, 10, 34, 42, -10}; + for(int x: a) H.add(x); + for(int x: a) cout << H.extract() << " "; + return 0; +} + + diff --git a/Library/DS/points-in-rectangle-KDTREE.cpp b/Library/DS/points-in-rectangle-KDTREE.cpp new file mode 100755 index 0000000..1a60411 --- /dev/null +++ b/Library/DS/points-in-rectangle-KDTREE.cpp @@ -0,0 +1,225 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pll; +typedef vector vi; +typedef vector vll; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 3e5+2; +using namespace std; + int cnt[N]; +typedef pair pii; + +class CompareByFirst +{ +public: + bool operator()(const pii& p1, const pii& p2)const + { + return p1.first < p2.first; + } +}; + +class CompareBySecond +{ +public: + bool operator()(const pii& p1, const pii& p2)const + { + return p1.second < p2.second; + } +}; + +struct QTNode +{ + int left, right, bottom, top; + int count; + QTNode* child[2]; + + void SplitData(vector& points, int first, int last, int level) + { + this->count = last - first + 1; + + this->left = points[first].first; + this->right = points[first].first; + this->bottom = points[first].second; + this->top = points[first].second; + + if(first == last) + { + this->count = 1; + return; + } + + for(int i = first + 1; i <= last; i++) + { + this->left = min(this->left, points[i].first); + this->top = max(this->top, points[i].second); + this->right = max(this->right, points[i].first); + this->bottom = min(this->bottom, points[i].second); + } + + int mid = first + (last - first) / 2; + if(level & 0x1) + { + nth_element(&points[first], &points[mid], &points[last + 1], CompareByFirst()); + } + else + { + nth_element(&points[first], &points[mid], &points[last + 1], CompareBySecond()); + } + + child[0] = new QTNode(); + child[1] = new QTNode(); + child[0]->SplitData(points, first, mid, level + 1); + child[1]->SplitData(points, mid + 1, last, level + 1); + } + + int CountInRect(int _left, int _right, int _bottom, int _top) + { + if( this->left >= _left and + this->right <= _right and + this->top <= _top and + this->bottom >= _bottom) + { + return this->count; + } + else if(this->left <= _right and + this->right >= _left and + this->top >= _bottom and + this->bottom <= _top) + { + return this->child[0]->CountInRect(_left, _right, _bottom, _top) + this->child[1]->CountInRect(_left, _right, _bottom, _top); + } + else + { + return 0; + } + } + + void Traverse() + { + cout<Traverse(); + } + if(child[1]) + { + child[1]->Traverse(); + } + } +}; + +QTNode* buildQTree(vector >& points) +{ + QTNode* root = new QTNode(); + root->SplitData(points,0,points.size() - 1, 0); + return root; +} + +template +void PrintSet(set& s) +{ + for(set::iterator i = s.begin(); i != s.end(); i++) + { + cout<first<<":"<second<<" "; + } + cout<>u.F>>u.S; + cin>>v.F>>v.S; + if(u > v) swap(u, v); + find(); + } + void find(){ + if(u.F==v.F)o=1; + else o=0; + } +}seg[N]; +map hai[2][N]; + void solve(){ + + int i, n; + cin>>n; + ll ans = 0; + vpii interval[2][2]; + fo(i, n){ + seg[i].read(); + int x = seg[i].o; + node line = seg[i]; + hai[x][line.u.F][line.u.S] = 1; + hai[x][line.v.F][line.v.S] = 1; + if(x){ + // | + // | => x is constant + // | + interval[x][0].pb({line.u.F, line.u.S}); + interval[x][1].pb({line.v.F, line.v.S+1}); + + //cout<CountInRect(0, line.v.F, 0, line.v.S); + cnt[i] -= qTree[1-x][1]->CountInRect(0, line.v.F, 0, line.v.S); + // cout<<1-x<<" "; + //if(x){ + cnt[i] -= hai[1-x][line.u.F][line.u.S]+hai[1-x][line.v.F][line.v.S]; + // cout< +#include +#include +#include +using namespace std; +using namespace __gnu_pbds; +typedef tree,rb_tree_tag,tree_order_statistics_node_update> ordered_set; +typedef tree,null_type,less>,rb_tree_tag,tree_order_statistics_node_update> ordered_mset; +//ENDS + +int t = 0; + +int main() +{ + + int x = 1; + ordered_mset me; + me.insert({x, t++}); + // me.erase(me.lower_bound({x, 0})); + cout << me.order_of_key({x, 0}) << "\n"; + + + ordered_set A; + A.insert(1); + A.insert(2); + A.insert(10); + A.insert(100); + //how many numbers are smaller than it + cout<mid) return query(rpart, x, y); + node L = query(lpart, x, mid); + node R = query(rpart, mid+1, y); + node res; + res.merge(L, R); + return res; + } +}; diff --git a/Library/DS/sparse_table_2d.cpp b/Library/DS/sparse_table_2d.cpp new file mode 100755 index 0000000..fe75205 --- /dev/null +++ b/Library/DS/sparse_table_2d.cpp @@ -0,0 +1,49 @@ +//2d sparse table for max +//0 based index +//LGN = 1 + lg2(N) +//LGM = 1 + lg2(M) + +const int N = 1030; +const int M = 1030; +const int LGN = 11; +const int LGM = 11; + +int a[N][M]; +int dp[N][M][LGN][LGM]; +const int MAXN = 2e6; //max(N, M) +int lg2[MAXN]; +void pre(){ + //build lg2 + lg2[1] = log2(1); + lg2[2] = log2(2); + int val = 1, at = 4; + int i; + Fo(i, 3, MAXN){ + if (i == at){ + at *= 2; + val++; + } + lg2[i] = log2(i); + } +} +void build(int n, int m){ + pre(); + for(int i = 1; i <= n; ++ i) for(int j = 1; j <= m; ++ j) dp[i][j][0][0] = a[i-1][j-1]; + for(int j1 = 0; (1 << j1) <= n; ++ j1) { + for(int j2 = 0; (1 << j2) <= m; ++ j2) if(j1 || j2) { + for(int i1 = 1; i1 + (1 << j1) - 1 <= n; ++ i1) { + for(int i2 = 1; i2 + (1 << j2) - 1 <= m; ++ i2) { + if(j1) dp[i1][i2][j1][j2] = max(dp[i1][i2][j1 - 1][j2], dp[i1 + (1 << (j1 - 1))][i2][j1 - 1][j2]); + else dp[i1][i2][j1][j2] = max(dp[i1][i2][j1][j2 - 1], dp[i1][i2 + (1 << (j2 - 1))][j1][j2 - 1]); + } + } + } + } +} + +int query(int x1, int Y1, int x2, int y2){ + int k1 = lg2[x2-x1+1]; + int k2 = lg2[y2-Y1+1]; + return max(max(dp[x1][Y1][k1][k2], dp[x2 - (1 << k1) + 1][y2 - (1 << k2) + 1][k1][k2]), + max(dp[x2 - (1 << k1) + 1][Y1][k1][k2], dp[x1][y2 - (1 << k2) + 1][k1][k2])); +} diff --git a/Library/DS/treap_reversal.cpp b/Library/DS/treap_reversal.cpp new file mode 100755 index 0000000..78b017e --- /dev/null +++ b/Library/DS/treap_reversal.cpp @@ -0,0 +1,193 @@ +#include +// http://www.spoj.com/problems/HORRIBLE/ +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;kr); +// } +// int delete_at(pnode &t, int pos){ +// node *L, *mid, *R; +// split(t, L, mid, pos-1); +// split(mid, t, R, 1); +// node *tem = t; +// int val = t->val; +// merge(t, L, R); +// free(tem); +// return val; +// } +void clear(pnode &t){ + if(t == NULL)return; + clear(t->l); + clear(t->r); + free(t); +} +//======================= + +vi g[N]; +int a[N]; + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + srand(time(NULL)); + freopen("rev.in", "r", stdin); + freopen("rev.out", "w", stdout); + int i,n,k,j,q,x,y; + q = 1; + pnode t; + int v; + si(n); si(q); + // clear(t); + t = init(1); + fo(i, n-1) merge(t, t, init(i+2)); + while(q--){ + int ty; + si(x); + si(y); + si(k); + assert(x <= y); + assert(k<=n); + range_update(t, x, y); + // cout << range_query(t, k, k) << endl; + pi(range_query(t, k, k)); + } + return 0; +} + diff --git a/Library/DS/treaps.cpp b/Library/DS/treaps.cpp new file mode 100755 index 0000000..59f5f0f --- /dev/null +++ b/Library/DS/treaps.cpp @@ -0,0 +1,199 @@ +#include +// http://www.spoj.com/problems/HORRIBLE/ +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;kr); +// } +// int delete_at(pnode &t, int pos){ +// node *L, *mid, *R; +// split(t, L, mid, pos-1); +// split(mid, t, R, 1); +// node *tem = t; +// int val = t->val; +// merge(t, L, R); +// free(tem); +// return val; +// } +void clear(pnode &t){ + if(t == NULL)return; + clear(t->l); + clear(t->r); + free(t); +} +//======================= + +vi g[N]; +int a[N]; + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + srand(time(NULL)); + int i,n,k,j,q,x,y; + cin >> k; + pnode t; + int v; + while(k--){ + cin >> n >> q; + // clear(t); + t = init(0); + fo(i, n-1) merge(t, t, init(0)); + x = 2, y = 3; + v = 1; + while(q--){ + int ty; + cin >> ty >> x >> y; + if(ty == 0){ + cin >> v; + range_update(t, x, y, v); + } + else{ + cout << range_query(t, x, y) << endl; + } + } + } + return 0; +} + diff --git a/Library/Graph/BCC.cpp b/Library/Graph/BCC.cpp new file mode 100755 index 0000000..2191fa7 --- /dev/null +++ b/Library/Graph/BCC.cpp @@ -0,0 +1,56 @@ +class Bcc{ + vector num,inS; + stack roots,st; + int cnt; +public: + vv bcc,tree; + vector brdg,inv; + void dfs(const vv &g,const vector &es,int v,int e){ + num[v]=++cnt; + st.push(v); inS[v]=1; roots.push(v); + for(const int &i:g[v])if(i!=e){ + int w=es[i].X+es[i].Y-v; + if(!num[w]){ + dfs(g,es,w,i); + }else if(inS[w]){ + while(num[roots.top()]>num[w]) roots.pop(); + } + } + if(v==roots.top()){ + brdg.pb(e); + bcc.pb(vector()); + while(1){ + int w=st.top(); st.pop(); inS[w]=0; + bcc.back().pb(w); + if(v==w) break; + } + roots.pop(); + } + } + + Bcc(vv &g,vector es){ + const int n=g.size(); + num.resize(n); inS.resize(n); + int cnt=0; + rep(i,n)if(!num[i]){ + dfs(g,es,i,-1); + brdg.pop_back(); + } + const int m=bcc.size(); + inv.resize(n); + rep(i,m) for(const int &v:bcc[i]) inv[v]=i; + for(pii &p:es){p.X=inv[p.X]; p.Y=inv[p.Y];} + //sort(all(es)); UNIQUE(es); + tree.resize(m); //tedge.resize(m); + int i=0; + for(const pii &p:es){ + if(p.X!=p.Y){ + tree[p.X].pb(p.Y); + tree[p.Y].pb(p.X); + // tedge[p.X].pb(i); + // tedge[p.Y].pb(i); + } + ++i; + } + } +}; diff --git a/Library/Graph/Dijkstra.cpp b/Library/Graph/Dijkstra.cpp new file mode 100755 index 0000000..eb09bb5 --- /dev/null +++ b/Library/Graph/Dijkstra.cpp @@ -0,0 +1,103 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;i pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 2e5; +struct compar{ + //priority queue + //u need top element.. sort such + //that ur element comes at last + bool operator() (pii a, pii b){ + if (a.F != b.F) + return a.F > b.F; + return a.S < b.S; + } +}; +//UNDIRECTED GRAPH +class Dijkstra{ + int n, m; + ll *dis; + bool *vis; + int *par; + ll inf; + priority_queue,compar> Q; + vpii *G; + public: + void setVertices(int no){ + n = no; + G = new vpii[n+1]; + dis = new ll[n+1]; + vis = new bool[n+1]; + par = new int[n+1]; + inf = 1e18; + + } + void setEdges(int no){ + m = no; + } + void addEdge(int u, int v, int w){ + G[u].pb({w, v}); + //UNDIRECTED-GRAPH + G[v].pb({w, u}); + } + ll shortestPath(int source, int sink){ + int i; + for(i=1; i<=n; i++) + dis[i] = inf, vis[i] = 0; + dis[source] = 0; + Q.push({0, source}); + while(!Q.empty()){ + pii cur = Q.top(); Q.pop(); + if (vis[cur.S]) continue; + vis[cur.S] = 1; + dis[cur.S] = cur.F; + for(pii x: G[cur.S]){ + int to = x.S, w = x.F; + Q.push({cur.F+w, to}); + } + + } + if (dis[sink] != inf) return dis[sink]; + return -1; + } +}; +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i, j, n, m; + cin>>n>>m; + Dijkstra A; + A.setVertices(n); + A.setEdges(m); + while(m--){ + int u, v, w; + cin>>u>>v>>w; + A.addEdge(u, v, w); + } + A.pathOfShortestPath(1, n); + return 0; +} + + diff --git a/Library/Graph/Dijkstra_Khattar_Style.cpp b/Library/Graph/Dijkstra_Khattar_Style.cpp new file mode 100755 index 0000000..cda7f7b --- /dev/null +++ b/Library/Graph/Dijkstra_Khattar_Style.cpp @@ -0,0 +1,150 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;i pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 2e5; +vi g[N]; +int a[N]; + +int mpow(int base, int exp); +void ipgraph(int n, int m); +void dfs(int u, int par); +//http://codeforces.com/problemset/problem/545/E +//Begins +//Works for 0/1 based index +//Stores the edges used in shortest paths + +struct f{ + bool operator()(pair a, pair b){ + if (a.F != b.F) return a.F > b.F; + if (a.S.S != b.S.S) return W[a.S.S] > W[b.S.S]; + return a.S.F < b.S.F; + + } +}; +class Dijkstra{ + int n, m; + vi *G; + set res; + int *vis, *U, *V; + int *W; + ll *dis; + + typedef pair node; + public: + void init(int no, int edges){ + n = no; + m = edges; + U = new int[m+3]; + V = new int[m+3]; + W = new int[m+3]; + dis = new ll[m+3]; + G = new vi[n+3]; + vis = new int[n+3]; + int i; + fo(i, n+1) vis[i] = 0; + clr(vis); + } + + int adj(int u, int e){ + return u == U[e]? V[e]:U[e]; + } + void addEdge(int pos, int u, int v, int w){ + U[pos] = u; + V[pos] = v; + W[pos] = w; + G[u].pb(pos); + G[v].pb(pos); + } + void compute(int source){ + priority_queue< node, vector, f > Q; + Q.push({0, {source, -1}}); + + while(!Q.empty()){ + node cur = Q.top(); Q.pop(); + if (vis[cur.S.F]) continue; + vis[cur.S.F] = 1; + dis[cur.S.F] = cur.F; + res.insert(cur.S.S); + for(int e: G[cur.S.F]){ + int to = adj(cur.S.F, e); + int w = W[e]; + Q.push({cur.F+w, {to, e}}); + } + } + res.erase(-1); + ll sum = 0; + tr(it, res) sum += W[*it]; + cout<>n>>m; + A.init(n, m); + fo(i, m){ + int u, v, w; + cin>>u>>v>>w; + A.addEdge(i+1, u, v, w); + } + int u; + cin>>u; + A.compute(u); + return 0; +} + +int mpow(int base, int exp) { + base %= mod; + int result = 1; + while (exp > 0) { + if (exp & 1) result = ((ll)result * base) % mod; + base = ((ll)base * base) % mod; + exp >>= 1; + } + return result; +} + +void ipgraph(int n, int m){ + int i, u, v; + while(m--){ + cin>>u>>v; + g[u-1].pb(v-1); + g[v-1].pb(u-1); + } +} + +void dfs(int u, int par){ + for(int v:g[u]){ + if (v == par) continue; + dfs(v, u); + } +} + diff --git a/Library/Graph/Euler_Circuit.cpp b/Library/Graph/Euler_Circuit.cpp new file mode 100755 index 0000000..283e365 --- /dev/null +++ b/Library/Graph/Euler_Circuit.cpp @@ -0,0 +1,102 @@ +//http://codeforces.com/problemset/problem/723/E +//EULER - TOUR -> UNDIRECTED and DIRECTED GRAPH +//for undirected i needed to mark edges that i have traversed +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;i pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 304; +vpii g[N]; +set has[N]; +ll a[N], vis[N], cnt[N], in[N], mark[N*N]; +vi ans; +int mpow(int base, int exp); +void ipgraph(int n, int m); +void dfs(int u, int par); +void go(int u, int par){ + vis[u] = 1; + while(cnt[u] < (int)g[u].size()){ + cnt[u]++; + if (mark[g[u][cnt[u]-1].S]) continue; + else mark[g[u][cnt[u]-1].S] = 1, go(g[u][cnt[u]-1].F, u); + } + ans.pb(u); +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int n, m, t, i, u,j, v, w; + //freopen("input.txt", "r". stdin); + //freopen("output.txt", "w". stdout); + cin>>t; + while(t--){ + cin>>n>>m; + ans.clear(); + Fo(i, 0, n+1) g[i].clear(), has[i].clear(), in[i] = cnt[i] = vis[i] = 0; + fo(i, m){ + cin>>u>>v; + g[u].pb({v, i}); + g[v].pb({u, i}); + mark[i] = 0; + has[u].insert(v); + has[v].insert(u); + in[v]++; + in[u]++; + } + int x = m; + //add pseudo-vertex + int res = 0; + Fo(i, 1, n+1) res += 1 - (in[i]%2); + Fo(i, 0, n+1) if (in[i]&1) mark[x] = 0, g[i].pb({0, x}), g[0].pb({i, x++}); + + //graph has all vertices with even degree + //finding euler circuit makes sure all even degree vertices + //have equal no of incoming and outgoing edges + //later on removing extra edges we added + // will not affect even degree vertices :D + Fo(i, 1, n+1){ + if (!vis[i]){ + vis[i] = 1; + go(i, -1); + ans.pb(i); + } + } + cout< z[v]) p[v] = u; + else p[u] = v, z[v]++; + return 1; + } + + int get(int v){ + if (v == p[v]) return v; + return p[v] = get(p[v]); + } + +}; +bool f(pair a, pair b){ + return a.F < b.F; +} +class MST{ + int n, m; + typedef pair pii; + #define pb push_back + typedef pair edge; + vector Edges; + UnionFind *forest; + vector res; + public: + MST(int size){ + n = size; + forest = new UnionFind(n); + } + void addEdge(int u, int v, int w){ + Edges.pb({w, {u, v}}); + } + void compute(){ + sort(Edges.begin(), Edges.end(), f); + for(edge E:Edges){ + if (forest->addEdge(E.S.F, E.S.S)) + res.pb(E); + } + } + void out(){ + int sum = 0; + for(edge E: res) + sum += E.F; + cout< +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;i pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 2e5; +vi g[N]; +int a[N]; +//http://codeforces.com/problemset/problem/237/E + +// min-cost max-flow ... SOURCE: Unknown +// Not tested for multi edges, negative edge weight +typedef vector VI; +typedef vector VVI; +typedef long long L; +typedef vector VL; +typedef vector VVL; +typedef pair PII; +typedef vector VPII; + +const L INF = numeric_limits::max() / 4; + +struct MinCostMaxFlow { + int N; + VVL cap, flow, cost; + VI found; + VL dist, pi, width; + VPII dad; + + MinCostMaxFlow(int N) : + N(N), cap(N, VL(N)), flow(N, VL(N)), cost(N, VL(N)), + found(N), dist(N), pi(N), width(N), dad(N) {} + + // 0 based indexing + void AddEdge(int from, int to, L cap, L cost) { + this->cap[from][to] = cap; + this->cost[from][to] = cost; + } + + void Relax(int s, int k, L cap, L cost, int dir) { + L val = dist[s] + pi[s] - pi[k] + cost; + if (cap && val < dist[k]) { + dist[k] = val; + dad[k] = make_pair(s, dir); + width[k] = min(cap, width[s]); + } + } + + L Dijkstra(int s, int t) { + fill(found.begin(), found.end(), false); + fill(dist.begin(), dist.end(), INF); + fill(width.begin(), width.end(), 0); + dist[s] = 0; + width[s] = INF; + + while (s != -1) { + int best = -1; + found[s] = true; + for (int k = 0; k < N; k++) { + if (found[k]) continue; + Relax(s, k, cap[s][k] - flow[s][k], cost[s][k], 1); + Relax(s, k, flow[k][s], -cost[k][s], -1); + if (best == -1 || dist[k] < dist[best]) best = k; + } + s = best; + } + + for (int k = 0; k < N; k++) + pi[k] = min(pi[k] + dist[k], INF); + return width[t]; + } + + pair GetMaxFlow(int s, int t) { + L totflow = 0, totcost = 0; + while (L amt = Dijkstra(s, t)) { + totflow += amt; + for (int x = t; x != s; x = dad[x].first) { + if (dad[x].second == 1) { + flow[dad[x].first][x] += amt; + totcost += amt * cost[dad[x].first][x]; + } else { + flow[x][dad[x].first] -= amt; + totcost -= amt * cost[x][dad[x].first]; + } + } + } + return make_pair(totflow, totcost); + } +}; +// END +int cnt[28]; +int main() +{ + int i,n,j; + string t; + cin>>t; + int lenT = t.length(); + clr(cnt); + fo(i, lenT)cnt[t[i]-'a']++; + cin>>n; + MinCostMaxFlow A(n+28); + int source = n+26 , sink = n+27; + fo(i, 26) A.AddEdge(n+i, sink, cnt[i], 0); + fo(i, n){ + string s; + cin>>s; + int v; + cin>>v; + clr(cnt); + fo(j, s.size()) cnt[s[j]-'a']++; + fo(j, 26) + A.AddEdge(i, n+j, cnt[j], 0); + A.AddEdge(source, i, v, i+1); + } + pair res = A.GetMaxFlow(source, sink); + if (res.F != lenT)cout<<-1; + else cout< extended_gcd(var a, var b){ + bool swp = 0; + if (a K; + var k, r, FF, SS; + while(1){ + k = a/b; + r = a - k*b; + if(r == 1){ + FF = 1, SS = -k; + reverse(all(K)); + for(int k: K){ + var tem = FF; + FF = SS; + SS = tem - SS * k; + } + return swp?mp(SS, FF):mp(FF, SS); + } + else{ + K.pb(k); + } + a = b; + b = r; + } +} +var solve(var a, var b, var n){ + pair ans = extended_gcd(a, n); + var x = ( ans.F * b ) % n; + if ( x < 0) + x += n; + + //a*x is b (mod n) + return x; + +} diff --git a/Library/Math/Seive/seive_totient.cpp b/Library/Math/Seive/seive_totient.cpp new file mode 100755 index 0000000..841b007 --- /dev/null +++ b/Library/Math/Seive/seive_totient.cpp @@ -0,0 +1,36 @@ +//prime[i] is smallest prime that divides i +vector primes; +const int NN = 1e6+1; +int prime[NN]; +void seive(){ + ll i; + Fo(i, 1, NN) prime[i] = i; + prime[0] = prime[1] = 0; + for(i=2; i < NN; i++){ + if (prime[i] == i){ + + for(ll j = 2*i; j < NN; j += i) + if (prime[j] == j) + prime[j] = i; + } + } + for(i=2; i1){ + n2 /= n; + n1 *= n-1; + } + return n1*n2; +} diff --git a/Library/Math/SmallestPrimeSeive.cpp b/Library/Math/SmallestPrimeSeive.cpp new file mode 100755 index 0000000..1e171a3 --- /dev/null +++ b/Library/Math/SmallestPrimeSeive.cpp @@ -0,0 +1,17 @@ +const int M = 1e6+3; +int pr[M]; +//pr[6] = 2 and not 3 +void pre() +{ + int i; + pr[1] = 1; pr[2] = 2; + fo(i, M) pr[i] = i; + for(i=2; i +#include +#include +using namespace std; + + + +int main() +{ + bigint a = bigint("1"); + int b = 2; + for(int i=1; i<100; i++) + { + a = a*b; + } + + cout << a << endl; + + for(int i=1; i<99; i++) + { + a /= b; + } + + cout << a << endl; +} diff --git a/Library/Math/dec2bin.cpp b/Library/Math/dec2bin.cpp new file mode 100755 index 0000000..ec8add2 --- /dev/null +++ b/Library/Math/dec2bin.cpp @@ -0,0 +1,13 @@ +//the bit size +#define szz 17 +void go(ll no, vector &a){ + a.clear(); + while(no){ + a.push_back(no%2); + no /= 2; + } + int left = szz-a.size(); + while(left--) a.pb(0); + //If you uncomment the following 10 will become -> 00000000000001010 + // reverse(a.begin(), a.end()); +} diff --git a/Library/Math/fact_ncr.cpp b/Library/Math/fact_ncr.cpp new file mode 100755 index 0000000..a0a4f8d --- /dev/null +++ b/Library/Math/fact_ncr.cpp @@ -0,0 +1,20 @@ +const int N = 1e6; +ll fac[N], inv[N], b[N]; +void pre(){ + int i; + fac[0] = inv[0] = 1; + fac[1] = inv[1] = 1; + Fo(i, 2, N){ + fac[i] = (i*fac[i-1])%mod; + inv[i] = (mpow(i, mod-2)*inv[i-1])%mod; + } +} +ll C(int n, int r){ + if (r>n)return 0; + ll ans = fac[n]; + ans *= inv[r]; + ans %= mod; + ans *= inv[n-r]; + ans %= mod; + return ans; +} diff --git a/Library/Math/geometry.cpp b/Library/Math/geometry.cpp new file mode 100755 index 0000000..fbf9611 --- /dev/null +++ b/Library/Math/geometry.cpp @@ -0,0 +1,374 @@ +/* +ID: ganeshk2 +lang: cpp +*/ +#include +using namespace std; +typedef long long ll; +typedef pair ii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +#define si(x) scanf("%d",&x) +#define sl(x) scanf("%I64d",&x) +#define ss(s) scanf("%s",s) +#define pb push_back +#define mp make_pair +#define rep(i,b,a) for(i=a;i>=1){if(b&(1LL))res=(res*a)%MOD;a=a*a%MOD;}return res;} +int scan_d(){ + int ip=getchar_unlocked(),ret=0,flag=1;for(;ip<'0'||ip>'9';ip=getchar_unlocked()) + if(ip=='-'){flag=-1;ip=getchar_unlocked();break;} + for(;ip>='0'&&ip<='9';ip=getchar_unlocked())ret=ret<<1+ret<<3+ip-'0';return flag*ret;} +ll scan_lld(){ + int ip=getchar_unlocked(),flag=1;ll ret=0;for(;ip<'0'||ip>'9';ip=getchar_unlocked()) + if(ip=='-'){flag=-1;ip=getchar_unlocked();break;} + for(;ip>='0'&&ip<='9';ip=getchar_unlocked())ret=ret<<1+ret<<3+ip-'0';return flag*ret;} +*/ + +double INF = 1e100; +double EPS = 1e-12; + +struct PT { + double x, y; + PT() {} + PT(double x, double y) : x(x), y(y) {} + PT(const PT &p) : x(p.x), y(p.y) {} + PT operator + (const PT &p) const { return PT(x+p.x, y+p.y); } + PT operator - (const PT &p) const { return PT(x-p.x, y-p.y); } + PT operator * (double c) const { return PT(x*c, y*c ); } + PT operator / (double c) const { return PT(x/c, y/c ); } + bool operator <(const PT &p) const { + return x < p.x || (x == p.x && y < p.y); + } +}; + +double dot(PT p, PT q) { return p.x*q.x+p.y*q.y; } +double dist2(PT p, PT q) { return dot(p-q,p-q); } +double cross(PT p, PT q) { return p.x*q.y-p.y*q.x; } +ostream &operator<<(ostream &os, const PT &p) { + os << "(" << p.x << "," << p.y << ")"; +} + +// rotate a point CCW or CW around the origin +PT RotateCCW90(PT p) { return PT(-p.y,p.x); } +PT RotateCW90(PT p) { return PT(p.y,-p.x); } +PT RotateCCW(PT p, double t) { + return PT(p.x*cos(t)-p.y*sin(t), p.x*sin(t)+p.y*cos(t)); +} + +// project point c onto line through a and b +// assuming a != b +PT ProjectPointLine(PT a, PT b, PT c) { + return a + (b-a)*dot(c-a, b-a)/dot(b-a, b-a); +} + +// project point c onto line segment through a and b +PT ProjectPointSegment(PT a, PT b, PT c) { + double r = dot(b-a,b-a); + if (fabs(r) < EPS) return a; + r = dot(c-a, b-a)/r; + if (r < 0) return a; + if (r > 1) return b; + return a + (b-a)*r; +} + +// compute distance from c to segment between a and b +double DistancePointSegment(PT a, PT b, PT c) { + return sqrt(dist2(c, ProjectPointSegment(a, b, c))); +} + +// compute distance between point (x,y,z) and plane ax+by+cz=d +double DistancePointPlane(double x, double y, double z, + double a, double b, double c, double d) +{ + return fabs(a*x+b*y+c*z-d)/sqrt(a*a+b*b+c*c); +} + +// determine if lines from a to b and c to d are parallel or collinear +bool LinesParallel(PT a, PT b, PT c, PT d) { + return fabs(cross(b-a, c-d)) < EPS; +} + +bool LinesCollinear(PT a, PT b, PT c, PT d) { + return LinesParallel(a, b, c, d) + && fabs(cross(a-b, a-c)) < EPS + && fabs(cross(c-d, c-a)) < EPS; +} + +// determine if line segment from a to b intersects with +// line segment from c to d +bool SegmentsIntersect(PT a, PT b, PT c, PT d) { + if (LinesCollinear(a, b, c, d)) { + if (dist2(a, c) < EPS || dist2(a, d) < EPS || + dist2(b, c) < EPS || dist2(b, d) < EPS) return true; + if (dot(c-a, c-b) > 0 && dot(d-a, d-b) > 0 && dot(c-b, d-b) > 0) + return false; + return true; + } + if (cross(d-a, b-a) * cross(c-a, b-a) > 0) return false; + if (cross(a-c, d-c) * cross(b-c, d-c) > 0) return false; + return true; +} + +// compute intersection of line passing through a and b +// with line passing through c and d, assuming that unique +// intersection exists; for segment intersection, check if +// segments intersect first +PT ComputeLineIntersection(PT a, PT b, PT c, PT d) { + b=b-a; d=c-d; c=c-a; + assert(dot(b, b) > EPS && dot(d, d) > EPS); + return a + b*cross(c, d)/cross(b, d); +} + +// compute center of circle given three points +PT ComputeCircleCenter(PT a, PT b, PT c) { + b=(a+b)/2; + c=(a+c)/2; + return ComputeLineIntersection(b, b+RotateCW90(a-b), c, c+RotateCW90(a-c)); +} + +// determine if point is in a possibly non-convex polygon (by William +// Randolph Franklin); returns 1 for strictly interior points, 0 for +// strictly exterior points, and 0 or 1 for the remaining points. +// Note that it is possible to convert this into an *exact* test using +// integer arithmetic by taking care of the division appropriately +// (making sure to deal with signs properly) and then by writing exact +// tests for checking point on polygon boundary +bool PointInPolygon(const vector &p, PT q) { + bool c = 0; + for (int i = 0; i < p.size(); i++){ + int j = (i+1)%p.size(); + if ((p[i].y <= q.y && q.y < p[j].y || + p[j].y <= q.y && q.y < p[i].y) && + q.x < p[i].x + (p[j].x - p[i].x) * (q.y - p[i].y) / (p[j].y - p[i].y)) + c = !c; + } + return c; +} + +// determine if point is on the boundary of a polygon +bool PointOnPolygon(const vector &p, PT q) { + for (int i = 0; i < p.size(); i++) + if (dist2(ProjectPointSegment(p[i], p[(i+1)%p.size()], q), q) < EPS) + return true; + return false; +} + +// compute intersection of line through points a and b with +// circle centered at c with radius r > 0 +vector CircleLineIntersection(PT a, PT b, PT c, double r) { + vector ret; + b = b-a; + a = a-c; + double A = dot(b, b); + double B = dot(a, b); + double C = dot(a, a) - r*r; + double D = B*B - A*C; + if (D < -EPS) return ret; + ret.push_back(c+a+b*(-B+sqrt(D+EPS))/A); + if (D > EPS) + ret.push_back(c+a+b*(-B-sqrt(D))/A); + return ret; +} + +// compute intersection of circle centered at a with radius r +// with circle centered at b with radius R +vector CircleCircleIntersection(PT a, PT b, double r, double R) { + vector ret; + double d = sqrt(dist2(a, b)); + if (d > r+R || d+min(r, R) < max(r, R)) return ret; + double x = (d*d-R*R+r*r)/(2*d); + double y = sqrt(r*r-x*x); + PT v = (b-a)/d; + ret.push_back(a+v*x + RotateCCW90(v)*y); + if (y > 0) + ret.push_back(a+v*x - RotateCCW90(v)*y); + return ret; +} + +// This code computes the area or centroid of a (possibly nonconvex) +// polygon, assuming that the coordinates are listed in a clockwise or +// counterclockwise fashion. Note that the centroid is often known as +// the "center of gravity" or "center of mass". +double ComputeSignedArea(const vector &p) { + double area = 0; + for(int i = 0; i < p.size(); i++) { + int j = (i+1) % p.size(); + area += p[i].x*p[j].y - p[j].x*p[i].y; + } + return area / 2.0; +} + +double ComputeArea(const vector &p) { + return fabs(ComputeSignedArea(p)); +} + +PT ComputeCentroid(const vector &p) { + PT c(0,0); + double scale = 6.0 * ComputeSignedArea(p); + for (int i = 0; i < p.size(); i++){ + int j = (i+1) % p.size(); + c = c + (p[i]+p[j])*(p[i].x*p[j].y - p[j].x*p[i].y); + } + return c / scale; +} + +// tests whether or not a given polygon (in CW or CCW order) is simple +bool IsSimple(const vector &p) { + for (int i = 0; i < p.size(); i++) { + for (int k = i+1; k < p.size(); k++) { + int j = (i+1) % p.size(); + int l = (k+1) % p.size(); + if (i == l || j == k) continue; + if (SegmentsIntersect(p[i], p[j], p[k], p[l])) + return false; + } + } + return true; +} + +// 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product. +// Returns a positive value, if OAB makes a counter-clockwise turn, +// negative for clockwise turn, and zero if the points are collinear. +double cross(const PT &O, const PT &A, const PT &B) +{ + return (long)(A.x - O.x) * (B.y - O.y) - (long)(A.y - O.y) * (B.x - O.x); +} + +// Returns a list of points on the convex hull in counter-clockwise order. +// Note: the last point in the returned list is the same as the first one. +vector convex_hull(vector P) +{ + int n = P.size(), k = 0; + vector H(2*n); + + // Sort points lexicographically + sort(P.begin(), P.end()); + + // Build lower hull + for (int i = 0; i < n; ++i) { + while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--; + H[k++] = P[i]; + } + + // Build upper hull + for (int i = n-2, t = k+1; i >= 0; i--) { + while (k >= t && cross(H[k-2], H[k-1], P[i]) <= 0) k--; + H[k++] = P[i]; + } + + H.resize(k); + return H; +} + + +int main() { + + // expected: (-5,2) + cerr << RotateCCW90(PT(2,5)) << endl; + + // expected: (5,-2) + cerr << RotateCW90(PT(2,5)) << endl; + + // expected: (-5,2) + cerr << RotateCCW(PT(2,5),M_PI/2) << endl; + + // expected: (5,2) + cerr << ProjectPointLine(PT(-5,-2), PT(10,4), PT(3,7)) << endl; + + // expected: (5,2) (7.5,3) (2.5,1) + cerr << ProjectPointSegment(PT(-5,-2), PT(10,4), PT(3,7)) << " " + << ProjectPointSegment(PT(7.5,3), PT(10,4), PT(3,7)) << " " + << ProjectPointSegment(PT(-5,-2), PT(2.5,1), PT(3,7)) << endl; + + // expected: 6.78903 + cerr << DistancePointPlane(4,-4,3,2,-2,5,-8) << endl; + + // expected: 1 0 1 + cerr << LinesParallel(PT(1,1), PT(3,5), PT(2,1), PT(4,5)) << " " + << LinesParallel(PT(1,1), PT(3,5), PT(2,0), PT(4,5)) << " " + << LinesParallel(PT(1,1), PT(3,5), PT(5,9), PT(7,13)) << endl; + + // expected: 0 0 1 + cerr << LinesCollinear(PT(1,1), PT(3,5), PT(2,1), PT(4,5)) << " " + << LinesCollinear(PT(1,1), PT(3,5), PT(2,0), PT(4,5)) << " " + << LinesCollinear(PT(1,1), PT(3,5), PT(5,9), PT(7,13)) << endl; + + // expected: 1 1 1 0 + cerr << SegmentsIntersect(PT(0,0), PT(2,4), PT(3,1), PT(-1,3)) << " " + << SegmentsIntersect(PT(0,0), PT(2,4), PT(4,3), PT(0,5)) << " " + << SegmentsIntersect(PT(0,0), PT(2,4), PT(2,-1), PT(-2,1)) << " " + << SegmentsIntersect(PT(0,0), PT(2,4), PT(5,5), PT(1,7)) << endl; + + // expected: (1,2) + cerr << ComputeLineIntersection(PT(0,0), PT(2,4), PT(3,1), PT(-1,3)) << endl; + + // expected: (1,1) + cerr << ComputeCircleCenter(PT(-3,4), PT(6,1), PT(4,5)) << endl; + + vector v; + v.push_back(PT(0,0)); + v.push_back(PT(5,0)); + v.push_back(PT(5,5)); + v.push_back(PT(0,5)); + + // expected: 1 1 1 0 0 + cerr << PointInPolygon(v, PT(2,2)) << " " + << PointInPolygon(v, PT(2,0)) << " " + << PointInPolygon(v, PT(0,2)) << " " + << PointInPolygon(v, PT(5,2)) << " " + << PointInPolygon(v, PT(2,5)) << endl; + + // expected: 0 1 1 1 1 + cerr << PointOnPolygon(v, PT(2,2)) << " " + << PointOnPolygon(v, PT(2,0)) << " " + << PointOnPolygon(v, PT(0,2)) << " " + << PointOnPolygon(v, PT(5,2)) << " " + << PointOnPolygon(v, PT(2,5)) << endl; + + // expected: (1,6) + // (5,4) (4,5) + // blank line + // (4,5) (5,4) + // blank line + // (4,5) (5,4) + vector u = CircleLineIntersection(PT(0,6), PT(2,6), PT(1,1), 5); + for (int i = 0; i < u.size(); i++) cerr << u[i] << " "; cerr << endl; + u = CircleLineIntersection(PT(0,9), PT(9,0), PT(1,1), 5); + for (int i = 0; i < u.size(); i++) cerr << u[i] << " "; cerr << endl; + u = CircleCircleIntersection(PT(1,1), PT(10,10), 5, 5); + for (int i = 0; i < u.size(); i++) cerr << u[i] << " "; cerr << endl; + u = CircleCircleIntersection(PT(1,1), PT(8,8), 5, 5); + for (int i = 0; i < u.size(); i++) cerr << u[i] << " "; cerr << endl; + u = CircleCircleIntersection(PT(1,1), PT(4.5,4.5), 10, sqrt(2.0)/2.0); + for (int i = 0; i < u.size(); i++) cerr << u[i] << " "; cerr << endl; + u = CircleCircleIntersection(PT(1,1), PT(4.5,4.5), 5, sqrt(2.0)/2.0); + for (int i = 0; i < u.size(); i++) cerr << u[i] << " "; cerr << endl; + + // area should be 5.0 + // centroid should be (1.1666666, 1.166666) + PT pa[] = { PT(0,0), PT(5,0), PT(1,1), PT(0,5) }; + vector p(pa, pa+4); + PT c = ComputeCentroid(p); + cerr << "Area: " << ComputeArea(p) << endl; + cerr << "Centroid: " << c << endl; + + return 0; +} + diff --git a/Library/Math/linear_recurrence.cpp b/Library/Math/linear_recurrence.cpp new file mode 100755 index 0000000..0111191 --- /dev/null +++ b/Library/Math/linear_recurrence.cpp @@ -0,0 +1,234 @@ +//https://www.codechef.com/OCT16/problems/POWSUMS +//linear recurrence -> https://discuss.codechef.com/questions/49614/linear-recurrence-using-cayley-hamilton-theorem + +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pl; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpl; +typedef vector vvi; +typedef vector vvl; +const int mod = 1e9+7; +const int N = 315; +vi g[N]; +int n; +ll p[N], e[N], a[N]; +ll tem[N][N], hold[N][N]; +//BEGINS +const int MOD = 1e9 + 7; +const long long MOD2 = static_cast(MOD) * MOD; +const int MAX_K = 50; +vector C; +vector M; +ll A[N*2]; +struct coef +{ + vl mat; + int n_cols; + + coef() {} + + coef(vl values): mat(values), n_cols(values.size()){} + + static coef identity_coef(int n){ + vl res(n, 0); + res[0] = 1; + return coef(res); + } + coef operator*(const coef &other) const + { + int n = other.n_cols, i, j; + fo(i, 2*n) A[i] = 0; + fo(i, n) + fo(j, n){ + ll &ans = A[i+j]; + ans += (mat[i] * other.mat[j])%mod; + if (ans < 0) ans += mod; + if (ans >= mod) ans -= mod; + } + vl res(n, 0); + fo(i, n) { + res[i] += A[i]; + if (res[i] < 0) res[i] += mod; + if (res[i] >= mod) res[i] -= mod; + } + Fo(i, n, 2*n-1){ + ll mul = A[i]; + if (mul){ + fo(j, n){ + res[j] += (mul*C[i][j])%mod; + if (res[j] < 0) res[j] += mod; + if (res[j] >= mod) res[j] -= mod; + } + } + } + return coef(res); + } +}; + +// M_powers[i] is M, raised to 2^i-th power +coef M_powers[67]; + +void precalc_powers() +{ + M_powers[0] = coef(C[1]); + for(int i = 1; i < 67; i++) + M_powers[i] = M_powers[i - 1] * M_powers[i - 1]; +} + +coef mat_pow(ll power) +{ + coef result = coef::identity_coef(M_powers[0].mat.size()); + int pointer = 0; + while(power) { + if(power & 1) + result = result * M_powers[pointer]; + pointer++; + power >>= 1; + } + return result; +} + + + +//ENDS +int mpow(int base, int exp) { + base %= mod; + int result = 1; + while (exp > 0) { + if (exp & 1) result = ((ll)result * base) % mod; + base = ((ll)base * base) % mod; + exp >>= 1; + } + return result; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,k,j,q; + ll val,x ; + int sign; + int t; + cin>>t; + while(t--){ + e[0] = 1; + cin>>n>>q; + // fo(i, n) cin>>a[i]; + fo(i, n) cin>>p[i+1]; + e[1] = p[1]; + Fo(i, 2, n+1){ + val = 0; + sign = 1; + Fo(j, 1, i+1){ + val += (sign*p[j]*e[i-j])%mod; + if (val < 0) val += mod; + if (val >= mod) val -= mod; + sign *= -1; + } + val *= mpow(i, mod-2); + val %= mod; + e[i] = val; + } + M.resize(n, vl(n, 0)); + C.resize(2*n-1, vl(n, 0)); + //build matrix + sign = 1; + //construct 1st row of M + M[0][0] = 1; + fo(i, n) + // M[1][i] = a[i]; + M[1][i] = sign*e[i+1], sign *= -1; + //construct rows of M^2, M^3, .. M^{n-1} + Fo(i, 2, n){ + fo(j, n){ + //M[i][j] = ? + int pre = 0; + if(j!=n-1) pre = M[i-1][j+1]; + ll &ans = M[i][j]; + ans = (M[i-1][0]*M[1][j] + pre)%mod; + if (ans < 0) ans += mod; + } + } + //find coefficients of M^i as C[i][0...n-1] M^i = sum(C[i][j]*M^j) + //i from [0, n) + fo(i, n) fo(j, n) C[i][j] = 0; + fo(i, n) C[i][i] = 1; + //set for M^n -> use characteristic + fo(i, n) + C[n][n-1-i] = (mod+M[1][i])%mod; + + //i from [n+1, 2n-2] + Fo(i, n+1, 2*n-1){ + C[i][0] = (C[i-1][n-1]*C[n][0])%mod; + if(C[i][0] < 0) C[i][0] += mod; + Fo(j, 1, n){ + ll &ans = C[i][j]; + ans = (C[i-1][n-1]*C[n][j] + C[i-1][j-1])%mod; + if (ans < 0) ans += mod; + } + } + + //matrix M(mat); + precalc_powers(); + //answer queries + ll mx = 0; + while(q--) { + cin>>x; + x -= n; + + //mat^x + // fo(i, n) fo(j, n) M[i][j] = mat[i][j]; + coef res = mat_pow(x); + // fo(i, n) cout<= mod) A[j] -= mod; + if (A[j] < 0) A[j] += mod; + } + } + } + //A[i] * p[n-i] + fo(i, n) { + val += (A[i]*p[n-i])%mod; + if (val >= mod) val -= mod; + if (val < 0) val += mod; + } + cout< +#include +using namespace std; +template class matrix +{ + public: + typedef T value_type; + private: + vector > M; + public: + matrix(){} + + matrix(int rSize,int cSize) + { + M.assign(rSize,vector(cSize)); + } + void assign(int rSize,int cSize) + { + M.assign(rSize,vector(cSize)); + } + + vector& operator[](int i) + { + return M[i]; + } + + int rowSize() const + { + return M.size(); + } + int columnSize() const + { + if(M.size()==0) + return 0; + else + return M[0].size(); + } + matrix operator *(matrix B) //assumes matricces are multiplicable + { + matrix &A=*this; + matrix temp(A.rowSize(),B.columnSize()); + + for(int i=0;i operator %(value_type MOD) + { + matrix temp(rowSize(),columnSize()); + for(int i=0;i identity(int i) + { + matrix X; + X.assign(i,i); + for(int j=0;j T p(T &n,long long m,int MOD) +{ + if(m==0) + return matrix::identity(n.rowSize()); + + T x=p(n,m/2,MOD); + if(m%2==0) + return (x*x)%MOD; + else + return (((x*x)%MOD)*n)%MOD; +} +template void printMatrix(matrix X) +{ + for(int i=0;i T(26,26); + for(int i=0;i>T[i][j]; + + const int MOD = 1000000007; + int t; + cin>>t; + while(t--){ + char endChar; + long long length; + cin>>endChar>>length; + matrix solutionMatrix = p(T,length-1, MOD); + long long solution = 0; + for(int i=0;i mat; + matrix(){ + ; + } + matrix(int x, int y = 0, int iden = 0){ + n = x; m = y; + if(y==0) m = n; + mat = vector(n, vi(m, 0)); + if(iden){ + int i; + fo(i, n) mat[i][i] = 1; + } + } + void out(){ + int i, j; + fo(i, n){fo(j, m)cout<=mod) ans -= mod; + } + return ans; + } + int colsum(int x){ + int i; + ll ans = 0; + fo(i, n){ + ans += mat[i][x]; + if (ans>=mod) ans -= mod; + } + return ans; + } +}; +matrix operator *(matrix a, matrix b){ + matrix c = matrix(a.n); + int i, j, k, n = c.n; + fo(i, n)fo(j, n){ + int &val = c.mat[i][j]; + val = 0; + fo(k, n){ + val += (a.mat[i][k]*1LL*b.mat[k][j])%mod; + if (val >= mod) val -= mod; + } + } + return c; +} +matrix operator *(int a, matrix b){ + matrix c = matrix(a.n); + int i, j, k, n = c.n; + fo(i, n)fo(j, n){ + int &val = c.mat[i][j]; + val = (a*b.mat[i][j])%mod; + } + return c; +} +matrix operator +(matrix a, matrix b){ + matrix c = matrix(a.n); + int i, j, k, n = c.n; + fo(i, n)fo(j, n){ + int &val = c.mat[i][j]; + val = (a.mat[i][j]+b.mat[i][j]); + if (val >= mod) val -= mod; + } + return c; +} +matrix operator -(matrix a, matrix b){ + matrix c = matrix(a.n); + int i, j, k, n = c.n; + fo(i, n)fo(j, n){ + int &val = c.mat[i][j]; + val = (a.mat[i][j]-b.mat[i][j]); + if (val >= mod) val -= mod; + if (val < 0) val += mod; + } + return c; +} +matrix operator %(matrix M, int MOD) +{ + matrix temp(M.n); + for(int i=0;i 0: + s, n = s + fact[n % 10], n // 10 + return s + + + +#--- find the nth Fibonacci number--------------------------------------------------------------- +def fibonacci(n): + """ + Find the nth number in the Fibonacci series. Example: + + >>>fibonacci(100) + 354224848179261915075 + + Algorithm & Python source: Copyright (c) 2013 Nayuki Minase + Fast doubling Fibonacci algorithm + http://nayuki.eigenstate.org/page/fast-fibonacci-algorithms + """ + if n < 0: + raise ValueError("Negative arguments not implemented") + return _fib(n)[0] + +# Returns a tuple (F(n), F(n+1)) +def _fib(n): + if n == 0: + return (0, 1) + else: + a, b = _fib(n // 2) + c = a * (2 * b - a) + d = b * b + a * a + if n % 2 == 0: + return (c, d) + else: + return (d, c + d) + + +#--- sum of squares of digits------------------------------------------------------------------- +def sos_digits(n): + s = 0 + while n > 0: + s, n = s + (n % 10)**2, n // 10 + return s + +#--- sum of the digits to a power e------------------------------------------------------------- +def pow_digits(n, e): + s = 0 + while n > 0: + s, n = s + (n % 10)**e, n // 10 + return s + + + +#--- check n for prime-------------------------------------------------------------------------- +def is_prime(n): + if n <= 1: return False + if n <= 3: return True + if n%2==0 or n%3 == 0: return False + r = int(sqrt(n)) + f = 5 + while f <= r: + if n%f == 0 or n%(f+2) == 0: return False + f+= 6 + return True + + + + +#--- Miller-Rabin primality test---------------------------------------------------------------- +def miller_rabin(n): + """ + Check n for primalty: Example: + + >miller_rabin(162259276829213363391578010288127) #Mersenne prime #11 + True + + Algorithm & Python source: + http://en.literateprograms.org/Miller-Rabin_primality_test_(Python) + """ + d = n - 1 + s = 0 + while d % 2 == 0: + d >>= 1 + s += 1 + for repeat in range(20): + a = 0 + while a == 0: + a = random.randrange(n) + if not miller_rabin_pass(a, s, d, n): + return False + return True + +def miller_rabin_pass(a, s, d, n): + a_to_power = pow(a, d, n) + if a_to_power == 1: + return True + for i in range(s-1): + if a_to_power == n - 1: + return True + a_to_power = (a_to_power * a_to_power) % n + return a_to_power == n - 1 + + + +#--- factor a number into primes and frequency---------------------------------------------------- +""" + find the prime factors of n along with their frequencies. Example: + + >>> factor(786456) + [(2,3), (3,3), (11,1), (331,1)] + + Source: Project Euler forums for problem #3 +""" +def factor(n): + f, factors, prime_gaps = 1, [], [2, 4, 2, 4, 6, 2, 6, 4] + if n < 1: + return [] + while True: + for gap in ([1, 1, 2, 2, 4] if f < 11 else prime_gaps): + f += gap + if f * f > n: # If f > sqrt(n) + if n == 1: + return factors + else: + return factors + [(n, 1)] + if not n % f: + e = 1 + n //= f + while not n % f: + n //= f + e += 1 + factors.append((f, e)) + + +#--- greatest common divisor---------------------------------------------------------------------- +def gcd(a, b): + """ + Compute the greatest common divisor of a and b. Examples: + + >>> gcd(14, 15) #co-prime + 1 + >>> gcd(5*5, 3*5) + 5 + """ + if a < 0: a = -a + if b < 0: b = -b + if a == 0: return b + while (b): a, b = b, a%b + return a + + + + +#--- generate permutations----------------------------------------------------------------------- +def perm(n, s): + """ + requires function factorial() + Find the nth permutation of the string s. Example: + + >>>perm(30, 'abcde') + bcade + """ + if len(s)==1: return s + q, r = divmod(n, factorial(len(s)-1)) + return s[q] + perm(r, s[:q] + s[q+1:]) + + + + +#--- binomial coefficients----------------------------------------------------------------------- +def binomial(n, k): + """ + Calculate C(n,k), the number of ways can k be chosen from n. Example: + + >>>binomial(30,12) + 86493225 + """ + nt = 1 + for t in range(min(k, n-k)): + nt = nt * (n-t) // (t+1) + return nt + + +#--- catalan number------------------------------------------------------------------------------ +def catalan_number(n): + """ + Calculate the nth Catalan number. Example: + + >>>catalan_number(10) + 16796 + """ + nm = dm = 1 + for k in range(2, n+1): + nm, dm = (nm*(n+k), dm*k) + return nm / dm + + + +#--- generate prime numbers---------------------------------------------------------------------- +def prime_sieve(n): + """ + Return a list of prime numbers from 2 to a prime < n. Very fast (n<10,000,000) in 0.4 sec. + + Example: + >>>prime_sieve(25) + [2, 3, 5, 7, 11, 13, 17, 19, 23] + + Algorithm & Python source: Robert William Hanks + http://stackoverflow.com/questions/17773352/python-sieve-prime-numbers + """ + sieve = [True] * (n/2) + for i in xrange(3,int(n**0.5)+1,2): + if sieve[i/2]: + sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*i)+1) + return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]] + + +#--- bezout coefficients-------------------------------------------------------------------------- +def bezout(a,b): + """ + Bézout coefficients (u,v) of (a,b) as: + + a*u + b*v = gcd(a,b) + + Result is the tuple: (u, v, gcd(a,b)). Examples: + + >>> bezout(7*3, 15*3) + (-2, 1, 3) + >>> bezout(24157817, 39088169) #sequential Fibonacci numbers + (-14930352, 9227465, 1) + + Algorithm source: Pierre L. Douillet + http://www.douillet.info/~douillet/working_papers/bezout/node2.html + """ + u, v, s, t = 1, 0, 0, 1 + while b !=0: + q, r = divmod(a,b) + a, b = b, r + u, s = s, u - q*s + v, t = t, v - q*t + + return (u, v, a) + +#--- number base conversion ------------------------------------------------------------------- +#source: http://interactivepython.org/runestone/static/pythonds/Recursion/pythondsConvertinganIntegertoaStringinAnyBase.html +def dec2base(n,base): + convertString = "0123456789ABCDEF" + if n < base: + return convertString[n] + else: + return dec2base(n//base,base) + convertString[n%base] + +#--- number to words ---------------------------------------------------------------------------- +#this function copied from stackoverflow user: Developer, Oct 5 '13 at 3:45 +def n2words(num,join=True): + '''words = {} convert an integer number into words''' + units = ['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] + teens = ['','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen', \ + 'Seventeen','Eighteen','Nineteen'] + tens = ['','Ten','Twenty','Thirty','Forty','Fifty','Sixty','Seventy', \ + 'Eighty','Ninety'] + thousands = ['','Thousand','Million','Billion','Trillion','Quadrillion', \ + 'Quintillion','Sextillion','Septillion','Octillion', \ + 'Nonillion','Decillion','Undecillion','Duodecillion', \ + 'Tredecillion','Quattuordecillion','Sexdecillion', \ + 'Septendecillion','Octodecillion','Novemdecillion', \ + 'Vigintillion'] + words = [] + if num==0: words.append('zero') + else: + numStr = '%d'%num + numStrLen = len(numStr) + groups = (numStrLen+2)/3 + numStr = numStr.zfill(groups*3) + for i in range(0,groups*3,3): + h,t,u = int(numStr[i]),int(numStr[i+1]),int(numStr[i+2]) + g = groups-(i/3+1) + if h>=1: + words.append(units[h]) + words.append('Hundred') + if t>1: + words.append(tens[t]) + if u>=1: words.append(units[u]) + elif t==1: + if u>=1: words.append(teens[u]) + else: words.append(tens[t]) + else: + if u>=1: words.append(units[u]) + if (g>=1) and ((h+t+u)>0): words.append(thousands[g]+'') + if join: return ' '.join(words) + return words + diff --git a/Library/Math/projecteuelr/Miller-rabin-primality-test.cpp b/Library/Math/projecteuelr/Miller-rabin-primality-test.cpp new file mode 100755 index 0000000..f700d22 --- /dev/null +++ b/Library/Math/projecteuelr/Miller-rabin-primality-test.cpp @@ -0,0 +1,78 @@ +#include +using namespace std; + +typedef long long ll; + +int T; +ll mod; +int b[]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97}; +ll a[]={1996011519951206ll,1995120619960115ll,1995100319960115ll,195100319951206ll,1996011519951003ll}; + + +ll multi(ll x,ll y) +{ + ll w=x*y-mod*(ll(double(x)*y/mod+1e-3)); + while(w<0) + w+=mod; + while(w>=mod) + w-=mod; + return w; +} + +ll pow(ll x,ll y) +{ + ll t=1; + while(y) + { + if(y&1) + t=multi(t,x); + x=multi(x,x); + y>>=1; + } + return t; +} + +bool judge(ll n) +{ + if(n==2) return true; + if(n<2||!(n&1)) return false; + for(int i=0;i<25;i++) + if(n%b[i]==0&&n!=b[i]) + return false; + mod=n; + int t=0; + ll u=n-1; + while(!(u&1)) t++,u>>=1; + for(int i=0;i<5;i++) + { + ll x=a[i]%(n-1)+1; + x=pow(x,u); + ll y=x; + for(int j=1;j<=t;j++) + { + x=multi(x,x); + if(x==1&&y!=1&&y!=n-1) + return false; + y=x; + } + if(x!=1) return false; + } + return true; +} + +int main() +{ + // judge(n) check whether a number is prime or not +// ll n,lower,upper,count=0,numcount=0; +// lower=3; upper=19; +// for(n=lower;n<=upper;n=n+4) +// { +// if(judge(n)) cout< +using namespace std; +struct PT{ + double x, y; + PT(){} + PT(int a, int b){ + x = a, y = b; + } + PT unit(){ + return PT(x/mag(), y/mag()); + } + double mag(){ + return sqrt(x*x+y*y); + } +}; +//returns dot product +double operator*(PT &a, PT &b){ + return a.x*b.x + a.y*b.y; +} +#define PI 3.1415926535897932384626 +double ang(PT &a, PT &b){ + double c0 = (a*b)/(a.mag()*b.mag()); + return acos(c0)*180/PI; +} + +int main() { + // your code goes here + PT a(1, 0); + PT b(-2, 2); + cout< +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +//http://codeforces.com/gym/100570/problem/D +//"2-sat" and "small to large" merging +//N must be atleast twice the value of nodes +const int N = 5e5; + +int a[N], par[N], n, q; +map mep; +vi comp[N]; + +void add(ll &x){ + if (mep.find(x) == mep.end()) + mep[x] = mep.size(); + x = mep[x]; +} + +void out(){ + while(q++ < n) printf("No\n"); + exit(0); +} +void merge(int u, int v){ + u = par[u]; + v = par[v]; + if (u == v) return; + if ((int)comp[u].size() > (int)comp[v].size()) swap(u, v); + //v is bada + vi &r = comp[v]; + // each time we merge two components + // size increases atleast by 2 * chote set ka size + //each node can move at most log2(n) times + // n * log(n) complexity mei merge hojayega + for(int x: comp[u]){ + if (par[x^1] == v) out(); + r.pb(x); + par[x] = v; + } +} +int main() +{ + //ios_base::sync_with_stdio(false); + //cin.tie(NULL); + int i,k,j; + si(n); + ll x, y, a, b; + fo(i, N) par[i] = i, comp[i].clear(), comp[i].pb(i); + fo(i, n){ + q = i; + sl(x); sl(y); sl(a); sl(b); + y = -y; + add(x); add(y); + x *= 2; + y *= 2; + if (a == b){ + merge(x, y); + merge(x^1, y^1); + } + else{ + merge(x, y^1); + merge(x^1, y); + } + printf("Yes\n"); + } + + return 0; +} + diff --git a/Library/Miscellanious/MosMaxFrequency.cpp b/Library/Miscellanious/MosMaxFrequency.cpp new file mode 100755 index 0000000..4172d7e --- /dev/null +++ b/Library/Miscellanious/MosMaxFrequency.cpp @@ -0,0 +1,171 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;i pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 2e5; +const int N = 3e5; +vi g[N]; +int a[N]; +void dfs(int u, int par); +//http://codeforces.com/contest/600/problem/E +static int t = 0; +int BLOCK = sqrt(mod); +bool f(pair a, pair b){ + if (a.S.F / BLOCK != b.S.F / BLOCK) return a.S.F < b.S.F; + return a.S.S < b.S.S; +} + +ll sum = 0, occ = 0; +ll ans[N], val[N]; +int cnt[N], col[N], rep[N], in[N], out[N], agla[N], pre[N]; +set dom; +set mx; +//ADD , DEL a number and store the sum of max occuring nos in 'sum' +void add(int pos){ + //c is the variable that we are adding here + int c = rep[pos]; + val[cnt[c]] -= c; + int pr = pre[cnt[c]]; + int nxt = agla[cnt[c]]; + if (val[cnt[c]] == 0) { + if (nxt == cnt[c]){ + //this is highest + occ = pr; + agla[pr] = pr; + } + else{ + pre[nxt] = pr; + agla[pr] = nxt; + } + agla[cnt[c]] = pre[cnt[c]] = -1; + } + cnt[c]++; + val[cnt[c]] += c; + + if (cnt[c] > occ){ + agla[occ] = cnt[c]; + pre[cnt[c]] = occ; + occ = cnt[c]; + } + else if (cnt[c] < nxt){ + agla[pr] = cnt[c]; + pre[cnt[c]] = pr; + agla[cnt[c]] = nxt; + pre[nxt] = cnt[c]; + } + agla[occ] = occ; + sum = val[occ]; +} +void del(int pos){ + int c = rep[pos]; + val[cnt[c]] -= c; + int pr = pre[cnt[c]]; + int nxt = agla[cnt[c]]; + if (val[cnt[c]] == 0) { + if (nxt == cnt[c]){ + //this is highest + occ = pr; + agla[pr] = pr; + } + else{ + pre[nxt] = pr; + agla[pr] = nxt; + } + agla[cnt[c]] = pre[cnt[c]] = -1; + } + cnt[c]--; + val[cnt[c]] += c; + if (cnt[c] > occ){ + agla[occ] = cnt[c]; + pre[cnt[c]] = occ; + occ = cnt[c]; + } + else if (cnt[c] > pr){ + agla[pr] = cnt[c]; + pre[cnt[c]] = pr; + agla[cnt[c]] = nxt; + pre[nxt] = cnt[c]; + } + agla[occ] = occ; + sum = val[occ]; +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int n, i; + si(n); + set dis_col; + fo (i, n) si(col[i+1]), dis_col.insert(col[i+1]); + tr(it, dis_col) val[0] += *it; + + fo(i, n-1){ + int u, v; + si(u); si(v); + g[u].pb(v); + g[v].pb(u); + } + dfs(1, 0); + vector< pair > Q; + Fo(i, 1, n+1) Q.pb( { i, {in[i], out[i]} } ); + sort(Q.begin(), Q.end(), f); + int L , R, curl, curr; + curl = curr = 0; + fo(i, n){ + pair q = Q[i]; + L = q.S.F, R = q.S.S; + + while( curl > L){ + add(curl-1); + curl--; + } + while( curr < R){ + add(curr+1); + curr++; + } + while( curl < L){ + del(curl); + curl++; + } + while( curr > R){ + del(curr); + curr--; + } + ans[q.F] = sum; + } + Fo(i, 1, n+1) printf("%I64d ",ans[i]); + return 0; +} + +void dfs(int u, int par){ + in[u] = ++t; + rep[t] = col[u]; + for(int v:g[u]){ + if (v == par) continue; + dfs(v, u); + } + out[u] = ++t; + rep[t] = col[u]; +} diff --git a/Tree/SmallToLarge.cpp b/Library/Miscellanious/SmallToLarge.cpp old mode 100644 new mode 100755 similarity index 100% rename from Tree/SmallToLarge.cpp rename to Library/Miscellanious/SmallToLarge.cpp diff --git a/Library/Miscellanious/hash_adjaceny_list.cpp b/Library/Miscellanious/hash_adjaceny_list.cpp new file mode 100755 index 0000000..15d0665 --- /dev/null +++ b/Library/Miscellanious/hash_adjaceny_list.cpp @@ -0,0 +1,148 @@ +#include +//http://codeforces.com/contest/794/submission/27087664 +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pl; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpl; +typedef vector vvi; +typedef vector vvl; +int mpow(int base, int exp); +void ipgraph(int m); +void dfs(int u, int par); +const ll mod = 1000000007*1LL*1000000007; +const int N = 3e5 + 3, M = N; +//======================= + +set g[N]; +int sz[N], par[N]; +int rep(int x){ + if(x == par[x]) return x; + return par[x] = rep(par[x]); +} +void unite(int x, int y){ + x = rep(x); + y = rep(y); + if(x==y)return; + if(sz[x] taken; +set allvals; +map com; +int ass[N], T; +void go(int u){ + + int cur = ass[u]; + for(int v: g[u]){ + if(ass[v]){ + if(abs(ass[v]-ass[u])>1){ + cout <<"NO\n"; + exit(0); + } + } + else{ + if(!taken[cur+1]) + ass[v] = cur+1; + else if(!taken[cur-1]) + ass[v] = cur-1; + else{ + cout <<"NO\n"; + exit(0); + } + T = max(T, ass[v]+2); + taken[ass[v]] = 1; + go(v); + } + } +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,n,k,j, u, v, x, y, a, b, c, m; + cin >> n >> m; + srand(1234); + Fo(i, 1, n+1) h[i] = (r()*r()+r())%mod; + Fo(i, 1, n+1){ + par[i] = i; + sz[i] = 0; + } + fo(i, m) { + cin >> u >> v; + g[u].insert(v); + g[v].insert(u); + } + Fo(i, 1, n+1){ + val[i] = h[i]; + for(int x: g[i]){ + val[i] = (val[i] + h[x])%mod; + } + allvals.insert(val[i]); + com[val[i]].pb(i); + } + for(ll c: allvals){ + int x = com[c].size(); + if(x>1){ + u = com[c][0]; + for(int v: com[c]) + unite(u, v); + } + } + Fo(i, 1, n+1){ + set allnew; allnew.clear(); + for(int v: g[i]){ + allnew.insert(rep(v)); + } + g[i].clear(); + for(int v: allnew) { + if(v != i) + g[i].insert(v); + } + int nsz = g[i].size(); + if(nsz > 2 and i == rep(i)){ + cout <<"NO\n"; + return 0; + } + } + T = n+2; //take it bigger enough to avoid negative values + Fo(i, 1, n+1){ + u = rep(i); + if(u != i) continue; + if(!ass[i]) ass[i] = T,taken[T] = 1, go(i); + } + cout<<"YES\n"; + Fo(i, 1, n+1){ + cout << ass[rep(i)] << " "; + } + return 0; +} diff --git a/Library/Miscellanious/hash_unordered_map.cpp b/Library/Miscellanious/hash_unordered_map.cpp new file mode 100755 index 0000000..4bc70e6 --- /dev/null +++ b/Library/Miscellanious/hash_unordered_map.cpp @@ -0,0 +1,22 @@ +template +inline void hash_combine(std::size_t & seed, const T & v) +{ + std::hash hasher; + seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); +} + +namespace std +{ + template struct hash> + { + inline size_t operator()(const pair & v) const + { + size_t seed = 0; + ::hash_combine(seed, v.first); + ::hash_combine(seed, v.second); + return seed; + } + }; +} +//use it now +unordered_map dp; diff --git a/Library/Miscellanious/meet-in-middle.cpp b/Library/Miscellanious/meet-in-middle.cpp new file mode 100755 index 0000000..261a3a4 --- /dev/null +++ b/Library/Miscellanious/meet-in-middle.cpp @@ -0,0 +1,113 @@ +//http://codeforces.com/contest/525/problem/E +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pll; +typedef vector vi; +typedef vector vll; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 3e5; +vi g[N]; +int a[N]; +vi rep(int no, int len, int base){ + vi ans; + while(no){ + ans.pb(no%base); + no /= base; + } + while((int)ans.size() != len) ans.pb(0); + reverse(all(ans)); + return ans; +} +map cnt[30]; +ll fac[20]; +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,n,k,j, mask; + ll s, ans = 0; + cin>>n>>k>>s; + fo(i, n) cin>>a[i]; + int len = n/2, left = n-len; + int lim = pow(3, len); + fo(i, n+1) cnt[i].clear(); + fac[1] = 1; + Fo(i, 2, 20) fac[i] = fac[i-1]*i; + fo(mask, lim){ + vi bit = rep(mask, len, 3); + int used = 0; + ll sum = 0; + fo(i, bit.size()){ + int dig = bit[i]; + if(dig==0)continue; + else if(dig==1) sum += a[i]; + else if (a[i]<20)sum += fac[a[i]], used++; + else if(a[i]>=20) { + sum = -1; + break; + } + } + if(sum>=0){ + // for(int x:bit) cout<=20) { + sum = -1; + break; + } + } + if(sum>=0){ + int remk = k-used; + ll need = s-sum; + while(remk>=0 and need>=0 ){ + if(cnt[remk].count(need)) + ans += cnt[remk][need]; + remk--; + } + } + } + + cout< 2.35 and not 2.34 as in scientific +void out(double x, int n){ + cout< +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pl; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpl; +typedef vector vvi; +typedef vector vvl; +int mpow(int base, int exp); +void ipgraph(int m); +void dfs(int u, int par); +const int mod = 1000000007; +const int N = 3e5, M = N; +//======================= + +vi g[N]; +int a[N]; +/* +Input: A vector of intervals in any random order +Output: +1. Removes redundant intervals ie remove [2,3] if [1,4] is present. +2. does NOT merge overlapping intervals. +3. Sorted in ascending order of starting interval which are distinct. +*/ +void fun_interval(vpii &in){ + int i = 1, n = in.size(); + sort(in.begin(), in.end(), [](pii x, pii y){if(x.F == y.F)return x.S>y.S;return x.F=in[i].S)continue; + hi = in[i].S; + took.pb(in[i]); + } + in.clear(); + for(pii x: took) in.pb(x); +// Uncomment the following lines, if you wish to sort intervals on asc order of HI value. +// for(auto& x: in) swap(x.F,x.S); // [lo, hi] is converted to [hi, lo]. +// sort(in.begin(), in.end(), [](pii x, pii y){return x.F> n; + vpii in(n, {0,0}); + fo(i, n) cin >> in[i].F >> in[i].S ; + fun_interval(in); + for(pii x: in) cout << x.F << " " << x.S << endl; + + return 0; +} +/* +Input: +5 +1 4 +0 3 +2 3 +0 5 +3 9 +Output: +0 5 +3 9 +*/ diff --git a/Miscellanious/parallel_binary_search.cpp b/Library/Miscellanious/parallel_binary_search.cpp old mode 100644 new mode 100755 similarity index 100% rename from Miscellanious/parallel_binary_search.cpp rename to Library/Miscellanious/parallel_binary_search.cpp diff --git a/Library/Miscellanious/popcount.cpp b/Library/Miscellanious/popcount.cpp new file mode 100755 index 0000000..bacd80d --- /dev/null +++ b/Library/Miscellanious/popcount.cpp @@ -0,0 +1,20 @@ +int popc[66000]; + +int popcount(int x) { + return popc[x & 0xffff] + popc[(x>>16) & 0xffff]; +} + +string ThueMorseGame::get(int n,int m) +{ + popc[0] = 0; + for (int i = 1; i < (1<<16); i++) popc[i] = popc[i & (i-1)] + 1; + + int currl = 0; + while(currl + m + 1 <= n) + { + currl+= m + 1; + while(currl<=n && (popcount(currl) & 1))++currl; + } + if(currl == n)return "Bob"; + return "Alice"; +} diff --git a/Library/Miscellanious/range_sum.cpp b/Library/Miscellanious/range_sum.cpp new file mode 100755 index 0000000..d3c99f5 --- /dev/null +++ b/Library/Miscellanious/range_sum.cpp @@ -0,0 +1,98 @@ +#include +// http://ideone.com/jsXeQn +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pl; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpl; +typedef vector vvi; +typedef vector vvl; +int mpow(int base, int exp); +void ipgraph(int m); +void dfs(int u, int par); +const int mod = 1000000007; +const int N = 3e5, M = N; +//======================= + +vi g[N]; +ll a[N]; +//Input: Array and queries asking {sum, no} +// of elements less than given x +//log(n) per query +class RangeSum{ + int n; + vector A; + set> my; + public: + RangeSum(long long a[], int nn){ + sort(a, a+nn); + int i; + n = nn; + A = {0}; + fo(i, n){ + A.push_back(A[i]+a[i]); + my.insert({a[i], i+1}); + } + } + RangeSum(vector &a){ + sort(a.begin(), a.end()); + int i; + n = a.size(); + A = {0}; + fo(i, n){ + A.push_back(A[i]+a[i]); + my.insert({a[i], i+1}); + } + } + //Returns {sum, no} where + // sum = sum of ele <= val + // no = # of ele <= val + pair sum(long long val){ + if(n == 0) return {0, 0}; + auto it = my.lower_bound({val, n+1}); + if(it == my.end()) return {A[n], n}; + if((*it).F == val) return {A[(*it).S], (*it).S}; + return {A[(*it).S-1], (*it).S-1}; + } + pair sum(long long x, long long y){ + if(x>y) swap(x,y); + pl p = sum(y); + pl q = sum(x-1); + return {p.first-q.first, p.second-q.second}; + } +}; +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,n,k,j; + cin >> n; + fo(i, n) cin >> a[i]; + RangeSum my(a, n); + cout << my.sum(5).F << " " < win; + int i; + //move from left to right + //initialse window [0, b-1] + fo(i, b){ + while(!win.empty() and win.back().F <= A[i]) win.pop_back(); + win.pb({A[i], i}); + } + fo(i, n){ + dp[i] = win.front().F; + int x = i+b; + if(x - inf + if(i+b-1 >= n) dp[i] = -inf; + } +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,n,k,j; + cin >> n; + vi A; + A.resize(n, 0); + fo(i, n) cin >> A[i]; + slide(A, 3); + fo(i, n) cout << dp[i] << " " ; + return 0; +} diff --git a/Library/Miscellanious/sos_dp.cpp b/Library/Miscellanious/sos_dp.cpp new file mode 100755 index 0000000..5cfffcd --- /dev/null +++ b/Library/Miscellanious/sos_dp.cpp @@ -0,0 +1,72 @@ +#include +// https://www.hackerearth.com/practice/algorithms/dynamic-programming/bit-masking/practice-problems/algorithm/special-pairs-7/description/ +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pl; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpl; +typedef vector vvi; +typedef vector vvl; +int mpow(int base, int exp); +void ipgraph(int m); +void dfs(int u, int par); +const int mod = 1000000007; +const int N = 1LL<<20, M = N; +//======================= + +vi g[N]; +int a[N]; +const int B = 20; +ll dp[N][B]; +int cnt[N]; +void sosdp(){ + int i, j; + fo(i, N){ + dp[i][0] = cnt[i]; + if(i&1) dp[i][0] += cnt[i^1]; + Fo(j, 1, B){ + dp[i][j] = dp[i][j-1]; + if(i&(1<> t; + int allone = 1<> n; + fo(i, n) cin >> a[i], cnt[a[i]]++; + sosdp(); + ll ans = 0; + fo(i, n) ans += dp[allone^a[i]][B-1], cnt[a[i]] = 0; + cout << ans << endl; + } + + return 0; +} diff --git a/Library/Miscellanious/template.cpp b/Library/Miscellanious/template.cpp new file mode 100644 index 0000000..896e4bb --- /dev/null +++ b/Library/Miscellanious/template.cpp @@ -0,0 +1,73 @@ +sing namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 5e5; +vi g[N]; +int a[N], par[N], ans[N], sz[N]; +int cen, n; +void ipgraph(int n, int m); +void dfs(int u, int p){ + sz[u] = 1; + for( int v: g[u]){ + if (v == p) continue; + dfs(v, u); + sz[u] += sz[v]; + } +} +void dfs2(int u, int p){ + sz[u] = 1; + if ( p == cen ) par[u] = u; + else par[u] = par[p]; + for( int v: g[u]){ + if (v == p) continue; + dfs2(v, u); + sz[u] += sz[v]; + } +} +void go(int u, int p){ + int hai = 1; + for(int v: g[u]){ + if ( v == p ) continue; + if ( sz[v] > n/2 ) hai = 0; + go(v, u); + } + int other = n - sz[u]; + if ( other > n/2 ) hai = 0; + if (hai) cen = u; +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i, m; + cin >> n ; + m = n - 1; + ipgraph(n, n-1); + clr(sz); + par[0] = 0; + dfs(1, 0); + go(1, 0); + dfs2(cen, 0); + int F, S, idx; + F = S = idx = -1; + Fo(i, 1, n+1) { + if (par[i] == i) { + if (sz[i] >= F){ + idx = i; + S = F; + F = sz[i]; + } + else if (sz[i] > S) S = sz[i]; + } + } + Fo(i, 1, n+1){ + if ( i == cen ) { + ans[i] = 1; + continue; + } + int rep = par[i]; + int mx, other; + if ( rep == idx ){ + mx = max(S, F - sz[i]); + } + else mx = F; + other = n - sz[i] - mx; + ans[i] = other <= n/2; + } + Fo(i, 1, n+1) cout<>u>>v; + u++, v++; + g[u-1].pb(v-1); + g[v-1].pb(u-1); + } +} diff --git a/Tree/HLD.cpp b/Library/Tree/HLD.cpp old mode 100644 new mode 100755 similarity index 100% rename from Tree/HLD.cpp rename to Library/Tree/HLD.cpp diff --git a/Tree/centroid_decomposition.cpp b/Library/Tree/centroid_decomposition.cpp old mode 100644 new mode 100755 similarity index 100% rename from Tree/centroid_decomposition.cpp rename to Library/Tree/centroid_decomposition.cpp diff --git a/Tree/centroid_example.cpp b/Library/Tree/centroid_example.cpp old mode 100644 new mode 100755 similarity index 100% rename from Tree/centroid_example.cpp rename to Library/Tree/centroid_example.cpp diff --git a/dp-on-tree-type-c-LCA.cpp b/Library/Tree/dp-on-tree-type-c-LCA.cpp similarity index 100% rename from dp-on-tree-type-c-LCA.cpp rename to Library/Tree/dp-on-tree-type-c-LCA.cpp diff --git a/Library/Tree/lca.cpp b/Library/Tree/lca.cpp new file mode 100755 index 0000000..1ddfb88 --- /dev/null +++ b/Library/Tree/lca.cpp @@ -0,0 +1,99 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;i pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 2e5; +vi g[N]; +const int LG = 20; +//LCA begins +//1 based index +int a[N], lvl[N], P[N][LG], sz[N]; +void dfs(int u, int par){ + sz[u] = 1; + lvl[u] = 1+lvl[par]; + P[u][0] = par; + for(int v:g[u]){ + if (v == par) continue; + dfs(v, u); + sz[u] += sz[v]; + } +} + +int lca(int u, int v){ + int i, lg; + if (lvl[u] < lvl[v]) swap(u, v); + for(lg = 0; (1<=0; i--){ + if (lvl[u] - (1<= lvl[v]) + u = P[u][i]; + } + if (u == v) return u; + for(i=lg; i>=0; i--){ + if (P[u][i] != -1 and P[u][i] != P[v][i]) + u = P[u][i], v = P[v][i]; + } + return P[u][0]; +} +int get(int u, int dis){ + dis = lvl[u] - dis; + int i, lg = 0; + for(; (1<=0; i--){ + if (lvl[u] - (1<= dis) + u = P[u][i]; + } + return u; +} +int dis(int u, int v){ + if (lvl[u] < lvl[v]) swap(u, v); + int w = lca(u, v); + return lvl[u] + lvl[v] - 2*lvl[w]; +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,n,q, m, j; + int u, v; + cin>>n>>m; + fo(i, n-1){ + cin>>u>>v; + g[u].pb(v); + g[v].pb(u); + } + fo(i, LG) fo(j, n+1) P[j][i] = -1; + lvl[0] = -1; + dfs(1, 0); + for(i=1; i +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;i pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +const int N = 2e5; +vi g[N]; +const int LG = 20; +#define red 1 +#define blue 0 +int a[N], col[N], lvl[N], P[N][LG], sz[N]; +ll in[N], out[N]; +void dfs(int u, int par){ + sz[u] = 1; + lvl[u] = 1+lvl[par]; + P[u][0] = par; + in[u] = col[u]==blue?0:mod; + for(int v:g[u]){ + if (v == par) continue; + dfs(v, u); + in[u] = min(in[u], 1+in[v]); + sz[u] += sz[v]; + } +} +void dfs1(int u, int par){ + if (par == 0) out[u] = mod; + else out[u] = 1 + out[par]; + ll F, S; F = S = mod; + for(int v:g[u]){ + if (v == par) continue; + if (F >= in[v]){ + S = F; + F = in[v]; + } + else if ( in[v] < S) S = in[v]; + } + for(int v: g[u]){ + if (v == par) continue; + ll use = F; + if (F == in[v]) use = S; + dfs1(v, u); + out[v] = min(out[v], 2+use); + } +} +//lvl[u] > lvl[v] +int lca(int u, int v){ + int i, lg; + for(lg = 0; (1<=0; i--){ + if (lvl[u] - (1<= lvl[v]) + u = P[u][i]; + } + if (u == v) return u; + for(i=lg; i>=0; i--){ + if (P[u][i] != -1 and P[u][i] != P[v][i]) + u = P[u][i], v = P[v][i]; + } + return P[u][0]; +} +int get(int u, int dis){ + dis = lvl[u] - dis; + int i, lg = 0; + for(; (1<=0; i--){ + if (lvl[u] - (1<= dis) + u = P[u][i]; + } + return u; +} +int dis(int u, int v){ + if (lvl[u] < lvl[v]) swap(u, v); + int w = lca(u, v); + return lvl[u] + lvl[v] - 2*lvl[w]; +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int i,n,q, m, j; + int u, v; + cin>>n>>m; + fo(i, n-1){ + cin>>u>>v; + g[u].pb(v); + g[v].pb(u); + } + fo(i, LG) fo(j, n+1) P[j][i] = -1; + lvl[0] = -1; + dfs(1, 0); + dfs1(1, 0); + for(i=1; i>ty>>u; + if (ty == 1) col[u]= red, redd.pb(u); + else { + int ans = mod; + ans = min(in[u], out[u]); + for(int x: redd) ans = min(ans, dis(u, x)); + cout< +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; +int mpow(int base, int exp); +void ipgraph(int n, int m); +void dfs(int u, int par); +//2d sparse table for max +//0 based index +//LGN = 1 + lg2(N) +//LGM = 1 + lg2(M) + +const int N = 1030; +const int M = 1030; +const int LGN = 11; +const int LGM = 11; +vi g[N]; +int a[N][M]; +int dp[N][LGN][M][LGM]; +const int MAXN = 2e6; //max(N, M) +int lg2[MAXN]; +void pre(){ + //build lg2 + lg2[1] = 0; + lg2[2] = 1; + int val = 1, at = 4; + int i; + Fo(i, 3, MAXN){ + if (i == at){ + at *= 2; + val++; + } + lg2[i] = val; + } +} +void build(int n, int m){ + int ir, ic, jr, jc; + //unit cells + fo(ir, n) + fo(ic, m) dp[0][ir][0][ic] = a[ir][ic]; + + //fill 1-d sparse table for all rows + fo(ir, n) + Fo(jc, 1, LGM) + for(ic = 0; ic + (1<>n>>m; + fo(i,n)fo(j, m)cin>>a[i][j]; + build(n, m); + cout< 0) { + if (exp & 1) result = ((ll)result * base) % mod; + base = ((ll)base * base) % mod; + exp >>= 1; + } + return result; +} + +void ipgraph(int n, int m){ + int i, u, v; + while(m--){ + cin>>u>>v; + g[u-1].pb(v-1); + g[v-1].pb(u-1); + } +} + +void dfs(int u, int par){ +for(int v:g[u]){ + if (v == par) continue; + dfs(v, u); +} +}#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k pii; +typedef pair pll; +typedef vector vi; +typedef vector vl; +typedef vector vpii; +typedef vector vpll; +typedef vector vvi; +typedef vector vvl; +const int mod = 1000000007; + +//2d sparse table for max +//0 based index +//LGN = 1 + lg2(N) +//LGM = 1 + lg2(M) + +const int N = 1030; +const int M = 1030; +const int LGN = 11; +const int LGM = 11; +vi g[N]; +int a[N][M]; +int dp[N][LGN][M][LGM]; +const int MAXN = 2e6; //max(N, M) +int lg2[MAXN]; +void pre(){ + //build lg2 + lg2[1] = 0; + lg2[2] = 1; + int val = 1, at = 4; + int i; + Fo(i, 3, MAXN){ + if (i == at){ + at *= 2; + val++; + } + lg2[i] = val; + } +} +void build(int n, int m){ + pre(); + int ir, ic, jr, jc; + //unit cells + fo(ir, n) + fo(ic, m) dp[0][ir][0][ic] = a[ir][ic]; + + //fill 1-d sparse table for all rows + fo(ir, n) + Fo(jc, 1, LGM) + for(ic = 0; ic + (1<>n>>m; + fo(i,n)fo(j, m)cin>>a[i][j]; + build(n, m); + cout< Date: Wed, 25 Mar 2020 01:58:50 +0530 Subject: [PATCH 02/47] added persistent sement trees + ST on maps --- Library/DS/persistent_segment_tree.cpp | 50 ++++++++++++++++++++++++++ Library/DS/segment_tree_on_map.cpp | 40 +++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 Library/DS/persistent_segment_tree.cpp create mode 100644 Library/DS/segment_tree_on_map.cpp diff --git a/Library/DS/persistent_segment_tree.cpp b/Library/DS/persistent_segment_tree.cpp new file mode 100644 index 0000000..672dca2 --- /dev/null +++ b/Library/DS/persistent_segment_tree.cpp @@ -0,0 +1,50 @@ + +// query l to r range for the no of integers between x and y +#include +using namespace std; +int T = 1; +const int N = 1e6; +const int MX = N; +struct node{ + int l, r, cnt; +}t[100*MX]; +int root[N], a[N]; +int build(int lo, int hi){ + int id = T++; + if(lo == hi) return id; + int mid = (lo+hi)/2; + t[id].l = build(lo, mid); + t[id].r = build(mid+1, hi); + return id; +} +int update(int rt, int lo, int hi, int val){ + int id = T++; + t[id] = t[rt]; t[id].cnt++; + if(lo == hi) return id; + int mid = (lo+hi)/2; + if(val <= mid) t[id].l = update(t[rt].l, lo, mid, val); + else t[id].r = update(t[rt].r, mid+1, hi, val); + return id; +} +int query(int rt, int lo, int hi, int x, int y){ + if(x==lo and y==hi) return t[rt].cnt; + int mid = (lo+hi)/2; + if(y <= mid) return query(t[rt].l, lo, mid, x, y); + else if (x > mid) return query(t[rt].r, mid+1, hi, x, y); + return query(t[rt].l, lo, mid, x, mid) + query(t[rt].r, mid+1, hi, mid+1, y); +} +int main() { + int i, n, q; + cin >> n >> q; + for(i = 0; i < n; i++) cin >> a[i+1]; + root[0] = build(0, MX); + for(i = 1; i <= n; i++){ + root[i] = update(root[i-1], 0, MX, a[i]); + } + while(q--){ + int l, r, x, y; + cin >> l >> r >> x >> y; + cout << query(root[r], 0, MX, x, y) - query(root[l-1], 0, MX, x, y) << endl; + } + return 0; +} \ No newline at end of file diff --git a/Library/DS/segment_tree_on_map.cpp b/Library/DS/segment_tree_on_map.cpp new file mode 100644 index 0000000..d5db933 --- /dev/null +++ b/Library/DS/segment_tree_on_map.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; +const int N = 2e6; +map my[N]; +void update(int st, int lo, int hi, int pos, int val){ + my[st][val]++; + if(lo == hi){ + return; + } + int l = 2*st, r = l+1, mid = (lo+hi)/2; + if(pos>mid) update(r, mid+1, hi, pos, val); + else update(l, lo, mid, pos, val); +} +long long query(int st, int lo, int hi, int x, int y, int val){ + if(lo == x and hi == y){ + return my[st][val]; + } + int l = 2*st, r = l+1, mid = (lo+hi)/2; + if(x>mid) return query(r, mid+1, hi, x, y, val); + else if(y<=mid) return query(l, lo, mid, x, y, val); + return query(l ,lo , mid, x, mid, val) + query(r, mid+1, hi, mid+1, y, val); +} + +int main() { + int n, i, q, k, l, t, r; + cin >> n >> q; + while(q--){ + cin >> t >> l >> r; + if(t == 1){ + //add l to a[r] + update(1, 0, n-1, r-1, l); + } + else{ + //count of k from a[l] to a[r]. + cin >> k; + cout << query(1, 0, n-1, l-1, r-1, k) << endl; + } + } + return 0; +} \ No newline at end of file From b442ef2b01bfbfc4cc8fdaeace5681687b416870 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Wed, 1 Apr 2020 19:39:04 +0530 Subject: [PATCH 03/47] fixed my template.cpp --- Library/Miscellanious/template.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Library/Miscellanious/template.cpp b/Library/Miscellanious/template.cpp index 896e4bb..7a8caf2 100644 --- a/Library/Miscellanious/template.cpp +++ b/Library/Miscellanious/template.cpp @@ -1,4 +1,5 @@ -sing namespace std; +#include +using namespace std; #define gc getchar_unlocked #define fo(i,n) for(i=0;in;k Date: Sun, 5 Apr 2020 19:10:05 +0530 Subject: [PATCH 04/47] Google Codejam 2020 - Qualitifaction Round --- .../2020/QualificationRound/A-Vestigium.cpp | 109 +++++++++++ .../QualificationRound/B-NestingDepth.cpp | 91 +++++++++ .../C-ParentingActivities.cpp | 117 ++++++++++++ .../2020/QualificationRound/D-interactive.cpp | 176 ++++++++++++++++++ 4 files changed, 493 insertions(+) create mode 100644 MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/A-Vestigium.cpp create mode 100644 MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/B-NestingDepth.cpp create mode 100644 MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/C-ParentingActivities.cpp create mode 100644 MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/D-interactive.cpp diff --git a/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/A-Vestigium.cpp b/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/A-Vestigium.cpp new file mode 100644 index 0000000..2602a07 --- /dev/null +++ b/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/A-Vestigium.cpp @@ -0,0 +1,109 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k 0) { + if (exp & 1) result = ((ll)result * base) % mod; + base = ((ll)base * base) % mod; + exp >>= 1; + } + return result; +} + +void ipgraph(int n, int m){ + int i, u, v; + while(m--){ + cin>>u>>v; + g[u-1].pb(v-1); + g[v-1].pb(u-1); + } +} + +void dfs(int u, int par){ + for(int v:g[u]){ + if (v == par) continue; + dfs(v, u); + } +} + + diff --git a/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/B-NestingDepth.cpp b/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/B-NestingDepth.cpp new file mode 100644 index 0000000..6f9d77f --- /dev/null +++ b/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/B-NestingDepth.cpp @@ -0,0 +1,91 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k 0) { + if (exp & 1) result = ((ll)result * base) % mod; + base = ((ll)base * base) % mod; + exp >>= 1; + } + return result; +} + +void ipgraph(int n, int m){ + int i, u, v; + while(m--){ + cin>>u>>v; + g[u-1].pb(v-1); + g[v-1].pb(u-1); + } +} + +void dfs(int u, int par){ + for(int v:g[u]){ + if (v == par) continue; + dfs(v, u); + } +} + + diff --git a/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/C-ParentingActivities.cpp b/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/C-ParentingActivities.cpp new file mode 100644 index 0000000..dd6de7f --- /dev/null +++ b/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/C-ParentingActivities.cpp @@ -0,0 +1,117 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k 0) { + if (exp & 1) result = ((ll)result * base) % mod; + base = ((ll)base * base) % mod; + exp >>= 1; + } + return result; +} + +void ipgraph(int n, int m){ + int i, u, v; + while(m--){ + cin>>u>>v; + g[u-1].pb(v-1); + g[v-1].pb(u-1); + } +} + +void dfs(int u, int par){ + for(int v:g[u]){ + if (v == par) continue; + dfs(v, u); + } +} + + diff --git a/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/D-interactive.cpp b/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/D-interactive.cpp new file mode 100644 index 0000000..999ae51 --- /dev/null +++ b/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/D-interactive.cpp @@ -0,0 +1,176 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k> c; + if(c != 'Y') exit(0); + } + + return 0; +} + + + +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k> verdict; + assert(verdict == 'Y'); + } + + return 0; +} \ No newline at end of file From 75a9fd8ecaca3023a31347229a72f43f66717328 Mon Sep 17 00:00:00 2001 From: Learning Algorithms With Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Sun, 5 Apr 2020 19:28:47 +0530 Subject: [PATCH 05/47] updating solution to Codejam2020 - Problem D --- .../2020/QualificationRound/D-interactive.cpp | 82 +------------------ 1 file changed, 1 insertion(+), 81 deletions(-) diff --git a/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/D-interactive.cpp b/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/D-interactive.cpp index 999ae51..e98b2d5 100644 --- a/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/D-interactive.cpp +++ b/MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/D-interactive.cpp @@ -1,83 +1,3 @@ -#include -using namespace std; -#define gc getchar_unlocked -#define fo(i,n) for(i=0;in;k> c; - if(c != 'Y') exit(0); - } - - return 0; -} - - - #include using namespace std; #define gc getchar_unlocked @@ -173,4 +93,4 @@ int main() { } return 0; -} \ No newline at end of file +} From de068fa2b34970e939b0ca53233aaedeb1e8ac7c Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Sat, 25 Apr 2020 17:45:42 +0530 Subject: [PATCH 06/47] PE63 - analysis, logarithm, algebra, interview --- MyOnlineSubmissions/ProjectEuler/63.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 MyOnlineSubmissions/ProjectEuler/63.py diff --git a/MyOnlineSubmissions/ProjectEuler/63.py b/MyOnlineSubmissions/ProjectEuler/63.py new file mode 100644 index 0000000..afa1944 --- /dev/null +++ b/MyOnlineSubmissions/ProjectEuler/63.py @@ -0,0 +1,19 @@ +# The 5-digit number, 16807=7^5, is also a fifth power. +# Similarly, the 9-digit number, 134217728=8^9, is a ninth power. +# How many n-digit positive integers exist which are also an nth power? + +def digits(x): + ans = 0 + while x > 0: + x //= 10 + ans += 1 + return ans + +ans = 1 # 1^1 = 1 +for k in range(2, 11): + for p in range(1, 22): + # check if k^p has p digits + if digits(pow(k, p)) == p: + ans += 1 + print(f'{k}^{p} = {pow(k, p)} has {p} digits.') +print(ans) From 7681e3dc5cbb24dd759ac0007d22185474f4d009 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Sat, 25 Apr 2020 17:46:14 +0530 Subject: [PATCH 07/47] PE81: DP, easy min path in matrix --- MyOnlineSubmissions/ProjectEuler/81.py | 98 ++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 MyOnlineSubmissions/ProjectEuler/81.py diff --git a/MyOnlineSubmissions/ProjectEuler/81.py b/MyOnlineSubmissions/ProjectEuler/81.py new file mode 100644 index 0000000..c113037 --- /dev/null +++ b/MyOnlineSubmissions/ProjectEuler/81.py @@ -0,0 +1,98 @@ +mat = [[4445,2697,5115,718,2209,2212,654,4348,3079,6821,7668,3276,8874,4190,3785,2752,9473,7817,9137,496,7338,3434,7152,4355,4552,7917,7827,2460,2350,691,3514,5880,3145,7633,7199,3783,5066,7487,3285,1084,8985,760,872,8609,8051,1134,9536,5750,9716,9371,7619,5617,275,9721,2997,2698,1887,8825,6372,3014,2113,7122,7050,6775,5948,2758,1219,3539,348,7989,2735,9862,1263,8089,6401,9462,3168,2758,3748,5870], +[1096,20,1318,7586,5167,2642,1443,5741,7621,7030,5526,4244,2348,4641,9827,2448,6918,5883,3737,300,7116,6531,567,5997,3971,6623,820,6148,3287,1874,7981,8424,7672,7575,6797,6717,1078,5008,4051,8795,5820,346,1851,6463,2117,6058,3407,8211,117,4822,1317,4377,4434,5925,8341,4800,1175,4173,690,8978,7470,1295,3799,8724,3509,9849,618,3320,7068,9633,2384,7175,544,6583,1908,9983,481,4187,9353,9377], +[9607,7385,521,6084,1364,8983,7623,1585,6935,8551,2574,8267,4781,3834,2764,2084,2669,4656,9343,7709,2203,9328,8004,6192,5856,3555,2260,5118,6504,1839,9227,1259,9451,1388,7909,5733,6968,8519,9973,1663,5315,7571,3035,4325,4283,2304,6438,3815,9213,9806,9536,196,5542,6907,2475,1159,5820,9075,9470,2179,9248,1828,4592,9167,3713,4640,47,3637,309,7344,6955,346,378,9044,8635,7466,5036,9515,6385,9230], +[7206,3114,7760,1094,6150,5182,7358,7387,4497,955,101,1478,7777,6966,7010,8417,6453,4955,3496,107,449,8271,131,2948,6185,784,5937,8001,6104,8282,4165,3642,710,2390,575,715,3089,6964,4217,192,5949,7006,715,3328,1152,66,8044,4319,1735,146,4818,5456,6451,4113,1063,4781,6799,602,1504,6245,6550,1417,1343,2363,3785,5448,4545,9371,5420,5068,4613,4882,4241,5043,7873,8042,8434,3939,9256,2187], +[3620,8024,577,9997,7377,7682,1314,1158,6282,6310,1896,2509,5436,1732,9480,706,496,101,6232,7375,2207,2306,110,6772,3433,2878,8140,5933,8688,1399,2210,7332,6172,6403,7333,4044,2291,1790,2446,7390,8698,5723,3678,7104,1825,2040,140,3982,4905,4160,2200,5041,2512,1488,2268,1175,7588,8321,8078,7312,977,5257,8465,5068,3453,3096,1651,7906,253,9250,6021,8791,8109,6651,3412,345,4778,5152,4883,7505], +[1074,5438,9008,2679,5397,5429,2652,3403,770,9188,4248,2493,4361,8327,9587,707,9525,5913,93,1899,328,2876,3604,673,8576,6908,7659,2544,3359,3883,5273,6587,3065,1749,3223,604,9925,6941,2823,8767,7039,3290,3214,1787,7904,3421,7137,9560,8451,2669,9219,6332,1576,5477,6755,8348,4164,4307,2984,4012,6629,1044,2874,6541,4942,903,1404,9125,5160,8836,4345,2581,460,8438,1538,5507,668,3352,2678,6942], +[4295,1176,5596,1521,3061,9868,7037,7129,8933,6659,5947,5063,3653,9447,9245,2679,767,714,116,8558,163,3927,8779,158,5093,2447,5782,3967,1716,931,7772,8164,1117,9244,5783,7776,3846,8862,6014,2330,6947,1777,3112,6008,3491,1906,5952,314,4602,8994,5919,9214,3995,5026,7688,6809,5003,3128,2509,7477,110,8971,3982,8539,2980,4689,6343,5411,2992,5270,5247,9260,2269,7474,1042,7162,5206,1232,4556,4757], +[510,3556,5377,1406,5721,4946,2635,7847,4251,8293,8281,6351,4912,287,2870,3380,3948,5322,3840,4738,9563,1906,6298,3234,8959,1562,6297,8835,7861,239,6618,1322,2553,2213,5053,5446,4402,6500,5182,8585,6900,5756,9661,903,5186,7687,5998,7997,8081,8955,4835,6069,2621,1581,732,9564,1082,1853,5442,1342,520,1737,3703,5321,4793,2776,1508,1647,9101,2499,6891,4336,7012,3329,3212,1442,9993,3988,4930,7706], +[9444,3401,5891,9716,1228,7107,109,3563,2700,6161,5039,4992,2242,8541,7372,2067,1294,3058,1306,320,8881,5756,9326,411,8650,8824,5495,8282,8397,2000,1228,7817,2099,6473,3571,5994,4447,1299,5991,543,7874,2297,1651,101,2093,3463,9189,6872,6118,872,1008,1779,2805,9084,4048,2123,5877,55,3075,1737,9459,4535,6453,3644,108,5982,4437,5213,1340,6967,9943,5815,669,8074,1838,6979,9132,9315,715,5048], +[3327,4030,7177,6336,9933,5296,2621,4785,2755,4832,2512,2118,2244,4407,2170,499,7532,9742,5051,7687,970,6924,3527,4694,5145,1306,2165,5940,2425,8910,3513,1909,6983,346,6377,4304,9330,7203,6605,3709,3346,970,369,9737,5811,4427,9939,3693,8436,5566,1977,3728,2399,3985,8303,2492,5366,9802,9193,7296,1033,5060,9144,2766,1151,7629,5169,5995,58,7619,7565,4208,1713,6279,3209,4908,9224,7409,1325,8540], +[6882,1265,1775,3648,4690,959,5837,4520,5394,1378,9485,1360,4018,578,9174,2932,9890,3696,116,1723,1178,9355,7063,1594,1918,8574,7594,7942,1547,6166,7888,354,6932,4651,1010,7759,6905,661,7689,6092,9292,3845,9605,8443,443,8275,5163,7720,7265,6356,7779,1798,1754,5225,6661,1180,8024,5666,88,9153,1840,3508,1193,4445,2648,3538,6243,6375,8107,5902,5423,2520,1122,5015,6113,8859,9370,966,8673,2442], +[7338,3423,4723,6533,848,8041,7921,8277,4094,5368,7252,8852,9166,2250,2801,6125,8093,5738,4038,9808,7359,9494,601,9116,4946,2702,5573,2921,9862,1462,1269,2410,4171,2709,7508,6241,7522,615,2407,8200,4189,5492,5649,7353,2590,5203,4274,710,7329,9063,956,8371,3722,4253,4785,1194,4828,4717,4548,940,983,2575,4511,2938,1827,2027,2700,1236,841,5760,1680,6260,2373,3851,1841,4968,1172,5179,7175,3509], +[4420,1327,3560,2376,6260,2988,9537,4064,4829,8872,9598,3228,1792,7118,9962,9336,4368,9189,6857,1829,9863,6287,7303,7769,2707,8257,2391,2009,3975,4993,3068,9835,3427,341,8412,2134,4034,8511,6421,3041,9012,2983,7289,100,1355,7904,9186,6920,5856,2008,6545,8331,3655,5011,839,8041,9255,6524,3862,8788,62,7455,3513,5003,8413,3918,2076,7960,6108,3638,6999,3436,1441,4858,4181,1866,8731,7745,3744,1000], +[356,8296,8325,1058,1277,4743,3850,2388,6079,6462,2815,5620,8495,5378,75,4324,3441,9870,1113,165,1544,1179,2834,562,6176,2313,6836,8839,2986,9454,5199,6888,1927,5866,8760,320,1792,8296,7898,6121,7241,5886,5814,2815,8336,1576,4314,3109,2572,6011,2086,9061,9403,3947,5487,9731,7281,3159,1819,1334,3181,5844,5114,9898,4634,2531,4412,6430,4262,8482,4546,4555,6804,2607,9421,686,8649,8860,7794,6672], +[9870,152,1558,4963,8750,4754,6521,6256,8818,5208,5691,9659,8377,9725,5050,5343,2539,6101,1844,9700,7750,8114,5357,3001,8830,4438,199,9545,8496,43,2078,327,9397,106,6090,8181,8646,6414,7499,5450,4850,6273,5014,4131,7639,3913,6571,8534,9703,4391,7618,445,1320,5,1894,6771,7383,9191,4708,9706,6939,7937,8726,9382,5216,3685,2247,9029,8154,1738,9984,2626,9438,4167,6351,5060,29,1218,1239,4785], +[192,5213,8297,8974,4032,6966,5717,1179,6523,4679,9513,1481,3041,5355,9303,9154,1389,8702,6589,7818,6336,3539,5538,3094,6646,6702,6266,2759,4608,4452,617,9406,8064,6379,444,5602,4950,1810,8391,1536,316,8714,1178,5182,5863,5110,5372,4954,1978,2971,5680,4863,2255,4630,5723,2168,538,1692,1319,7540,440,6430,6266,7712,7385,5702,620,641,3136,7350,1478,3155,2820,9109,6261,1122,4470,14,8493,2095], +[1046,4301,6082,474,4974,7822,2102,5161,5172,6946,8074,9716,6586,9962,9749,5015,2217,995,5388,4402,7652,6399,6539,1349,8101,3677,1328,9612,7922,2879,231,5887,2655,508,4357,4964,3554,5930,6236,7384,4614,280,3093,9600,2110,7863,2631,6626,6620,68,1311,7198,7561,1768,5139,1431,221,230,2940,968,5283,6517,2146,1646,869,9402,7068,8645,7058,1765,9690,4152,2926,9504,2939,7504,6074,2944,6470,7859], +[4659,736,4951,9344,1927,6271,8837,8711,3241,6579,7660,5499,5616,3743,5801,4682,9748,8796,779,1833,4549,8138,4026,775,4170,2432,4174,3741,7540,8017,2833,4027,396,811,2871,1150,9809,2719,9199,8504,1224,540,2051,3519,7982,7367,2761,308,3358,6505,2050,4836,5090,7864,805,2566,2409,6876,3361,8622,5572,5895,3280,441,7893,8105,1634,2929,274,3926,7786,6123,8233,9921,2674,5340,1445,203,4585,3837], +[5759,338,7444,7968,7742,3755,1591,4839,1705,650,7061,2461,9230,9391,9373,2413,1213,431,7801,4994,2380,2703,6161,6878,8331,2538,6093,1275,5065,5062,2839,582,1014,8109,3525,1544,1569,8622,7944,2905,6120,1564,1839,5570,7579,1318,2677,5257,4418,5601,7935,7656,5192,1864,5886,6083,5580,6202,8869,1636,7907,4759,9082,5854,3185,7631,6854,5872,5632,5280,1431,2077,9717,7431,4256,8261,9680,4487,4752,4286], +[1571,1428,8599,1230,7772,4221,8523,9049,4042,8726,7567,6736,9033,2104,4879,4967,6334,6716,3994,1269,8995,6539,3610,7667,6560,6065,874,848,4597,1711,7161,4811,6734,5723,6356,6026,9183,2586,5636,1092,7779,7923,8747,6887,7505,9909,1792,3233,4526,3176,1508,8043,720,5212,6046,4988,709,5277,8256,3642,1391,5803,1468,2145,3970,6301,7767,2359,8487,9771,8785,7520,856,1605,8972,2402,2386,991,1383,5963], +[1822,4824,5957,6511,9868,4113,301,9353,6228,2881,2966,6956,9124,9574,9233,1601,7340,973,9396,540,4747,8590,9535,3650,7333,7583,4806,3593,2738,8157,5215,8472,2284,9473,3906,6982,5505,6053,7936,6074,7179,6688,1564,1103,6860,5839,2022,8490,910,7551,7805,881,7024,1855,9448,4790,1274,3672,2810,774,7623,4223,4850,6071,9975,4935,1915,9771,6690,3846,517,463,7624,4511,614,6394,3661,7409,1395,8127], +[8738,3850,9555,3695,4383,2378,87,6256,6740,7682,9546,4255,6105,2000,1851,4073,8957,9022,6547,5189,2487,303,9602,7833,1628,4163,6678,3144,8589,7096,8913,5823,4890,7679,1212,9294,5884,2972,3012,3359,7794,7428,1579,4350,7246,4301,7779,7790,3294,9547,4367,3549,1958,8237,6758,3497,3250,3456,6318,1663,708,7714,6143,6890,3428,6853,9334,7992,591,6449,9786,1412,8500,722,5468,1371,108,3939,4199,2535], +[7047,4323,1934,5163,4166,461,3544,2767,6554,203,6098,2265,9078,2075,4644,6641,8412,9183,487,101,7566,5622,1975,5726,2920,5374,7779,5631,3753,3725,2672,3621,4280,1162,5812,345,8173,9785,1525,955,5603,2215,2580,5261,2765,2990,5979,389,3907,2484,1232,5933,5871,3304,1138,1616,5114,9199,5072,7442,7245,6472,4760,6359,9053,7876,2564,9404,3043,9026,2261,3374,4460,7306,2326,966,828,3274,1712,3446], +[3975,4565,8131,5800,4570,2306,8838,4392,9147,11,3911,7118,9645,4994,2028,6062,5431,2279,8752,2658,7836,994,7316,5336,7185,3289,1898,9689,2331,5737,3403,1124,2679,3241,7748,16,2724,5441,6640,9368,9081,5618,858,4969,17,2103,6035,8043,7475,2181,939,415,1617,8500,8253,2155,7843,7974,7859,1746,6336,3193,2617,8736,4079,6324,6645,8891,9396,5522,6103,1857,8979,3835,2475,1310,7422,610,8345,7615], +[9248,5397,5686,2988,3446,4359,6634,9141,497,9176,6773,7448,1907,8454,916,1596,2241,1626,1384,2741,3649,5362,8791,7170,2903,2475,5325,6451,924,3328,522,90,4813,9737,9557,691,2388,1383,4021,1609,9206,4707,5200,7107,8104,4333,9860,5013,1224,6959,8527,1877,4545,7772,6268,621,4915,9349,5970,706,9583,3071,4127,780,8231,3017,9114,3836,7503,2383,1977,4870,8035,2379,9704,1037,3992,3642,1016,4303], +[5093,138,4639,6609,1146,5565,95,7521,9077,2272,974,4388,2465,2650,722,4998,3567,3047,921,2736,7855,173,2065,4238,1048,5,6847,9548,8632,9194,5942,4777,7910,8971,6279,7253,2516,1555,1833,3184,9453,9053,6897,7808,8629,4877,1871,8055,4881,7639,1537,7701,2508,7564,5845,5023,2304,5396,3193,2955,1088,3801,6203,1748,3737,1276,13,4120,7715,8552,3047,2921,106,7508,304,1280,7140,2567,9135,5266], +[6237,4607,7527,9047,522,7371,4883,2540,5867,6366,5301,1570,421,276,3361,527,6637,4861,2401,7522,5808,9371,5298,2045,5096,5447,7755,5115,7060,8529,4078,1943,1697,1764,5453,7085,960,2405,739,2100,5800,728,9737,5704,5693,1431,8979,6428,673,7540,6,7773,5857,6823,150,5869,8486,684,5816,9626,7451,5579,8260,3397,5322,6920,1879,2127,2884,5478,4977,9016,6165,6292,3062,5671,5968,78,4619,4763], +[9905,7127,9390,5185,6923,3721,9164,9705,4341,1031,1046,5127,7376,6528,3248,4941,1178,7889,3364,4486,5358,9402,9158,8600,1025,874,1839,1783,309,9030,1843,845,8398,1433,7118,70,8071,2877,3904,8866,6722,4299,10,1929,5897,4188,600,1889,3325,2485,6473,4474,7444,6992,4846,6166,4441,2283,2629,4352,7775,1101,2214,9985,215,8270,9750,2740,8361,7103,5930,8664,9690,8302,9267,344,2077,1372,1880,9550], +[5825,8517,7769,2405,8204,1060,3603,7025,478,8334,1997,3692,7433,9101,7294,7498,9415,5452,3850,3508,6857,9213,6807,4412,7310,854,5384,686,4978,892,8651,3241,2743,3801,3813,8588,6701,4416,6990,6490,3197,6838,6503,114,8343,5844,8646,8694,65,791,5979,2687,2621,2019,8097,1423,3644,9764,4921,3266,3662,5561,2476,8271,8138,6147,1168,3340,1998,9874,6572,9873,6659,5609,2711,3931,9567,4143,7833,8887], +[6223,2099,2700,589,4716,8333,1362,5007,2753,2848,4441,8397,7192,8191,4916,9955,6076,3370,6396,6971,3156,248,3911,2488,4930,2458,7183,5455,170,6809,6417,3390,1956,7188,577,7526,2203,968,8164,479,8699,7915,507,6393,4632,1597,7534,3604,618,3280,6061,9793,9238,8347,568,9645,2070,5198,6482,5000,9212,6655,5961,7513,1323,3872,6170,3812,4146,2736,67,3151,5548,2781,9679,7564,5043,8587,1893,4531], +[5826,3690,6724,2121,9308,6986,8106,6659,2142,1642,7170,2877,5757,6494,8026,6571,8387,9961,6043,9758,9607,6450,8631,8334,7359,5256,8523,2225,7487,1977,9555,8048,5763,2414,4948,4265,2427,8978,8088,8841,9208,9601,5810,9398,8866,9138,4176,5875,7212,3272,6759,5678,7649,4922,5422,1343,8197,3154,3600,687,1028,4579,2084,9467,4492,7262,7296,6538,7657,7134,2077,1505,7332,6890,8964,4879,7603,7400,5973,739], +[1861,1613,4879,1884,7334,966,2000,7489,2123,4287,1472,3263,4726,9203,1040,4103,6075,6049,330,9253,4062,4268,1635,9960,577,1320,3195,9628,1030,4092,4979,6474,6393,2799,6967,8687,7724,7392,9927,2085,3200,6466,8702,265,7646,8665,7986,7266,4574,6587,612,2724,704,3191,8323,9523,3002,704,5064,3960,8209,2027,2758,8393,4875,4641,9584,6401,7883,7014,768,443,5490,7506,1852,2005,8850,5776,4487,4269], +[4052,6687,4705,7260,6645,6715,3706,5504,8672,2853,1136,8187,8203,4016,871,1809,1366,4952,9294,5339,6872,2645,6083,7874,3056,5218,7485,8796,7401,3348,2103,426,8572,4163,9171,3176,948,7654,9344,3217,1650,5580,7971,2622,76,2874,880,2034,9929,1546,2659,5811,3754,7096,7436,9694,9960,7415,2164,953,2360,4194,2397,1047,2196,6827,575,784,2675,8821,6802,7972,5996,6699,2134,7577,2887,1412,4349,4380], +[4629,2234,6240,8132,7592,3181,6389,1214,266,1910,2451,8784,2790,1127,6932,1447,8986,2492,5476,397,889,3027,7641,5083,5776,4022,185,3364,5701,2442,2840,4160,9525,4828,6602,2614,7447,3711,4505,7745,8034,6514,4907,2605,7753,6958,7270,6936,3006,8968,439,2326,4652,3085,3425,9863,5049,5361,8688,297,7580,8777,7916,6687,8683,7141,306,9569,2384,1500,3346,4601,7329,9040,6097,2727,6314,4501,4974,2829], +[8316,4072,2025,6884,3027,1808,5714,7624,7880,8528,4205,8686,7587,3230,1139,7273,6163,6986,3914,9309,1464,9359,4474,7095,2212,7302,2583,9462,7532,6567,1606,4436,8981,5612,6796,4385,5076,2007,6072,3678,8331,1338,3299,8845,4783,8613,4071,1232,6028,2176,3990,2148,3748,103,9453,538,6745,9110,926,3125,473,5970,8728,7072,9062,1404,1317,5139,9862,6496,6062,3338,464,1600,2532,1088,8232,7739,8274,3873], +[2341,523,7096,8397,8301,6541,9844,244,4993,2280,7689,4025,4196,5522,7904,6048,2623,9258,2149,9461,6448,8087,7245,1917,8340,7127,8466,5725,6996,3421,5313,512,9164,9837,9794,8369,4185,1488,7210,1524,1016,4620,9435,2478,7765,8035,697,6677,3724,6988,5853,7662,3895,9593,1185,4727,6025,5734,7665,3070,138,8469,6748,6459,561,7935,8646,2378,462,7755,3115,9690,8877,3946,2728,8793,244,6323,8666,4271], +[6430,2406,8994,56,1267,3826,9443,7079,7579,5232,6691,3435,6718,5698,4144,7028,592,2627,217,734,6194,8156,9118,58,2640,8069,4127,3285,694,3197,3377,4143,4802,3324,8134,6953,7625,3598,3584,4289,7065,3434,2106,7132,5802,7920,9060,7531,3321,1725,1067,3751,444,5503,6785,7937,6365,4803,198,6266,8177,1470,6390,1606,2904,7555,9834,8667,2033,1723,5167,1666,8546,8152,473,4475,6451,7947,3062,3281], +[2810,3042,7759,1741,2275,2609,7676,8640,4117,1958,7500,8048,1757,3954,9270,1971,4796,2912,660,5511,3553,1012,5757,4525,6084,7198,8352,5775,7726,8591,7710,9589,3122,4392,6856,5016,749,2285,3356,7482,9956,7348,2599,8944,495,3462,3578,551,4543,7207,7169,7796,1247,4278,6916,8176,3742,8385,2310,1345,8692,2667,4568,1770,8319,3585,4920,3890,4928,7343,5385,9772,7947,8786,2056,9266,3454,2807,877,2660], +[6206,8252,5928,5837,4177,4333,207,7934,5581,9526,8906,1498,8411,2984,5198,5134,2464,8435,8514,8674,3876,599,5327,826,2152,4084,2433,9327,9697,4800,2728,3608,3849,3861,3498,9943,1407,3991,7191,9110,5666,8434,4704,6545,5944,2357,1163,4995,9619,6754,4200,9682,6654,4862,4744,5953,6632,1054,293,9439,8286,2255,696,8709,1533,1844,6441,430,1999,6063,9431,7018,8057,2920,6266,6799,356,3597,4024,6665], +[3847,6356,8541,7225,2325,2946,5199,469,5450,7508,2197,9915,8284,7983,6341,3276,3321,16,1321,7608,5015,3362,8491,6968,6818,797,156,2575,706,9516,5344,5457,9210,5051,8099,1617,9951,7663,8253,9683,2670,1261,4710,1068,8753,4799,1228,2621,3275,6188,4699,1791,9518,8701,5932,4275,6011,9877,2933,4182,6059,2930,6687,6682,9771,654,9437,3169,8596,1827,5471,8909,2352,123,4394,3208,8756,5513,6917,2056], +[5458,8173,3138,3290,4570,4892,3317,4251,9699,7973,1163,1935,5477,6648,9614,5655,9592,975,9118,2194,7322,8248,8413,3462,8560,1907,7810,6650,7355,2939,4973,6894,3933,3784,3200,2419,9234,4747,2208,2207,1945,2899,1407,6145,8023,3484,5688,7686,2737,3828,3704,9004,5190,9740,8643,8650,5358,4426,1522,1707,3613,9887,6956,2447,2762,833,1449,9489,2573,1080,4167,3456,6809,2466,227,7125,2759,6250,6472,8089], +[3266,7025,9756,3914,1265,9116,7723,9788,6805,5493,2092,8688,6592,9173,4431,4028,6007,7131,4446,4815,3648,6701,759,3312,8355,4485,4187,5188,8746,7759,3528,2177,5243,8379,3838,7233,4607,9187,7216,2190,6967,2920,6082,7910,5354,3609,8958,6949,7731,494,8753,8707,1523,4426,3543,7085,647,6771,9847,646,5049,824,8417,5260,2730,5702,2513,9275,4279,2767,8684,1165,9903,4518,55,9682,8963,6005,2102,6523], +[1998,8731,936,1479,5259,7064,4085,91,7745,7136,3773,3810,730,8255,2705,2653,9790,6807,2342,355,9344,2668,3690,2028,9679,8102,574,4318,6481,9175,5423,8062,2867,9657,7553,3442,3920,7430,3945,7639,3714,3392,2525,4995,4850,2867,7951,9667,486,9506,9888,781,8866,1702,3795,90,356,1483,4200,2131,6969,5931,486,6880,4404,1084,5169,4910,6567,8335,4686,5043,2614,3352,2667,4513,6472,7471,5720,1616], +[8878,1613,1716,868,1906,2681,564,665,5995,2474,7496,3432,9491,9087,8850,8287,669,823,347,6194,2264,2592,7871,7616,8508,4827,760,2676,4660,4881,7572,3811,9032,939,4384,929,7525,8419,5556,9063,662,8887,7026,8534,3111,1454,2082,7598,5726,6687,9647,7608,73,3014,5063,670,5461,5631,3367,9796,8475,7908,5073,1565,5008,5295,4457,1274,4788,1728,338,600,8415,8535,9351,7750,6887,5845,1741,125], +[3637,6489,9634,9464,9055,2413,7824,9517,7532,3577,7050,6186,6980,9365,9782,191,870,2497,8498,2218,2757,5420,6468,586,3320,9230,1034,1393,9886,5072,9391,1178,8464,8042,6869,2075,8275,3601,7715,9470,8786,6475,8373,2159,9237,2066,3264,5000,679,355,3069,4073,494,2308,5512,4334,9438,8786,8637,9774,1169,1949,6594,6072,4270,9158,7916,5752,6794,9391,6301,5842,3285,2141,3898,8027,4310,8821,7079,1307], +[8497,6681,4732,7151,7060,5204,9030,7157,833,5014,8723,3207,9796,9286,4913,119,5118,7650,9335,809,3675,2597,5144,3945,5090,8384,187,4102,1260,2445,2792,4422,8389,9290,50,1765,1521,6921,8586,4368,1565,5727,7855,2003,4834,9897,5911,8630,5070,1330,7692,7557,7980,6028,5805,9090,8265,3019,3802,698,9149,5748,1965,9658,4417,5994,5584,8226,2937,272,5743,1278,5698,8736,2595,6475,5342,6596,1149,6920], +[8188,8009,9546,6310,8772,2500,9846,6592,6872,3857,1307,8125,7042,1544,6159,2330,643,4604,7899,6848,371,8067,2062,3200,7295,1857,9505,6936,384,2193,2190,301,8535,5503,1462,7380,5114,4824,8833,1763,4974,8711,9262,6698,3999,2645,6937,7747,1128,2933,3556,7943,2885,3122,9105,5447,418,2899,5148,3699,9021,9501,597,4084,175,1621,1,1079,6067,5812,4326,9914,6633,5394,4233,6728,9084,1864,5863,1225], +[9935,8793,9117,1825,9542,8246,8437,3331,9128,9675,6086,7075,319,1334,7932,3583,7167,4178,1726,7720,695,8277,7887,6359,5912,1719,2780,8529,1359,2013,4498,8072,1129,9998,1147,8804,9405,6255,1619,2165,7491,1,8882,7378,3337,503,5758,4109,3577,985,3200,7615,8058,5032,1080,6410,6873,5496,1466,2412,9885,5904,4406,3605,8770,4361,6205,9193,1537,9959,214,7260,9566,1685,100,4920,7138,9819,5637,976], +[3466,9854,985,1078,7222,8888,5466,5379,3578,4540,6853,8690,3728,6351,7147,3134,6921,9692,857,3307,4998,2172,5783,3931,9417,2541,6299,13,787,2099,9131,9494,896,8600,1643,8419,7248,2660,2609,8579,91,6663,5506,7675,1947,6165,4286,1972,9645,3805,1663,1456,8853,5705,9889,7489,1107,383,4044,2969,3343,152,7805,4980,9929,5033,1737,9953,7197,9158,4071,1324,473,9676,3984,9680,3606,8160,7384,5432], +[1005,4512,5186,3953,2164,3372,4097,3247,8697,3022,9896,4101,3871,6791,3219,2742,4630,6967,7829,5991,6134,1197,1414,8923,8787,1394,8852,5019,7768,5147,8004,8825,5062,9625,7988,1110,3992,7984,9966,6516,6251,8270,421,3723,1432,4830,6935,8095,9059,2214,6483,6846,3120,1587,6201,6691,9096,9627,6671,4002,3495,9939,7708,7465,5879,6959,6634,3241,3401,2355,9061,2611,7830,3941,2177,2146,5089,7079,519,6351], +[7280,8586,4261,2831,7217,3141,9994,9940,5462,2189,4005,6942,9848,5350,8060,6665,7519,4324,7684,657,9453,9296,2944,6843,7499,7847,1728,9681,3906,6353,5529,2822,3355,3897,7724,4257,7489,8672,4356,3983,1948,6892,7415,4153,5893,4190,621,1736,4045,9532,7701,3671,1211,1622,3176,4524,9317,7800,5638,6644,6943,5463,3531,2821,1347,5958,3436,1438,2999,994,850,4131,2616,1549,3465,5946,690,9273,6954,7991], +[9517,399,3249,2596,7736,2142,1322,968,7350,1614,468,3346,3265,7222,6086,1661,5317,2582,7959,4685,2807,2917,1037,5698,1529,3972,8716,2634,3301,3412,8621,743,8001,4734,888,7744,8092,3671,8941,1487,5658,7099,2781,99,1932,4443,4756,4652,9328,1581,7855,4312,5976,7255,6480,3996,2748,1973,9731,4530,2790,9417,7186,5303,3557,351,7182,9428,1342,9020,7599,1392,8304,2070,9138,7215,2008,9937,1106,7110], +[7444,769,9688,632,1571,6820,8743,4338,337,3366,3073,1946,8219,104,4210,6986,249,5061,8693,7960,6546,1004,8857,5997,9352,4338,6105,5008,2556,6518,6694,4345,3727,7956,20,3954,8652,4424,9387,2035,8358,5962,5304,5194,8650,8282,1256,1103,2138,6679,1985,3653,2770,2433,4278,615,2863,1715,242,3790,2636,6998,3088,1671,2239,957,5411,4595,6282,2881,9974,2401,875,7574,2987,4587,3147,6766,9885,2965], +[3287,3016,3619,6818,9073,6120,5423,557,2900,2015,8111,3873,1314,4189,1846,4399,7041,7583,2427,2864,3525,5002,2069,748,1948,6015,2684,438,770,8367,1663,7887,7759,1885,157,7770,4520,4878,3857,1137,3525,3050,6276,5569,7649,904,4533,7843,2199,5648,7628,9075,9441,3600,7231,2388,5640,9096,958,3058,584,5899,8150,1181,9616,1098,8162,6819,8171,1519,1140,7665,8801,2632,1299,9192,707,9955,2710,7314], +[1772,2963,7578,3541,3095,1488,7026,2634,6015,4633,4370,2762,1650,2174,909,8158,2922,8467,4198,4280,9092,8856,8835,5457,2790,8574,9742,5054,9547,4156,7940,8126,9824,7340,8840,6574,3547,1477,3014,6798,7134,435,9484,9859,3031,4,1502,4133,1738,1807,4825,463,6343,9701,8506,9822,9555,8688,8168,3467,3234,6318,1787,5591,419,6593,7974,8486,9861,6381,6758,194,3061,4315,2863,4665,3789,2201,1492,4416], +[126,8927,6608,5682,8986,6867,1715,6076,3159,788,3140,4744,830,9253,5812,5021,7616,8534,1546,9590,1101,9012,9821,8132,7857,4086,1069,7491,2988,1579,2442,4321,2149,7642,6108,250,6086,3167,24,9528,7663,2685,1220,9196,1397,5776,1577,1730,5481,977,6115,199,6326,2183,3767,5928,5586,7561,663,8649,9688,949,5913,9160,1870,5764,9887,4477,6703,1413,4995,5494,7131,2192,8969,7138,3997,8697,646,1028], +[8074,1731,8245,624,4601,8706,155,8891,309,2552,8208,8452,2954,3124,3469,4246,3352,1105,4509,8677,9901,4416,8191,9283,5625,7120,2952,8881,7693,830,4580,8228,9459,8611,4499,1179,4988,1394,550,2336,6089,6872,269,7213,1848,917,6672,4890,656,1478,6536,3165,4743,4990,1176,6211,7207,5284,9730,4738,1549,4986,4942,8645,3698,9429,1439,2175,6549,3058,6513,1574,6988,8333,3406,5245,5431,7140,7085,6407], +[7845,4694,2530,8249,290,5948,5509,1588,5940,4495,5866,5021,4626,3979,3296,7589,4854,1998,5627,3926,8346,6512,9608,1918,7070,4747,4182,2858,2766,4606,6269,4107,8982,8568,9053,4244,5604,102,2756,727,5887,2566,7922,44,5986,621,1202,374,6988,4130,3627,6744,9443,4568,1398,8679,397,3928,9159,367,2917,6127,5788,3304,8129,911,2669,1463,9749,264,4478,8940,1109,7309,2462,117,4692,7724,225,2312], +[4164,3637,2000,941,8903,39,3443,7172,1031,3687,4901,8082,4945,4515,7204,9310,9349,9535,9940,218,1788,9245,2237,1541,5670,6538,6047,5553,9807,8101,1925,8714,445,8332,7309,6830,5786,5736,7306,2710,3034,1838,7969,6318,7912,2584,2080,7437,6705,2254,7428,820,782,9861,7596,3842,3631,8063,5240,6666,394,4565,7865,4895,9890,6028,6117,4724,9156,4473,4552,602,470,6191,4927,5387,884,3146,1978,3000], +[4258,6880,1696,3582,5793,4923,2119,1155,9056,9698,6603,3768,5514,9927,9609,6166,6566,4536,4985,4934,8076,9062,6741,6163,7399,4562,2337,5600,2919,9012,8459,1308,6072,1225,9306,8818,5886,7243,7365,8792,6007,9256,6699,7171,4230,7002,8720,7839,4533,1671,478,7774,1607,2317,5437,4705,7886,4760,6760,7271,3081,2997,3088,7675,6208,3101,6821,6840,122,9633,4900,2067,8546,4549,2091,7188,5605,8599,6758,5229], +[7854,5243,9155,3556,8812,7047,2202,1541,5993,4600,4760,713,434,7911,7426,7414,8729,322,803,7960,7563,4908,6285,6291,736,3389,9339,4132,8701,7534,5287,3646,592,3065,7582,2592,8755,6068,8597,1982,5782,1894,2900,6236,4039,6569,3037,5837,7698,700,7815,2491,7272,5878,3083,6778,6639,3589,5010,8313,2581,6617,5869,8402,6808,2951,2321,5195,497,2190,6187,1342,1316,4453,7740,4154,2959,1781,1482,8256], +[7178,2046,4419,744,8312,5356,6855,8839,319,2962,5662,47,6307,8662,68,4813,567,2712,9931,1678,3101,8227,6533,4933,6656,92,5846,4780,6256,6361,4323,9985,1231,2175,7178,3034,9744,6155,9165,7787,5836,9318,7860,9644,8941,6480,9443,8188,5928,161,6979,2352,5628,6991,1198,8067,5867,6620,3778,8426,2994,3122,3124,6335,3918,8897,2655,9670,634,1088,1576,8935,7255,474,8166,7417,9547,2886,5560,3842], +[6957,3111,26,7530,7143,1295,1744,6057,3009,1854,8098,5405,2234,4874,9447,2620,9303,27,7410,969,40,2966,5648,7596,8637,4238,3143,3679,7187,690,9980,7085,7714,9373,5632,7526,6707,3951,9734,4216,2146,3602,5371,6029,3039,4433,4855,4151,1449,3376,8009,7240,7027,4602,2947,9081,4045,8424,9352,8742,923,2705,4266,3232,2264,6761,363,2651,3383,7770,6730,7856,7340,9679,2158,610,4471,4608,910,6241], +[4417,6756,1013,8797,658,8809,5032,8703,7541,846,3357,2920,9817,1745,9980,7593,4667,3087,779,3218,6233,5568,4296,2289,2654,7898,5021,9461,5593,8214,9173,4203,2271,7980,2983,5952,9992,8399,3468,1776,3188,9314,1720,6523,2933,621,8685,5483,8986,6163,3444,9539,4320,155,3992,2828,2150,6071,524,2895,5468,8063,1210,3348,9071,4862,483,9017,4097,6186,9815,3610,5048,1644,1003,9865,9332,2145,1944,2213], +[9284,3803,4920,1927,6706,4344,7383,4786,9890,2010,5228,1224,3158,6967,8580,8990,8883,5213,76,8306,2031,4980,5639,9519,7184,5645,7769,3259,8077,9130,1317,3096,9624,3818,1770,695,2454,947,6029,3474,9938,3527,5696,4760,7724,7738,2848,6442,5767,6845,8323,4131,2859,7595,2500,4815,3660,9130,8580,7016,8231,4391,8369,3444,4069,4021,556,6154,627,2778,1496,4206,6356,8434,8491,3816,8231,3190,5575,1015], +[3787,7572,1788,6803,5641,6844,1961,4811,8535,9914,9999,1450,8857,738,4662,8569,6679,2225,7839,8618,286,2648,5342,2294,3205,4546,176,8705,3741,6134,8324,8021,7004,5205,7032,6637,9442,5539,5584,4819,5874,5807,8589,6871,9016,983,1758,3786,1519,6241,185,8398,495,3370,9133,3051,4549,9674,7311,9738,3316,9383,2658,2776,9481,7558,619,3943,3324,6491,4933,153,9738,4623,912,3595,7771,7939,1219,4405], +[2650,3883,4154,5809,315,7756,4430,1788,4451,1631,6461,7230,6017,5751,138,588,5282,2442,9110,9035,6349,2515,1570,6122,4192,4174,3530,1933,4186,4420,4609,5739,4135,2963,6308,1161,8809,8619,2796,3819,6971,8228,4188,1492,909,8048,2328,6772,8467,7671,9068,2226,7579,6422,7056,8042,3296,2272,3006,2196,7320,3238,3490,3102,37,1293,3212,4767,5041,8773,5794,4456,6174,7279,7054,2835,7053,9088,790,6640], +[3101,1057,7057,3826,6077,1025,2955,1224,1114,6729,5902,4698,6239,7203,9423,1804,4417,6686,1426,6941,8071,1029,4985,9010,6122,6597,1622,1574,3513,1684,7086,5505,3244,411,9638,4150,907,9135,829,981,1707,5359,8781,9751,5,9131,3973,7159,1340,6955,7514,7993,6964,8198,1933,2797,877,3993,4453,8020,9349,8646,2779,8679,2961,3547,3374,3510,1129,3568,2241,2625,9138,5974,8206,7669,7678,1833,8700,4480], +[4865,9912,8038,8238,782,3095,8199,1127,4501,7280,2112,2487,3626,2790,9432,1475,6312,8277,4827,2218,5806,7132,8752,1468,7471,6386,739,8762,8323,8120,5169,9078,9058,3370,9560,7987,8585,8531,5347,9312,1058,4271,1159,5286,5404,6925,8606,9204,7361,2415,560,586,4002,2644,1927,2824,768,4409,2942,3345,1002,808,4941,6267,7979,5140,8643,7553,9438,7320,4938,2666,4609,2778,8158,6730,3748,3867,1866,7181], +[171,3771,7134,8927,4778,2913,3326,2004,3089,7853,1378,1729,4777,2706,9578,1360,5693,3036,1851,7248,2403,2273,8536,6501,9216,613,9671,7131,7719,6425,773,717,8803,160,1114,7554,7197,753,4513,4322,8499,4533,2609,4226,8710,6627,644,9666,6260,4870,5744,7385,6542,6203,7703,6130,8944,5589,2262,6803,6381,7414,6888,5123,7320,9392,9061,6780,322,8975,7050,5089,1061,2260,3199,1150,1865,5386,9699,6501], +[3744,8454,6885,8277,919,1923,4001,6864,7854,5519,2491,6057,8794,9645,1776,5714,9786,9281,7538,6916,3215,395,2501,9618,4835,8846,9708,2813,3303,1794,8309,7176,2206,1602,1838,236,4593,2245,8993,4017,10,8215,6921,5206,4023,5932,6997,7801,262,7640,3107,8275,4938,7822,2425,3223,3886,2105,8700,9526,2088,8662,8034,7004,5710,2124,7164,3574,6630,9980,4242,2901,9471,1491,2117,4562,1130,9086,4117,6698], +[2810,2280,2331,1170,4554,4071,8387,1215,2274,9848,6738,1604,7281,8805,439,1298,8318,7834,9426,8603,6092,7944,1309,8828,303,3157,4638,4439,9175,1921,4695,7716,1494,1015,1772,5913,1127,1952,1950,8905,4064,9890,385,9357,7945,5035,7082,5369,4093,6546,5187,5637,2041,8946,1758,7111,6566,1027,1049,5148,7224,7248,296,6169,375,1656,7993,2816,3717,4279,4675,1609,3317,42,6201,3100,3144,163,9530,4531], +[7096,6070,1009,4988,3538,5801,7149,3063,2324,2912,7911,7002,4338,7880,2481,7368,3516,2016,7556,2193,1388,3865,8125,4637,4096,8114,750,3144,1938,7002,9343,4095,1392,4220,3455,6969,9647,1321,9048,1996,1640,6626,1788,314,9578,6630,2813,6626,4981,9908,7024,4355,3201,3521,3864,3303,464,1923,595,9801,3391,8366,8084,9374,1041,8807,9085,1892,9431,8317,9016,9221,8574,9981,9240,5395,2009,6310,2854,9255], +[8830,3145,2960,9615,8220,6061,3452,2918,6481,9278,2297,3385,6565,7066,7316,5682,107,7646,4466,68,1952,9603,8615,54,7191,791,6833,2560,693,9733,4168,570,9127,9537,1925,8287,5508,4297,8452,8795,6213,7994,2420,4208,524,5915,8602,8330,2651,8547,6156,1812,6271,7991,9407,9804,1553,6866,1128,2119,4691,9711,8315,5879,9935,6900,482,682,4126,1041,428,6247,3720,5882,7526,2582,4327,7725,3503,2631], +[2738,9323,721,7434,1453,6294,2957,3786,5722,6019,8685,4386,3066,9057,6860,499,5315,3045,5194,7111,3137,9104,941,586,3066,755,4177,8819,7040,5309,3583,3897,4428,7788,4721,7249,6559,7324,825,7311,3760,6064,6070,9672,4882,584,1365,9739,9331,5783,2624,7889,1604,1303,1555,7125,8312,425,8936,3233,7724,1480,403,7440,1784,1754,4721,1569,652,3893,4574,5692,9730,4813,9844,8291,9199,7101,3391,8914], +[6044,2928,9332,3328,8588,447,3830,1176,3523,2705,8365,6136,5442,9049,5526,8575,8869,9031,7280,706,2794,8814,5767,4241,7696,78,6570,556,5083,1426,4502,3336,9518,2292,1885,3740,3153,9348,9331,8051,2759,5407,9028,7840,9255,831,515,2612,9747,7435,8964,4971,2048,4900,5967,8271,1719,9670,2810,6777,1594,6367,6259,8316,3815,1689,6840,9437,4361,822,9619,3065,83,6344,7486,8657,8228,9635,6932,4864], +[8478,4777,6334,4678,7476,4963,6735,3096,5860,1405,5127,7269,7793,4738,227,9168,2996,8928,765,733,1276,7677,6258,1528,9558,3329,302,8901,1422,8277,6340,645,9125,8869,5952,141,8141,1816,9635,4025,4184,3093,83,2344,2747,9352,7966,1206,1126,1826,218,7939,2957,2729,810,8752,5247,4174,4038,8884,7899,9567,301,5265,5752,7524,4381,1669,3106,8270,6228,6373,754,2547,4240,2313,5514,3022,1040,9738], +[2265,8192,1763,1369,8469,8789,4836,52,1212,6690,5257,8918,6723,6319,378,4039,2421,8555,8184,9577,1432,7139,8078,5452,9628,7579,4161,7490,5159,8559,1011,81,478,5840,1964,1334,6875,8670,9900,739,1514,8692,522,9316,6955,1345,8132,2277,3193,9773,3923,4177,2183,1236,6747,6575,4874,6003,6409,8187,745,8776,9440,7543,9825,2582,7381,8147,7236,5185,7564,6125,218,7991,6394,391,7659,7456,5128,5294], +[2132,8992,8160,5782,4420,3371,3798,5054,552,5631,7546,4716,1332,6486,7892,7441,4370,6231,4579,2121,8615,1145,9391,1524,1385,2400,9437,2454,7896,7467,2928,8400,3299,4025,7458,4703,7206,6358,792,6200,725,4275,4136,7390,5984,4502,7929,5085,8176,4600,119,3568,76,9363,6943,2248,9077,9731,6213,5817,6729,4190,3092,6910,759,2682,8380,1254,9604,3011,9291,5329,9453,9746,2739,6522,3765,5634,1113,5789], +[5304,5499,564,2801,679,2653,1783,3608,7359,7797,3284,796,3222,437,7185,6135,8571,2778,7488,5746,678,6140,861,7750,803,9859,9918,2425,3734,2698,9005,4864,9818,6743,2475,132,9486,3825,5472,919,292,4411,7213,7699,6435,9019,6769,1388,802,2124,1345,8493,9487,8558,7061,8777,8833,2427,2238,5409,4957,8503,3171,7622,5779,6145,2417,5873,5563,5693,9574,9491,1937,7384,4563,6842,5432,2751,3406,7981]] + +# min path sum from (0,0) to (79,79) +N = len(mat) + +dp = [[100000*80 for _ in range(N+1)] for _ in range(N+1)] + +for i in range(N-1, -1, -1): + for j in range(N-1, -1, -1): + if i == N-1 and j == N-1: + dp[i][j] = mat[i][j] + else: + dp[i][j] = mat[i][j] + min(dp[i][j+1], dp[i+1][j]) + +print(dp[0][0]) + + + + From 2e1655ed5752a62e1c0e5eb27484938e4f603db7 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Sat, 25 Apr 2020 17:46:37 +0530 Subject: [PATCH 08/47] PE70: Phi in NlogN, interview --- MyOnlineSubmissions/ProjectEuler/70.py | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 MyOnlineSubmissions/ProjectEuler/70.py diff --git a/MyOnlineSubmissions/ProjectEuler/70.py b/MyOnlineSubmissions/ProjectEuler/70.py new file mode 100644 index 0000000..3d528d3 --- /dev/null +++ b/MyOnlineSubmissions/ProjectEuler/70.py @@ -0,0 +1,32 @@ +# Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation of 79180. +# Find the value of n, 1 < n < 10^7, for which φ(n) is a permutation of n and the ratio n/φ(n) produces a minimum. +N = 10**7 +rat = N + 1 +ans = -1 + +def same(x, y): + return sorted(str(x)) == sorted(str(y)) + +def euler_phi(MAX=N+1): + phi = [0 for _ in range(MAX+1)] + phi[1] = 1 + for i in range(2, MAX+1): + if not phi[i]: + phi[i] = i-1 + for j in range((i<<1), MAX+1, i): + if not phi[j]: + phi[j] = j + phi[j] = (phi[j]//i) * (i-1) + return phi + +phi = euler_phi() + +for n in range(2, N + 1): + p = phi[n] + if same(p, n): + print(n, p) + if rat > n/p: + rat = n/p + ans = n + +print(ans) From d53ab066bf9b7d4a710bafda5df2be8a4dc20b88 Mon Sep 17 00:00:00 2001 From: Learning Algorithms With Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Tue, 12 May 2020 19:46:26 +0530 Subject: [PATCH 09/47] solution to CHANDF.cpp 1. https://www.youtube.com/watch?v=-F7cHQ-gWS4 2. Greediest Competitive Programming problem ever 3. Awesome Logical Reasoning / Problem Solving skills are needed to solve this. --- MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp diff --git a/MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp b/MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp new file mode 100644 index 0000000..bd717b9 --- /dev/null +++ b/MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp @@ -0,0 +1,122 @@ +// Video Explanation at https://www.youtube.com/watch?v=-F7cHQ-gWS4 +#include +using namespace std; + +#define ll long long + +ll f(ll &x, ll &y, ll &z) { + return (x&z) * (y&z); +} + +class Bit{ + ll x; + int _bits; // we need only these many bits, in this case 40 + + #define mask(b) (1LL<<(_bits-b)) // remember 0th bit is actually 39th bit +public: + Bit() {} + + Bit(ll &y, int bits=40) { + init(y, bits); + } + + void init(ll &y, int bits=40) { + x = y; + _bits = bits-1; + } + + bool get(int &b) { + return (x & mask(b)) != 0; + } + + void set(int &b) { + x |= mask(b); + } + + void reset(int &b) { + if(get(b)) + x ^= mask(b); + } + + void set(int &b,int k) { + if(k == 1) { + set(b); + } + else { + reset(b); + } + } + + ll toInt() { + return x; + } +} bitX, bitY; + +vector getValidZValues(ll &L, ll &R) { + vector validZ = {L, R}; // L and R are always valid Z values we should handle + Bit bitL(L); + Bit bitR(R); + int k = 0; + while(k<40 and bitL.get(k) == bitR.get(k)) k++; + + for(int l = k+1; l < 40; l++) { + if(bitL.get(l) != 0) continue; + Bit z(L); + z.set(l); + for(int i=l+1; i<40; i++) { + if(bitX.get(i) == 0 and bitY.get(i) == 0) { + z.set(i, 0); // minimize Z + } + else { + z.set(i, 1); // maximize F(X,Y,Z) + } + } + validZ.push_back(z.toInt()); + } + for(int r = k+1; r < 40; r++) { + if(bitR.get(r) != 1) continue; + Bit z(R); + z.reset(r); + for(int i=r+1; i<40; i++) { + if(bitX.get(i) == 0 and bitY.get(i) == 0) { + z.set(i, 0); + } + else { + z.set(i, 1); + } + } + validZ.push_back(z.toInt()); + } + + sort(validZ.begin(), validZ.end()); + return validZ; +} + +int main() { + ios_base::sync_with_stdio(0); + int t; + cin >> t; + + while(t--) { + ll x, y, l, r; + cin >> x >> y >> l >> r; + + bitX.init(x); + bitY.init(y); + + vector Zcandidates = getValidZValues(l, r); + + ll mx = -1, ans = r; + for(ll z: Zcandidates) { + ll currentF = f(x, y, z); + if(currentF > mx) { + mx = currentF; + ans = z; + } + } + + cout << ans << endl; + } + + return 0; +} From 8848e83faaef284f479bbf7a230fdd5b2e79c520 Mon Sep 17 00:00:00 2001 From: Learning Algorithms With Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Tue, 12 May 2020 19:52:26 +0530 Subject: [PATCH 10/47] Update CHANDF.cpp --- MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp b/MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp index bd717b9..7bf02dc 100644 --- a/MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp +++ b/MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp @@ -53,7 +53,7 @@ class Bit{ } bitX, bitY; vector getValidZValues(ll &L, ll &R) { - vector validZ = {L, R}; // L and R are always valid Z values we should handle + vector Zcandidates = {L, R}; // L and R are always valid Z values we should handle Bit bitL(L); Bit bitR(R); int k = 0; @@ -71,7 +71,7 @@ vector getValidZValues(ll &L, ll &R) { z.set(i, 1); // maximize F(X,Y,Z) } } - validZ.push_back(z.toInt()); + Zcandidates.push_back(z.toInt()); } for(int r = k+1; r < 40; r++) { if(bitR.get(r) != 1) continue; @@ -85,11 +85,11 @@ vector getValidZValues(ll &L, ll &R) { z.set(i, 1); } } - validZ.push_back(z.toInt()); + Zcandidates.push_back(z.toInt()); } - sort(validZ.begin(), validZ.end()); - return validZ; + sort(Zcandidates.begin(), Zcandidates.end()); + return Zcandidates; } int main() { From 593392aee3994044a9269b245363a5b3608c58ef Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Fri, 15 May 2020 06:26:43 +0000 Subject: [PATCH 11/47] Amazon Interview Question (Longest Subscrting without repeating chars) --- LeetCode/1.two-sum.cpp | 24 +++++++++++++++ ...substring-without-repeating-characters.cpp | 29 +++++++++++++++++++ LeetCode/7.reverse-integer.cpp | 24 +++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 LeetCode/1.two-sum.cpp create mode 100644 LeetCode/3.longest-substring-without-repeating-characters.cpp create mode 100644 LeetCode/7.reverse-integer.cpp diff --git a/LeetCode/1.two-sum.cpp b/LeetCode/1.two-sum.cpp new file mode 100644 index 0000000..dcfb62f --- /dev/null +++ b/LeetCode/1.two-sum.cpp @@ -0,0 +1,24 @@ +/* + * @lc app=leetcode id=1 lang=cpp + * + * [1] Two Sum + */ + +// @lc code=start +#include +class Solution { +public: + vector twoSum(vector& nums, int target) { + map id; + for(int i = 0; i < nums.size(); i++) { + int make = target - nums[i]; + if(id[make]) { + return {id[make]-1, i}; + } + id[nums[i]] = i+1; + } + return {-1, -1}; + } +}; +// @lc code=end + diff --git a/LeetCode/3.longest-substring-without-repeating-characters.cpp b/LeetCode/3.longest-substring-without-repeating-characters.cpp new file mode 100644 index 0000000..6a273b9 --- /dev/null +++ b/LeetCode/3.longest-substring-without-repeating-characters.cpp @@ -0,0 +1,29 @@ +/* + * @lc app=leetcode id=3 lang=cpp + * + * [3] Longest Substring Without Repeating Characters + */ + +// @lc code=start +class Solution { +public: + int lengthOfLongestSubstring(string s) { + int n = s.size(); + if(s.size()==0)return 0; + int i,j; + i=0, j=0; + vector cnt(326, 0); + cnt[s[0]]++; + int ans=1; + while(1){ + if(j==n-1) break; + if(cnt[s[j+1]] == 0) j++, cnt[s[j]]++, ans=max(ans,j-i+1); + else { + cnt[s[i++]]--; + } + } + return ans; + } +}; +// @lc code=end + diff --git a/LeetCode/7.reverse-integer.cpp b/LeetCode/7.reverse-integer.cpp new file mode 100644 index 0000000..7e471b6 --- /dev/null +++ b/LeetCode/7.reverse-integer.cpp @@ -0,0 +1,24 @@ +/* + * @lc app=leetcode id=7 lang=cpp + * + * [7] Reverse Integer + */ + +// @lc code=start +class Solution { +public: + int reverse(int x) { + long long rev = 0; + long long limit = (1LL<<31); + while(x) { + int d = x%10; + x /= 10; + rev = 10*rev + d; + } + if(rev >= limit or rev < -limit) + return 0; + return rev; + } +}; +// @lc code=end + From 0c099f2749f2b535173a34926993dac2d58e2c51 Mon Sep 17 00:00:00 2001 From: Learning Algorithms With Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Fri, 15 May 2020 13:29:00 +0530 Subject: [PATCH 12/47] Create 3.longest-substring-without-repeating-characters.py Solution in py --- ...-substring-without-repeating-characters.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 LeetCode/3.longest-substring-without-repeating-characters.py diff --git a/LeetCode/3.longest-substring-without-repeating-characters.py b/LeetCode/3.longest-substring-without-repeating-characters.py new file mode 100644 index 0000000..6981b9e --- /dev/null +++ b/LeetCode/3.longest-substring-without-repeating-characters.py @@ -0,0 +1,26 @@ +class Solution { +public: + int lengthOfLongestSubstring(string s) { + if(s.size()==0)return 0; // did you handle this? + int n = s.size(); + int i(0), j(0); + + // s[j] is a char, 'A' is 65, 'a' is 97 + vector cnt(300, 0); // ASCII length of 255 will be fine + cnt[s[0]]++; // this can crash if string is empty + + int ans=1; + while(j!=n-1){ + if(cnt[s[j+1]] == 0) { + j++; + cnt[s[j]] = 1; + ans = max(ans, j-i+1); + } + else { + i++; + cnt[s[i]]--; + } + } + return ans; + } +}; From b20c1dae70cbd8ce1365e219a3962ea6e79f404f Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Fri, 15 May 2020 17:23:49 +0000 Subject: [PATCH 13/47] Interview Question - Minimum Coin Change - DP --- LeetCode/322.coin-change.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 LeetCode/322.coin-change.py diff --git a/LeetCode/322.coin-change.py b/LeetCode/322.coin-change.py new file mode 100644 index 0000000..4b68e85 --- /dev/null +++ b/LeetCode/322.coin-change.py @@ -0,0 +1,28 @@ +# +# @lc app=leetcode id=322 lang=python3 +# +# [322] Coin Change +# + +# @lc code=start +INF = 10 ** 7 +class Solution: + def coinChange(self, C: List[int], S: int) -> int: + noCoins = len(C) + dp = [[INF for _ in range(noCoins+1)] for _ in range(S+1)] + # dp[i][j] is min coins needed to make sum "i" when first "j" coins are available + dp[0][0] = 0 # no coin needed to make 0 + for i in range(0, S+1): + for j in range(1, noCoins+1): + curCoin = C[j-1] # 0-based indexing + + # Case A: I don't take jth coin + dp[i][j] = dp[i][j-1] + + # Case B: I take jth coin + if curCoin <= i: + dp[i][j] = min(dp[i][j], 1 + dp[i-curCoin][j]) + return dp[S][noCoins] if dp[S][noCoins] != INF else -1 + +# @lc code=end + From cb6090c038f3c39defbc0947cb9cc27b75cec421 Mon Sep 17 00:00:00 2001 From: Learning Algorithms With Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Sat, 16 May 2020 15:21:41 +0530 Subject: [PATCH 14/47] Create 155.min-stack.cpp --- LeetCode/155.min-stack.cpp | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 LeetCode/155.min-stack.cpp diff --git a/LeetCode/155.min-stack.cpp b/LeetCode/155.min-stack.cpp new file mode 100644 index 0000000..d89c1ab --- /dev/null +++ b/LeetCode/155.min-stack.cpp @@ -0,0 +1,39 @@ +class MinStack { +public: + /** initialize your data structure here. */ + vector a, b; + MinStack() { + a = b = {}; + } + + void push(int x) { + a.push_back(x); + if(b.empty()) b.push_back(x); + else { + int newMin = min(x, *b.rbegin()); + b.push_back(newMin); + } + } + + void pop() { + a.pop_back(); + b.pop_back(); + } + + int top() { + return *a.rbegin(); + } + + int getMin() { + return *b.rbegin(); + } +}; + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack* obj = new MinStack(); + * obj->push(x); + * obj->pop(); + * int param_3 = obj->top(); + * int param_4 = obj->getMin(); + */ From e2662728597f9e0d166d9ffd8fa3ec538842db49 Mon Sep 17 00:00:00 2001 From: Learning Algorithms With Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Sat, 16 May 2020 20:19:17 +0530 Subject: [PATCH 15/47] HARD - Greedy - Implementation Corner cases should be covered too. Did you cover them? --- LeetCode/41.first-missing-positive.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LeetCode/41.first-missing-positive.py diff --git a/LeetCode/41.first-missing-positive.py b/LeetCode/41.first-missing-positive.py new file mode 100644 index 0000000..55e836d --- /dev/null +++ b/LeetCode/41.first-missing-positive.py @@ -0,0 +1,14 @@ +class Solution: + def firstMissingPositive(self, nums: List[int]) -> int: + n = len(nums) + for i in range(n): + correctPos = nums[i]-1 # number 3 goes to index 2 + while 1 <= nums[i] <= n and nums[i] != nums[correctPos]: + nums[i], nums[correctPos] = nums[correctPos], nums[i] + correctPos = nums[i]-1 # now nums[i] has changed + + + for i in range(n): + if i+1 != nums[i]: + return i+1 + return n+1 From 9fb729811a6503249d8e4c19f6bc9b0fc0a866d1 Mon Sep 17 00:00:00 2001 From: Learning Algorithms With Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Sat, 16 May 2020 20:20:39 +0530 Subject: [PATCH 16/47] CPP version of MEX value of array in O(1) space Check python code for more comments --- LeetCode/41.first-missing-positive.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 LeetCode/41.first-missing-positive.cpp diff --git a/LeetCode/41.first-missing-positive.cpp b/LeetCode/41.first-missing-positive.cpp new file mode 100644 index 0000000..2b54d9c --- /dev/null +++ b/LeetCode/41.first-missing-positive.cpp @@ -0,0 +1,18 @@ +// Check Youtube video for video explanation +class Solution { +public: + int firstMissingPositive(vector A) + { + int n = A.size(); + for(int i = 0; i < n; ++ i) { + while(A[i] >= 1 && A[i] <= n && A[i] != i+1) + swap(A[i], A[A[i] - 1]); + } + + for(int i = 0; i < n; ++ i) + if(A[i] != i + 1) + return i + 1; + + return n + 1; + } +}; From da09b2d64465561b0e341c3be2adcb5064c6f053 Mon Sep 17 00:00:00 2001 From: Learning Algorithms With Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Sat, 16 May 2020 20:21:46 +0530 Subject: [PATCH 17/47] bugfix --- LeetCode/41.first-missing-positive.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LeetCode/41.first-missing-positive.cpp b/LeetCode/41.first-missing-positive.cpp index 2b54d9c..f1ac638 100644 --- a/LeetCode/41.first-missing-positive.cpp +++ b/LeetCode/41.first-missing-positive.cpp @@ -5,7 +5,7 @@ class Solution { { int n = A.size(); for(int i = 0; i < n; ++ i) { - while(A[i] >= 1 && A[i] <= n && A[i] != i+1) + while(A[i] >= 1 && A[i] <= n && A[i] != A[A[i]-1]) swap(A[i], A[A[i] - 1]); } From bfce419d7bc43693283cb12485398741880df8ae Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Mon, 25 May 2020 01:24:35 +0530 Subject: [PATCH 18/47] RollingHash on Strings/Vector added --- Library/Miscellanious/RollingHash.cpp | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Library/Miscellanious/RollingHash.cpp diff --git a/Library/Miscellanious/RollingHash.cpp b/Library/Miscellanious/RollingHash.cpp new file mode 100644 index 0000000..6247624 --- /dev/null +++ b/Library/Miscellanious/RollingHash.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + + +typedef long long HashInt; +static const HashInt HASH_MOD = 2'000'000'033; +struct ModBasedHashInt { + HashInt x; ModBasedHashInt(HashInt x=0) : x(x) {} + ModBasedHashInt operator+(ModBasedHashInt o) { + HashInt y = x + o.x; + return y - (y >= HASH_MOD) * HASH_MOD; + } + ModBasedHashInt operator*(ModBasedHashInt o) { return x*o.x % HASH_MOD; } + HashInt operator-(ModBasedHashInt o) { + HashInt y = x - o.x; + return y + (y < 0) * HASH_MOD; + } +}; +struct RollingHash { + #define sz(x) ((int)x.size()) + vector hash, power; + HashInt C; + RollingHash(string& str, HashInt Co) : hash(sz(str)+1), power(hash) { + C = Co; + power[0] = 1; + for(int i=0; i Date: Mon, 25 May 2020 01:41:09 +0530 Subject: [PATCH 19/47] Improved template - added multiple testcase format + random number generator --- Library/Miscellanious/template.cpp | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/Library/Miscellanious/template.cpp b/Library/Miscellanious/template.cpp index 7a8caf2..2ad8dd0 100644 --- a/Library/Miscellanious/template.cpp +++ b/Library/Miscellanious/template.cpp @@ -29,19 +29,35 @@ typedef vector vpii; typedef vector vpl; typedef vector vvi; typedef vector vvl; +mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); +int rng(int lim) { + uniform_int_distribution uid(0,lim-1); + return uid(rang); +} int mpow(int base, int exp); void ipgraph(int m); void dfs(int u, int par); -const int mod = 1000000007; + +const int mod = 1'000'000'007; const int N = 3e5, M = N; //======================= vi g[N]; int a[N]; +void solve() { + int i, j, n, m; +} + int main() { - ios_base::sync_with_stdio(0); - int t, i, j, k, p, q, r, x, y, u, v, n, m; + ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); + srand(chrono::high_resolution_clock::now().time_since_epoch().count()); + + int t = 1; + cin >> t; + while(t--) { + solve(); + } return 0; } From fe52796af9fba23ee6ef3937572c211442022993 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Mon, 25 May 2020 01:46:45 +0530 Subject: [PATCH 20/47] RollingHash: Bugfix - init to 0 explicitly added --- Library/Miscellanious/RollingHash.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Library/Miscellanious/RollingHash.cpp b/Library/Miscellanious/RollingHash.cpp index 6247624..03de045 100644 --- a/Library/Miscellanious/RollingHash.cpp +++ b/Library/Miscellanious/RollingHash.cpp @@ -20,7 +20,7 @@ struct RollingHash { #define sz(x) ((int)x.size()) vector hash, power; HashInt C; - RollingHash(string& str, HashInt Co) : hash(sz(str)+1), power(hash) { + RollingHash(string& str, HashInt Co) : hash(sz(str)+1, 0), power(hash) { C = Co; power[0] = 1; for(int i=0; i Date: Mon, 25 May 2020 02:19:37 +0530 Subject: [PATCH 21/47] NcR added --- Library/Math/NcR.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Library/Math/NcR.cpp diff --git a/Library/Math/NcR.cpp b/Library/Math/NcR.cpp new file mode 100644 index 0000000..94e5476 --- /dev/null +++ b/Library/Math/NcR.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; +const int mod = 1'000'000'007; + +int mpow(int base, int exp) { + int result = 1; + while (exp > 0) { + if (exp & 1) result = ((long long)result * base) % mod; + base = ((long long)base * base) % mod; + exp >>= 1; + } + return result; +} + +namespace NcR { + int fact[200005],ifact[200005]; + int get(int n, int r) { + if(n=0; i--) { + ifact[i] = (ifact[i+1] * 1LL * (i+1))%mod; + } + } +}; + +int main() { + + NcR::init(); + cout << NcR::get(4, 2) << endl; + return 0; +} \ No newline at end of file From 8be81ef3ecd458bae1bd97a8809ab5b5b154f8a0 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Mon, 25 May 2020 12:18:45 +0530 Subject: [PATCH 22/47] Z-Algorithm - bugfix - found in CC CookOff May20 --- Library/Miscellanious/z-algo.cpp | 35 +++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/Library/Miscellanious/z-algo.cpp b/Library/Miscellanious/z-algo.cpp index d11a913..9d81578 100755 --- a/Library/Miscellanious/z-algo.cpp +++ b/Library/Miscellanious/z-algo.cpp @@ -1,7 +1,10 @@ //Z-Algorithm //z[i] is length of prefix starting from i -int z[N]; -void go(string s){ + +// always pass stirng by reference, weird how it got me SIGSEGV in a Codechef problem +// https://codeforces.com/blog/entry/77906 +vector go(const string &s){ + vector z(s.size(), 0); int i, n = s.size(), L = 0, R = 0; z[0] = 0; Fo(i, 1, n){ @@ -22,5 +25,31 @@ void go(string s){ } } } - + + return z; } + + +// another implementation +template +vector z_function(int n, const T &s) { + vector z(n, n); + int l = 0, r = 0; + for (int i = 1; i < n; i++) { + z[i] = (i > r ? 0 : 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) { + l = i; + r = i + z[i] - 1; + } + } + return z; +} + +template +vector z_function(const T &s) { + return z_function((int) s.size(), s); +} + From 59312a62eacbc2b4497a2ea89f2b7c4b3c2d538f Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Tue, 2 Jun 2020 19:36:48 +0530 Subject: [PATCH 23/47] template demo.cpp so that others can understand my template --- Library/Miscellanious/template_demo.cpp | 126 ++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 Library/Miscellanious/template_demo.cpp diff --git a/Library/Miscellanious/template_demo.cpp b/Library/Miscellanious/template_demo.cpp new file mode 100644 index 0000000..67a197e --- /dev/null +++ b/Library/Miscellanious/template_demo.cpp @@ -0,0 +1,126 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k> t; + deb(t); + + while(t--) { + solve(); + } + + return 0; +} + +int mpow(int base, int exp) { + base %= mod; + int result = 1; + while (exp > 0) { + if (exp & 1) result = ((ll)result * base) % mod; + base = ((ll)base * base) % mod; + exp >>= 1; + } + return result; +} + +void ipgraph(int n, int m){ + int i, u, v; + while(m--){ + cin>>u>>v; + g[u-1].pb(v-1); + g[v-1].pb(u-1); + } +} + +void dfs(int u, int par){ + for(int v:g[u]){ + if (v == par) continue; + dfs(v, u); + } +} + + From 3a6018291028a9c5ed84390a4d84b4993ea6af50 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Tue, 2 Jun 2020 20:15:24 +0530 Subject: [PATCH 24/47] fastinput c++ --- Library/Miscellanious/fast_input.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Library/Miscellanious/fast_input.cpp diff --git a/Library/Miscellanious/fast_input.cpp b/Library/Miscellanious/fast_input.cpp new file mode 100644 index 0000000..03e978b --- /dev/null +++ b/Library/Miscellanious/fast_input.cpp @@ -0,0 +1,11 @@ +void si(int &ret){ + int ip=gc(),flag=1;ret=0;for(;ip<'0'||ip>'9';ip=gc()) + if(ip=='-'){flag=-1;ip=gc();break;} + for(;ip>='0'&&ip<='9';ip=gc())ret=(ret<<1)+(ret<<3)+ip-'0';ret*=flag; +} + +void sl(ll &ret) { + int ip=gc(),flag=1;ret=0;for(;ip<'0'||ip>'9';ip=gc()) + if(ip=='-'){flag=-1;ip=gc();break;} + for(;ip>='0'&&ip<='9';ip=gc())ret=(ret<<1)+(ret<<3)+ip-'0';ret*=flag; +} \ No newline at end of file From 9ed253220a2406da82a21e66953f0a9a83b25049 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Wed, 3 Jun 2020 23:11:59 +0530 Subject: [PATCH 25/47] making template better for graph input --- Library/Miscellanious/template.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Library/Miscellanious/template.cpp b/Library/Miscellanious/template.cpp index 2ad8dd0..6a2b834 100644 --- a/Library/Miscellanious/template.cpp +++ b/Library/Miscellanious/template.cpp @@ -77,8 +77,9 @@ void ipgraph(int n, int m){ int i, u, v; while(m--){ cin>>u>>v; - g[u-1].pb(v-1); - g[v-1].pb(u-1); + u--, v--; + g[u].pb(v); + g[v].pb(u); } } From be7789e1c8d9d5579e264ab95dc8a7e235980a31 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Wed, 3 Jun 2020 23:18:29 +0530 Subject: [PATCH 26/47] fixed typo in template for ipgraph --- Library/Miscellanious/template.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Library/Miscellanious/template.cpp b/Library/Miscellanious/template.cpp index 6a2b834..bd9b0bc 100644 --- a/Library/Miscellanious/template.cpp +++ b/Library/Miscellanious/template.cpp @@ -35,7 +35,7 @@ int rng(int lim) { return uid(rang); } int mpow(int base, int exp); -void ipgraph(int m); +void ipgraph(int n, int m); void dfs(int u, int par); const int mod = 1'000'000'007; From 7408c079d27156f2871143f6e494773c0e3d1c85 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Sat, 6 Jun 2020 13:09:19 +0530 Subject: [PATCH 27/47] enchanced template demo --- Library/Miscellanious/template_demo.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/Library/Miscellanious/template_demo.cpp b/Library/Miscellanious/template_demo.cpp index 67a197e..f590965 100644 --- a/Library/Miscellanious/template_demo.cpp +++ b/Library/Miscellanious/template_demo.cpp @@ -61,7 +61,7 @@ void solve() { // print sum int sum = 0; fo(i, n) fo(j, n) sum += a[i][j]; - pi(sum); + deb(sum); } // Fo demo - works in both direction (0 to 100) as well as (100, 0) @@ -77,7 +77,16 @@ void solve() { { // (a * b) % mod == ( (a%mod) * (b%mod) ) % mod int mpow_result = mpow(2, 1000); - pi(mpow_result); + deb(mpow_result); + } + + // vector, pair + { + vpii ans = {{1, 1}, {-3, 9}, {10, 100}, {6, 36}}; + sortall(ans); + + for(pii x: ans) printf("[%d, %d]", x.F, x.S); + printf("\n"); } } From 8a5b995b9f886b4db57662ccb8d1e4b533cf3df9 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Fri, 26 Jun 2020 21:24:21 +0530 Subject: [PATCH 28/47] added a shorter template for C++ --- Library/Miscellanious/template-short.cpp | 40 ++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Library/Miscellanious/template-short.cpp diff --git a/Library/Miscellanious/template-short.cpp b/Library/Miscellanious/template-short.cpp new file mode 100644 index 0000000..aa4571c --- /dev/null +++ b/Library/Miscellanious/template-short.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k Trie::autoComplete(const string &prefix) { + +} +bool Trie::isPresent(const string &word) { + +} From d6096866096fe05683c4c3f24186b3e7edf4c479 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Tue, 11 May 2021 01:19:25 +0530 Subject: [PATCH 38/47] implemented a complex trie data structure --- Library/Tree/trie.cpp | 100 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 95 insertions(+), 5 deletions(-) diff --git a/Library/Tree/trie.cpp b/Library/Tree/trie.cpp index a5bfe03..ba7d013 100644 --- a/Library/Tree/trie.cpp +++ b/Library/Tree/trie.cpp @@ -6,18 +6,35 @@ using namespace std; class Trie { - map keys = {}; - int traversed = 0; - bool isLeaf = 0; + map m_keys = {}; // what are the next avail chars in trie node + int m_traversed = 0; // how many words in trie are proper prefix + bool m_isLeaf = 0; // is this trie node a leaf node i.e a word ends here + int m_depth = 0; // depth of trie node + public: + Trie() = default; + Trie(int depth): m_depth(depth) {} + int getDepth() { return m_depth; } + bool isKeyPresent(const char &c) { return m_keys.find(c) != m_keys.end(); } + bool isLeaf() { return m_isLeaf; } + void setLeaf() { m_isLeaf = 1; } void add(const string &word); int matchLength(const string &prefix); // returns the length of max prefix that exists in trie + vector getAllWords(); vector autoComplete(const string &prefix); bool isPresent(const string &word); + void addKey(const char &c); + Trie *to(const char &c); }; template void assertVectors(const vector& lhs, const vector& rhs) { + // for(auto e: lhs) + // cout << e << " "; + // cout << endl; + // for(auto e: rhs) + // cout << e << " "; + // cout << endl; assert(lhs.size() == rhs.size()); for (int i = 0; i < lhs.size(); i++) { @@ -36,9 +53,11 @@ int main() { t.add(w); } + assertVectors(t.autoComplete(""), words); assertVectors(t.autoComplete("Ra"), {"Rachit", "Rachit1", "Ramesh"}); assertVectors(t.autoComplete("Rachit"), {"Rachit", "Rachit1"}); assertVectors(t.autoComplete("Rachit1"), {"Rachit1"}); + assertVectors(t.autoComplete("Rachit12"), {}); assert(t.isPresent("")); assert(!t.isPresent("Racht")); @@ -52,19 +71,90 @@ int main() { return 0; } +// add the given char to current Trie node +void Trie::addKey(const char& c) { + if(!isKeyPresent(c)) { + m_keys[c] = new Trie(m_depth + 1); + } + m_traversed++; +} + +Trie* Trie::to(const char& c) { + if(!isKeyPresent(c)) { + return NULL; + } + return m_keys[c]; +} +// add the word to trie, duplicates are ignored void Trie::add(const string &word) { - + Trie *cur = this; + for (char c: word) + { + cur->addKey(c); + cur = cur->to(c); + } + cur->setLeaf(); } // returns the length of max prefix that exists in trie int Trie::matchLength(const string &prefix) { + Trie *cur = this; + int match = 0; + for (char c: prefix) { + if (cur->isKeyPresent(c)) { + match++; + cur = cur->to(c); + } + else { + return match; + } + } + return match; +} +vector Trie::getAllWords() { + vector ans = {}; + for (auto it: m_keys) { + char c = it.first; + Trie *t = it.second; + if (t->isLeaf()) { + ans.push_back(string("") + c); + } + for (auto word: t->getAllWords()) { + ans.push_back(c + word); + } + } + + return ans; } vector Trie::autoComplete(const string &prefix) { + if (!isPresent(prefix)) { + return {}; + } + vector ans = {}; + + Trie *cur = this; + for (char c: prefix) { + if (cur->isKeyPresent(c)) { + cur = cur->to(c); + } + else { + break; + } + } + if (cur->isLeaf()) { + ans.push_back(prefix); + } + + for (auto restWord: cur->getAllWords()) { + ans.push_back(prefix + restWord); + } + return ans; } -bool Trie::isPresent(const string &word) { +bool Trie::isPresent(const string &word) { + return matchLength(word) == word.size(); } From 659d45b9019d576cd013b4bbf4ba2e66fab51713 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Sat, 22 May 2021 23:24:23 +0530 Subject: [PATCH 39/47] GRAPH_LIVE_YOUTUBE - 3 problems https://www.youtube.com/watch?v=4B0M0biIa3E --- LeetCode/765.couples-holding-hands.cpp | 69 +++++++++++++++++++ .../797.all-paths-from-source-to-target.cpp | 51 ++++++++++++++ LeetCode/997.find-the-town-judge.cpp | 26 +++++++ 3 files changed, 146 insertions(+) create mode 100644 LeetCode/765.couples-holding-hands.cpp create mode 100644 LeetCode/797.all-paths-from-source-to-target.cpp create mode 100644 LeetCode/997.find-the-town-judge.cpp diff --git a/LeetCode/765.couples-holding-hands.cpp b/LeetCode/765.couples-holding-hands.cpp new file mode 100644 index 0000000..ec357cf --- /dev/null +++ b/LeetCode/765.couples-holding-hands.cpp @@ -0,0 +1,69 @@ +const int N = 70; +set g[N]; +bool vis[N]; + +void fill_cluster_size(int u, int &cluster_size) { + vis[u] = 1; + // cout << "dfs::at couple " << u << endl; + cluster_size++; + for(int v: g[u]) { + if(!vis[v]) { + fill_cluster_size(v, cluster_size); + } + } +} + +int get_couple_id(int person) { + return person / 2; +} + + +class Solution { +public: + int minSwapsCouples(vector& row) { + int n = row.size() / 2; + // normalizing the seating arrangement in terms of couple ids + for(int &x: row) x = get_couple_id(x); + + for(int i = 0; i < n; i++) { + g[i].clear(); + vis[i] = 0; + } + + for(int i = 0; i < row.size(); i += 2) { + int c1 = row[i], c2 = row[i+1]; + if( c1 == c2 ) continue; + g[c1].insert(c2); + g[c2].insert(c1); + // cout << i << " adding edge in couple " << c1 << " " << c2 << endl; + } + + int ans = 0; + for(int i = 0; i < n; i++) { + if(!vis[i]) { + int cluster_size = 0; + fill_cluster_size(i, cluster_size); + ans += cluster_size - 1; + } + } + return ans; + } +}; +/* + 0,3,1,2 -> 0,1,3,2 + easy notation: 0,1,0,1 + - Find a swap that can make two couples happy. + - +(0, 1) --- 1st couple --- couple id = 0 +(2, 3) --- 2nd couple --- couple id = 1 +(4, 5) -- 3rd couple --- couple id = 2 + 0,3,5,2,1,4 --> 0,1,2,1,0,2 + + 0---1---2 + \______/ + +x----y <--- 1 swap +x----y----z <--- 2 swaps + +C couples --- C-1 swaps +*/ diff --git a/LeetCode/797.all-paths-from-source-to-target.cpp b/LeetCode/797.all-paths-from-source-to-target.cpp new file mode 100644 index 0000000..d7b9868 --- /dev/null +++ b/LeetCode/797.all-paths-from-source-to-target.cpp @@ -0,0 +1,51 @@ +const int N = 20; +vector g[N]; +using path = vector; +set get_all_paths(int src, int tar) { + // cout << src << endl; + if(src == tar) return { {tar} }; + set ans = {}; + for(int v: g[src]) { + auto rem_paths = get_all_paths(v, tar); + for (path p: rem_paths) { + p.push_back(src); + ans.insert(p); + } + } + return ans; +} + + +class Solution { + +public: + + vector> allPathsSourceTarget(vector>& graph) { + // paths from 0 to 4 + // iterate on children v of 0 + // find paths from child v to 4 + // [0,1,3,4] + int n = graph.size(); + + if(n == 0) return {}; + for(int i = 0; i < n; i++) g[i].clear(); + + for(int i = 0; i < n; i++) { + for(int v: graph[i]) { + g[i].push_back(v); + } + } + + vector ans = {}; + set paths = get_all_paths(0, n-1); + + + // O(# of paths * avg_size of path) + for(auto p: paths) { + reverse(p.begin(), p.end()); + ans.push_back(p); + } + + return ans; + } +}; diff --git a/LeetCode/997.find-the-town-judge.cpp b/LeetCode/997.find-the-town-judge.cpp new file mode 100644 index 0000000..a6e9c8c --- /dev/null +++ b/LeetCode/997.find-the-town-judge.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int findJudge(int n, vector>& trust) { + vector followers(n+1, 0); // 1 based indexing + vector does_follow(n+1, 0); + + map followers, does_follow; // O(logN) + + for(auto edge: trust) { + int u = edge[0], v = edge[1]; + // person u trusts v + followers[v]++; // O(1) v/s in maps O(logN) --> O(1) + does_follow[u] = 1; + } + + vector final_candidates = {}; + for(int i = 1; i <= n; i++) { + if(followers[i] == n-1 && does_follow[i] == 0) { + final_candidates.push_back(i); + } + } + + if(final_candidates.size() != 1) return -1; + return final_candidates[0]; + } +}; From efcc86e6628d63725b1ddef5d8655fe7026f1a79 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Mon, 24 May 2021 21:51:41 +0530 Subject: [PATCH 40/47] LIVE_YOUTUBE - Developer Bhaiya - 3 problems https://youtu.be/_I8q2nFu47I First Problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock Second problem: https://leetcode.com/problems/stone-game/ Third problem: https://leetcode.com/problems/jump-game/ https://www.youtube.com/watch?v=4KAQ6UViDoE +1 -1 trick: https://www.youtube.com/watch?v=ERAHSoAk2Yo --- .../121.best-time-to-buy-and-sell-stock.cpp | 26 ++++++++ LeetCode/55.jump-game.cpp | 30 +++++++++ LeetCode/877.stone-game.cpp | 63 +++++++++++++++++++ 3 files changed, 119 insertions(+) create mode 100644 LeetCode/121.best-time-to-buy-and-sell-stock.cpp create mode 100644 LeetCode/55.jump-game.cpp create mode 100644 LeetCode/877.stone-game.cpp diff --git a/LeetCode/121.best-time-to-buy-and-sell-stock.cpp b/LeetCode/121.best-time-to-buy-and-sell-stock.cpp new file mode 100644 index 0000000..ebd217b --- /dev/null +++ b/LeetCode/121.best-time-to-buy-and-sell-stock.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int maxProfit(vector& prices) { + int n = prices.size(); + int ans = 0, suff_max = prices.back(); + for(int i = n-2; i >= 0; i--) { + ans = max(ans, suff_max - prices[i]); + suff_max = max(suff_max, prices[i]); + /* + for(int j = i+1; j < n; j++) { + ans = max(ans, prices[j] - prices[i]); + } + */ + } + return ans; + } +}; +/* + <---100---> +_ _ _ 120 _ _ _ _ _ _ + i + + max = 100 + */ + + diff --git a/LeetCode/55.jump-game.cpp b/LeetCode/55.jump-game.cpp new file mode 100644 index 0000000..22c9ef7 --- /dev/null +++ b/LeetCode/55.jump-game.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + bool canJump(vector& nums) { + int n = nums.size(); + vector allowed(n, 0); // O(n) extra space + allowed[0] = 1; + for (int i = 0; i < n; i++) { + if (allowed[i]) { + for(int j = min(n-1, i+nums[i]); j >= i+1; j--) { + if(allowed[j]) break; + allowed[j] = 1; + } + } + } + return allowed[n-1]; + } +}; + +/* +_ _ _ 7 _ _ 1 1 1 1 1 _ + i x x x x x x x + +if i is allowerd and 100 + i+1,i+2,...,i+100 <-- allowed + +whether n-1 is allowed <-- true / false + + */ + + diff --git a/LeetCode/877.stone-game.cpp b/LeetCode/877.stone-game.cpp new file mode 100644 index 0000000..2374848 --- /dev/null +++ b/LeetCode/877.stone-game.cpp @@ -0,0 +1,63 @@ +#define deb(x1, x2, x3) cout << #x1 << "=" << x1 << " " << #x2 << "=" << x2 << " "<< #x3 << "=" << x3 << endl; + +class Solution { +public: + bool stoneGame(vector& piles) { + int n = piles.size(); + // dp[i][j] = max profit for first player when the game is at state [i..j] + vector> dp(n, vector(n, 0)); + for(int i = 0; i < n; i++) { + dp[i][i] = piles[i]; // 1 size subarrays have been computed + // if(i+1 < n) { + // dp[i][i+1] = abs(piles[i] - piles[i+1]); // subarrays of size 2 + // } + } + for(int len = 2; len <= n; len++) { + for(int i = 0; i < n; i++) { + int j = i + len - 1; + if(j >= n) continue; + // i .. j + // take the Lth stone + int choice1 = piles[i] - dp[i+1][j]; + + // take the Rth stone + int choice2 = piles[j] - dp[i][j-1]; + dp[i][j] = max(choice1, choice2); + // cout << i << " " << j << " " << dp[i][j] << endl; + // deb(i, j, dp[i][j]); + } + } + + + return dp[0][n-1] > 0; + } +}; + +/* +5, 3, 4, 5 -> 3,4,5 -> 3,4 -> 3 + + 5 + <---------------------->17 ==> 17 - 5 = 12 + 23,....................,17 + 23<----------------------> ===> 23-7 = 16 + 7 + + +state = [L, R] => by how much quantity the first player wins + + +[0, n-1] => +ve => first player can win -> true +[0, n-1] => -ve => first player cant win -> false + +// take the Lth stone +choice1 = piles[L] - win(L+1, R) + +// take the Rth stone +choice2 = piles[R] - win(L, R-1) + +win(L, R) = max(choice1, choice2); + +return win(0, n-1) > 0 + +*/ + From 26ba875da4a66e9136a03631f88cf546e8e3e61e Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Tue, 25 May 2021 22:45:41 +0530 Subject: [PATCH 41/47] LIVE_YOUTUBE - Developer Bhaiya - 2 problems, 1 script typing test --- LeetCode/45.jump-game2.cpp | 35 ++++++++++++++++++++++++++++++++++ LeetCode/841.keys-and-room.cpp | 33 ++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 LeetCode/45.jump-game2.cpp create mode 100644 LeetCode/841.keys-and-room.cpp diff --git a/LeetCode/45.jump-game2.cpp b/LeetCode/45.jump-game2.cpp new file mode 100644 index 0000000..0a2bdeb --- /dev/null +++ b/LeetCode/45.jump-game2.cpp @@ -0,0 +1,35 @@ +ass Solution { +public: + int jump(vector& nums) { + int n = nums.size(); + vector dp(n, INT_MAX - 1); + // dp[i] = min steps to reach the end of array if we are at ith index + dp[n-1] = 0; + for(int i = n-2; i >= 0; i--) { + for(int j = i+1; j <= i+nums[i]; j++) { + if(j >= n) break; + dp[i] = min(dp[i], 1 + dp[j]); + } + } + + return dp[0]; + } +}; + +/* +Find: min steps to reach the end of array + +Given: i -> we can jump a length of nums[i] +0 index + +_ _ _ _ 7 _ _ _ _ _ _ _ _ _ + i x x x x x x x + +dp[i] = min steps to reach the end of array if we are at ith index + +for(j=i+1; j<=i+7; j++) { + dp[i] = min(dp[i], 1 + dp[j]); +} + +return dp[0] +*/ diff --git a/LeetCode/841.keys-and-room.cpp b/LeetCode/841.keys-and-room.cpp new file mode 100644 index 0000000..8ed1768 --- /dev/null +++ b/LeetCode/841.keys-and-room.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + bool canVisitAllRooms(vector>& rooms) { + int n = rooms.size(); + vector vis(n, 0); + + queue q; + q.push(0); + vis[0] = 1; + while(!q.empty()) { + int cur = q.front(); + q.pop(); + for(int child: rooms[cur]) { + if (!vis[child]) { + vis[child] = 1; + q.push(child); + } + } + } + for(int i = 0; i < n; i++) { + if(!vis[i]) return 0; + } + return 1; + } +}; + +/* +Input: [[1,3],[3,0,1],[2],[0]] +0 --> 1 +| +| +3 +*/ From 7147d16c7dcc09ab373131281c6e71f64c14eb85 Mon Sep 17 00:00:00 2001 From: Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Wed, 26 May 2021 11:39:23 +0530 Subject: [PATCH 42/47] typo fix: "class" spelling in jump game2.cpp --- LeetCode/45.jump-game2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LeetCode/45.jump-game2.cpp b/LeetCode/45.jump-game2.cpp index 0a2bdeb..5eb0784 100644 --- a/LeetCode/45.jump-game2.cpp +++ b/LeetCode/45.jump-game2.cpp @@ -1,4 +1,4 @@ -ass Solution { +class Solution { public: int jump(vector& nums) { int n = nums.size(); From fdd00b53cebc982ca4551ee3a7d83dcc3d45871d Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Thu, 27 May 2021 23:50:03 +0530 Subject: [PATCH 43/47] LIVE_YOUTUBE - 3 DP problems --- LeetCode/1314.matrix-block-sum.cpp | 69 ++++++++++++++++++++++++++++++ LeetCode/1402.reducing-dishes.cpp | 29 +++++++++++++ LeetCode/53.maximum-subarray.cpp | 27 ++++++++++++ 3 files changed, 125 insertions(+) create mode 100644 LeetCode/1314.matrix-block-sum.cpp create mode 100644 LeetCode/1402.reducing-dishes.cpp create mode 100644 LeetCode/53.maximum-subarray.cpp diff --git a/LeetCode/1314.matrix-block-sum.cpp b/LeetCode/1314.matrix-block-sum.cpp new file mode 100644 index 0000000..2dad760 --- /dev/null +++ b/LeetCode/1314.matrix-block-sum.cpp @@ -0,0 +1,69 @@ +class Solution { +public: + vector> matrixBlockSum(vector>& mat, int k) { + int n = mat.size(), m = mat[0].size(); + vector> ans(n, vector(m, 0)); + vector> dp(n+1, vector(m+1, 0)); // 1-based indexing <-- prefix sums,˘ + + // compute the prefix sums + for(int i = 1; i <= n; i++) { + for(int j = 1; j <= m; j++) { + dp[i][j] = mat[i-1][j-1] + dp[i][j-1] + dp[i-1][j] - dp[i-1][j-1]; + } + } + + for(int i = 0; i < n; i++) { + for(int j = 0; j < m; j++) { + // compute the ans for (i,j) + int i1 = max(0, i-k), j1 = max(0,j-k); + int i2 = min(n-1, i+k), j2 = min(m-1, j+k); + i1++, i2++, j1++, j2++; //1-based indexing + + ans[i][j] = dp[i2][j2] - dp[i2][j1-1] - dp[i1-1][j2] + dp[i1-1][j1-1]; + } + },™ + return ans; + } +}; + +/* +prefix sum in 2d approach +dp[i][j] = sum of rect from (0,0) to (i,j) as diagnal points +=> it helps me in computing any rectangle sum in O(1) +(i1, j1) and (i2, j2) i1 < i2 and j1 < j2 + +dp[i2][j2] - dp[i1][j1-1] - dp[i1-1][j2] + dp[i1-1][j1-1] + + + +prefix sums can be used for each row individually +=> for given row, sum(j-k, j+k) => O(1) + j-k j j+k + + +i-k + + + +i x + + + +i+k + +(i,j) => O(k^2) +O(N^2k^2) +O(N^2 k) + + + + +k = 1 +[1,2,3], +[4,5,6], +[7,8,9] + +9*10/2 = 45 + + 5+6+8+9 = 28 +*/ diff --git a/LeetCode/1402.reducing-dishes.cpp b/LeetCode/1402.reducing-dishes.cpp new file mode 100644 index 0000000..4acb0e4 --- /dev/null +++ b/LeetCode/1402.reducing-dishes.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int maxSatisfaction(vector& arr) { + int n = arr.size(); + sort(arr.begin(), arr.end()); + int ans = 0; + for(int i = 0; i < n; i++) { + int cur = 0; + // considering the suffix from pos i + // [arr[i], arr[i+1], ... arr[n-1]] + // 1 2 + for(int j = i; j < n; j++) { + cur += (j-i+1) * arr[j]; + } + ans = max(ans, cur); + } + return ans; + } +}; + +/* +a1 <= a2 <= a3 .... // we have proved +(a1,a2,...,ak) <-- reordering of satisfaction array + you can remove elements +max(a1 + 2*a2 + 3*a3 + k*ak) + + -9 -8 -1 0 5 + + how long a prefix would you remove to get the max score +*/ diff --git a/LeetCode/53.maximum-subarray.cpp b/LeetCode/53.maximum-subarray.cpp new file mode 100644 index 0000000..019d5d2 --- /dev/null +++ b/LeetCode/53.maximum-subarray.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int maxSubArray(vector& nums) { + int n = nums.size(); + int ans = INT_MIN; + + // vector dp(n+1, 0); // O(N) extra space + // dp[i] = max subarray sum starting from index i + // mandate to pick something + int nextMax = 0; + for(int i = n-1; i >= 0; i--) { + // dp[i] = max(nums[i] + dp[i+1], 0) + // dp[i] = nums[i] + max(dp[i+1], 0); + int curMax = nums[i] + max(nextMax, 0); + ans = max(ans, curMax); + nextMax = curMax; + } + + return ans; + } +}; + +/* +_ _ _ _ _ 100 _ _ _ _ _ + i ^ + dp[i] = max(nums[i] + dp[i+1], 0) +*/ From d999e0d1396905d49c73a49323edb697b5ff3666 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Sat, 29 May 2021 00:00:09 +0530 Subject: [PATCH 44/47] LIVE_YOUTUBE - graphs and dp problem --- LeetCode/1306.jump-game3.cpp | 26 +++++++++++++++ LeetCode/542.01-matrix.cpp | 63 ++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 LeetCode/1306.jump-game3.cpp create mode 100644 LeetCode/542.01-matrix.cpp diff --git a/LeetCode/1306.jump-game3.cpp b/LeetCode/1306.jump-game3.cpp new file mode 100644 index 0000000..4886804 --- /dev/null +++ b/LeetCode/1306.jump-game3.cpp @@ -0,0 +1,26 @@ +class Solution { + vector nums; + set s; // what all indices are there in recursion stack + + bool isPossible(int cur) { // can we reach a zero from cur index + if (s.find(cur) != s.end()) { + return false; // we detected a cycle / deadlock + } + if(0 <= cur && cur < nums.size()) { + if(nums[cur] == 0) return true; + s.insert(cur); + bool ans = false; + if (isPossible(cur + nums[cur])) ans = true; + else if (isPossible(cur - nums[cur])) ans = true; + s.erase(cur); + return ans; + } + return false; + } +public: + bool canReach(vector& arr, int start) { + //dp[i] <-- is it possible to reach a zero from i + nums = arr; + return isPossible(start); + } +}; diff --git a/LeetCode/542.01-matrix.cpp b/LeetCode/542.01-matrix.cpp new file mode 100644 index 0000000..1300106 --- /dev/null +++ b/LeetCode/542.01-matrix.cpp @@ -0,0 +1,63 @@ +using loc = pair; +int dx[] = {1, -1, 0, 0}; +int dy[] = {0, 0, 1, -1}; +class Solution { +public: + vector> updateMatrix(vector>& mat) { + int n = mat.size(), m = mat[0].size(); + + vector> dis(n, vector(m, INT_MAX)); + // dis[i][j] = nearest distance (i, j) to nearest 0 + + queue q; + for(int i = 0; i < n; i++) { + for(int j = 0; j < m; j++) { + if (mat[i][j] == 0) { + q.push({i, j}); + dis[i][j] = 0; + } + } + } + + while(!q.empty()) { + // loc cur = q.front(); + // int x = cur.first, y = cur.second; + auto [x, y] = q.front(); // current loc in mat, structured binding in C++ + q.pop(); + // (2,3) -> (1, 3) up, (3, 3) down, +1 -1 on the columns as well + for(int k = 0; k < 4; k++) { + int nx = x + dx[k], ny = y + dy[k]; + if (0 <= nx && nx < n && 0 <= ny && ny < m) { + // valid neighbour + if (dis[nx][ny] == INT_MAX) { + dis[nx][ny] = 1 + dis[x][y]; + q.push({nx, ny}); + } + } + } + } + + return dis; + } +}; + +/* +// BFS gives the shortest path in unweighted graphs + +n * m <--- 0s and 1s + + for every 1: + compute the smallest distance to 0 + +dis[i][j] = 0 where mat[i][j] = 0 + +queue<> Q = {(i,j)} where mat[i][j] = 0; + +cur = Q.front(); + +for(nei in neighbors(cur)) { + dis[nei] = 1 + dis[cur] if nei is not alreaady in queue +} + +*/ + From 12db8aa431c839def39a77d7182ccdd15085da8f Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Tue, 1 Jun 2021 18:57:51 +0530 Subject: [PATCH 45/47] youtube_live strings and dp Livestream: https://www.youtube.com/watch?v=lU6dNcpCzPU Problems solved: https://leetcode.com/problems/unique-email-addresses/ https://leetcode.com/problems/find-and-replace-pattern https://leetcode.com/problems/palindromic-substrings/ https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/ --- ...tring-containing-vowels-in-even-counts.cpp | 59 +++++++++++++++++++ LeetCode/647.panlindrmoic-substrings.cpp | 39 ++++++++++++ LeetCode/890.find-and-replace-patterns.cpp | 45 ++++++++++++++ LeetCode/929.unique-email-address.cpp | 32 ++++++++++ 4 files changed, 175 insertions(+) create mode 100644 LeetCode/1371.find-the-longest-substring-containing-vowels-in-even-counts.cpp create mode 100644 LeetCode/647.panlindrmoic-substrings.cpp create mode 100644 LeetCode/890.find-and-replace-patterns.cpp create mode 100644 LeetCode/929.unique-email-address.cpp diff --git a/LeetCode/1371.find-the-longest-substring-containing-vowels-in-even-counts.cpp b/LeetCode/1371.find-the-longest-substring-containing-vowels-in-even-counts.cpp new file mode 100644 index 0000000..774d42c --- /dev/null +++ b/LeetCode/1371.find-the-longest-substring-containing-vowels-in-even-counts.cpp @@ -0,0 +1,59 @@ +string vowels = "aeiou"; +class Solution { +public: + int findTheLongestSubstring(string s) { + int n = s.size(); + int ans = 0; + unordered_map> pref = {}; + for (char v: vowels) pref[v] = {0}; + + for(char cur: s) { + for(char v: vowels) { + int last_parity = *pref[v].rbegin(); + if (cur == v) pref[v].push_back(1 - last_parity); + else pref[v].push_back(last_parity); + } + } + + auto get_column = [&](int j) { // 1 based + int id = 0; + for(char v: vowels) { + int x = pref[v][j]; + id = 2*id + x; + } + return id; + }; + + int rightmost[33]; + rightmost[0] = 0; + for (int i = 1; i <= n; i++) { + int id = get_column(i); + rightmost[id] = i; + } + + for (int i = 1; i <= n; i++) { + // find the rightmost j substring(i, j) is valid + // ith column + int id = get_column(i-1); + int j = rightmost[id]; + if (j < i) continue; + ans = max(ans, j-i+1); + } + return ans; + } +}; + +/* +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + i ^ ^ + maintain prefix count of all vowels pref[a][7] + a,b,a,e,e,a,e + i j +a - 0,1,1,0,0,0,1,1 +e - 0,0,0,0,1,0,0,1 +i - ...,1,.....,1 +o - ...,0,.....,1 +u - ...,0,.....,0 +10100 <-- 20 +n^2 substrings -> O(n) => overall O(n^3) +*/ \ No newline at end of file diff --git a/LeetCode/647.panlindrmoic-substrings.cpp b/LeetCode/647.panlindrmoic-substrings.cpp new file mode 100644 index 0000000..3f95980 --- /dev/null +++ b/LeetCode/647.panlindrmoic-substrings.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int countSubstrings(string s) { + int n = s.size(); + vector> dp(n, vector(n, 0)); + for(int i = 0; i < n; i++) + dp[i][i] = 1; + + // fill this dp + for(int len = 2; len <= n; len++) { + for(int i = 0; i + len - 1 < n; i++) { + // starting from i, and length len + int j = i + len - 1; + if (i+1 == j) { + dp[i][j] = s[i] == s[j]; + } + else { + dp[i][j] = s[i] == s[j] && dp[i+1][j-1]; + } + } + } + + int ans = 0; + for(int i = 0; i < n; i++) + for(int j = 0; j < n; j++) + ans += dp[i][j]; + return ans; + } +}; +/* +for substring in all_subtrings; + if palindrome(substring) + ans++; + + +dp[i][j] = substring(i, i+1, ..., j) = is this a palindrome + +s[i] == s[j] && dp[i+1][j-1] should be true +*/ \ No newline at end of file diff --git a/LeetCode/890.find-and-replace-patterns.cpp b/LeetCode/890.find-and-replace-patterns.cpp new file mode 100644 index 0000000..934033e --- /dev/null +++ b/LeetCode/890.find-and-replace-patterns.cpp @@ -0,0 +1,45 @@ +class Solution { + bool matches(string word, string pattern) { + int n = word.size(); + vector forward(26, -1), backward(26, -1); + // map forward, backward; unordered_map + for(int i = 0; i < n; i++) { + int x = word[i] - 'a', y = pattern[i] - 'a'; + // I am trying to map x to y + if(forward[x] != -1 && forward[x] != y) return false; + if(backward[y] != -1 && backward[y] != x) return false; + forward[x] = y; + backward[y] = x; + } + + return true; + } + +public: + vector findAndReplacePattern(vector& words, string pattern) { + vector ans = {}; + // O(n * k) k is avg word size + for (auto word: words) { + if (matches(word, pattern)) ans.push_back(word); + } + + return ans; + } +}; + +/* abb xyy yxx + +// abbccc +// matches - xyyzzz yzzxxx +// does not match - xyyxxx + +abbccc yzzxxx +abbccc xyyxxx + +if a is mapped to y, then - + - a shall never be mapped to anything else + - no other char shall be mapped to y + +math background - +1:1 mapping +*/ \ No newline at end of file diff --git a/LeetCode/929.unique-email-address.cpp b/LeetCode/929.unique-email-address.cpp new file mode 100644 index 0000000..64aa042 --- /dev/null +++ b/LeetCode/929.unique-email-address.cpp @@ -0,0 +1,32 @@ +class Solution { + string get_normalized(string email) { + int i; + string local_name = ""; + bool ignore_chars = false; + for(i = 0; i < email.size(); i++) { + char c = email[i]; + if (c == '@') { + break; + } + + if (c == '.' || ignore_chars) continue; + if (c == '+') { + ignore_chars = true; + continue; + } + + local_name += c; + } + string domain = email.substr(i); + return local_name + domain; + } +public: + int numUniqueEmails(vector& emails) { + set email_set; + for(string email: emails) { + email_set.insert(get_normalized(email)); + } + + return email_set.size(); + } +}; \ No newline at end of file From 8d15a9a3ec9dfc8a08ad7aedba85a447446d68a7 Mon Sep 17 00:00:00 2001 From: Rachit Jain Date: Sun, 13 Jun 2021 19:03:01 +0530 Subject: [PATCH 46/47] youtube_live - medium problems speedrun Discord: https://bit.ly/discord-rachit Here's the link to the livestream: https://bit.ly/3iJdosx https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/ https://leetcode.com/problems/deepest-leaves-sum https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/ https://leetcode.com/problems/queries-on-a-permutation-with-key/ --- ...le-given-the-group-size-they-belong-to.cpp | 29 +++++++++++++++ LeetCode/1302.deepest-leaves-sum.cpp | 31 ++++++++++++++++ ...1409.queries-on-a-permutation-with-key.cpp | 28 ++++++++++++++ ...erations-to-move-all-balls-to-each-box.cpp | 37 +++++++++++++++++++ 4 files changed, 125 insertions(+) create mode 100644 LeetCode/1282.group-the-people-given-the-group-size-they-belong-to.cpp create mode 100644 LeetCode/1302.deepest-leaves-sum.cpp create mode 100644 LeetCode/1409.queries-on-a-permutation-with-key.cpp create mode 100644 LeetCode/1769.minimum-number-of-operations-to-move-all-balls-to-each-box.cpp diff --git a/LeetCode/1282.group-the-people-given-the-group-size-they-belong-to.cpp b/LeetCode/1282.group-the-people-given-the-group-size-they-belong-to.cpp new file mode 100644 index 0000000..cb6d854 --- /dev/null +++ b/LeetCode/1282.group-the-people-given-the-group-size-they-belong-to.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector> groupThePeople(vector& groupSizes) { + int n = groupSizes.size(); + unordered_map> peopleInGroupSize = {}; + for(int i = 0; i < n; i++) { + int curSize = groupSizes[i]; + peopleInGroupSize[curSize].push_back(i); + } + vector> ans = {}; + for(auto [groupSize, people]: peopleInGroupSize) { + // start making groups of |groupSize| + vector cur = {}; + for(int i = 0; i < people.size(); i++) { + cur.push_back(people[i]); + if ( cur.size() == groupSize) { + ans.push_back(cur); + cur = {}; + } + } + } + return ans; + } +}; +/* +[group_size] --> [ids of people in it] +[3] --> [0,1,2,3,4,6] +[1] --> [5] + */ \ No newline at end of file diff --git a/LeetCode/1302.deepest-leaves-sum.cpp b/LeetCode/1302.deepest-leaves-sum.cpp new file mode 100644 index 0000000..a1c3e27 --- /dev/null +++ b/LeetCode/1302.deepest-leaves-sum.cpp @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { + pair getDepthAndSum(TreeNode* root) { + if (root == NULL) return {0, 0}; + if (root->left == NULL and root->right == NULL) + return {1, root->val}; + + auto [left_depth, left_sum] = getDepthAndSum(root->left); + auto [right_depth, right_sum] = getDepthAndSum(root->right); + + if (left_depth == right_depth) + return {1 + left_depth, left_sum + right_sum}; + if (left_depth > right_depth) + return {1 + left_depth, left_sum}; + return {1 + right_depth, right_sum}; + } +public: + int deepestLeavesSum(TreeNode* root) { + return getDepthAndSum(root).second; + } +}; \ No newline at end of file diff --git a/LeetCode/1409.queries-on-a-permutation-with-key.cpp b/LeetCode/1409.queries-on-a-permutation-with-key.cpp new file mode 100644 index 0000000..4c5b09e --- /dev/null +++ b/LeetCode/1409.queries-on-a-permutation-with-key.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector processQueries(vector& queries, int m) { + unordered_map pos, rev_pos; // pos[3] - 10 => 3 occurs at index 10 + for(int i = 1; i <= m; i++) { + pos[i] = i-1, rev_pos[i-1] = i; + } + + vector ans = {}; + for(int q: queries) { + ans.push_back(pos[q]); + // increment the pos of all nos from 0 to pos[q]-1 + for (int i = pos[q]-1 ; i >= 0; i--) { + int cur = rev_pos[i]; + pos[cur] = i+1; // shift to right side + rev_pos[i+1] = cur; + } + pos[q] = 0; + rev_pos[0] = q; + } + return ans; + } +}; +// 1,2,3,4,5 +// 3,1,2,4,5 + +// _ _ _ _ _ _ _ _ _ _ _ + // ^ \ No newline at end of file diff --git a/LeetCode/1769.minimum-number-of-operations-to-move-all-balls-to-each-box.cpp b/LeetCode/1769.minimum-number-of-operations-to-move-all-balls-to-each-box.cpp new file mode 100644 index 0000000..a6f539c --- /dev/null +++ b/LeetCode/1769.minimum-number-of-operations-to-move-all-balls-to-each-box.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector minOperations(string boxes) { + int n = boxes.size(); + int left_cnt = 0, tot_cnt = 0; // cnt of 1s + int left_sum = 0, tot_sum = 0; // sum of indices where its a 1 + + + for(int i = 0; i < n; i++) { + if (boxes[i] == '1') tot_cnt++, tot_sum += i; + } + + vector ans = {}; + for(int i = 0; i < n; i++) { + int right_cnt = tot_cnt - left_cnt; + int right_sum = tot_sum - left_sum; + + int left = left_cnt * i - left_sum; + int right = right_sum - right_cnt * i; + ans.push_back(left + right); + + if (boxes[i] == '1') left_cnt++, left_sum += i; + } + return ans; + } +}; + + +/* +i=13 +j<13 +i-j1 + i-j2 => 2*i - (j1+j2) + +j>13 +j1-i + j2-i => (j1+j2) - 2 *(i) +*/ + From da7e12d0b02e2c6dd3764c4ecc2b0853d16e8891 Mon Sep 17 00:00:00 2001 From: Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Sat, 16 Mar 2024 07:49:33 +0000 Subject: [PATCH 47/47] Codeforces Contest Runner and Debug Logger during Local --- .gitignore | 5 +- Library/Miscellanious/template2024.cpp | 41 +++++++++ Library/Utils/bits/stdc++.h | 117 +++++++++++++++++++++++++ Library/Utils/codeforces.sh | 30 +++++++ Library/Utils/logger.h | 108 +++++++++++++++++++++++ 5 files changed, 300 insertions(+), 1 deletion(-) create mode 100644 Library/Miscellanious/template2024.cpp create mode 100644 Library/Utils/bits/stdc++.h create mode 100644 Library/Utils/codeforces.sh create mode 100644 Library/Utils/logger.h diff --git a/.gitignore b/.gitignore index d99efa9..aa1d2cc 100644 --- a/.gitignore +++ b/.gitignore @@ -29,4 +29,7 @@ # Executables *.exe *.out -*.app \ No newline at end of file +*.app + +# Temp Codeforces Contest Env +CodeforcesContestRunner \ No newline at end of file diff --git a/Library/Miscellanious/template2024.cpp b/Library/Miscellanious/template2024.cpp new file mode 100644 index 0000000..8c129f4 --- /dev/null +++ b/Library/Miscellanious/template2024.cpp @@ -0,0 +1,41 @@ +#include +#ifndef ONLINE_JUDGE + #include "logger.h" +#else + #define deb(...) + #define deb(...) +#endif +using namespace std; +#define ll long long +#define all(x) x.begin(), x.end() +int mpow(int base, int exp); +//======================= +const int MOD = 1'000'000'007; +const int N = 2003, M = N; +vector g[N]; +int a[N]; + +void solve() { + +} + +int main() { + ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); + int t = 1; + cin >> t; + while(t--) { + solve(); + } + return 0; +} + +int mpow(int base, int exp) { + base %= MOD; + int result = 1; + while (exp > 0) { + if (exp & 1) result = ((ll)result * base) % MOD; + base = ((ll)base * base) % MOD; + exp >>= 1; + } + return result; +} \ No newline at end of file diff --git a/Library/Utils/bits/stdc++.h b/Library/Utils/bits/stdc++.h new file mode 100644 index 0000000..4886b92 --- /dev/null +++ b/Library/Utils/bits/stdc++.h @@ -0,0 +1,117 @@ +// C++ includes used for precompiling -*- C++ -*- + +// Copyright (C) 2003-2015 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// Under Section 7 of GPL version 3, you are granted additional +// permissions described in the GCC Runtime Library Exception, version +// 3.1, as published by the Free Software Foundation. + +// You should have received a copy of the GNU General Public License and +// a copy of the GCC Runtime Library Exception along with this program; +// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +// . + +/** @file stdc++.h + * This is an implementation file for a precompiled header. + */ + +// 17.4.1.2 Headers + +// C +#ifndef _GLIBCXX_NO_ASSERT +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if __cplusplus >= 201103L +#include +#include +#include +// #include +#include +#include +#include +#include +#include +#endif + +// C++ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if __cplusplus >= 201103L +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif \ No newline at end of file diff --git a/Library/Utils/codeforces.sh b/Library/Utils/codeforces.sh new file mode 100644 index 0000000..444da0b --- /dev/null +++ b/Library/Utils/codeforces.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +# Get the root directory of the Git repository +GIT_ROOT=$(git rev-parse --show-toplevel) + +function enter() { + mkdir -p $GIT_ROOT/CodeforcesContestRunner; + cd $GIT_ROOT/CodeforcesContestRunner; + cp $GIT_ROOT/Library/Miscellanious/template2024.cpp a.cpp + cp $GIT_ROOT/Library/Miscellanious/template2024.cpp b.cpp + cp $GIT_ROOT/Library/Miscellanious/template2024.cpp c.cpp + cp $GIT_ROOT/Library/Miscellanious/template2024.cpp d.cpp + cp $GIT_ROOT/Library/Miscellanious/template2024.cpp e.cpp + echo '' > in.txt +} + +function build() { + problem=$1 + g++ -std=c++20 $problem.cpp -o run_$problem -isystem $GIT_ROOT/Library/Utils +} + +function run() { + problem=$1 + ./run_$problem +} + +function runtxt() { + problem=$1 + ./run_$problem < in.txt +} \ No newline at end of file diff --git a/Library/Utils/logger.h b/Library/Utils/logger.h new file mode 100644 index 0000000..593d3a7 --- /dev/null +++ b/Library/Utils/logger.h @@ -0,0 +1,108 @@ +#include +// #define cerr cout +namespace __DEBUG_UTIL__ +{ + using namespace std; + template + concept is_iterable = requires(T &&x) { begin(x); } && + !is_same_v, string>; + void print(const char *x) { cerr << x; } + void print(char x) { cerr << "\'" << x << "\'"; } + void print(bool x) { cerr << (x ? "T" : "F"); } + void print(string x) { cerr << "\"" << x << "\""; } + void print(vector &v) + { /* Overloaded this because stl optimizes vector by using + _Bit_reference instead of bool to conserve space. */ + int f = 0; + cerr << '{'; + for (auto &&i : v) + cerr << (f++ ? "," : "") << (i ? "T" : "F"); + cerr << "}"; + } + template + void print(T &&x) + { + if constexpr (is_iterable) + if (size(x) && is_iterable) + { /* Iterable inside Iterable */ + int f = 0; + cerr << "\n~~~~~\n"; + for (auto &&i : x) + { + cerr << setw(2) << left << f++, print(i), cerr << "\n"; + } + cerr << "~~~~~\n"; + } + else + { /* Normal Iterable */ + int f = 0; + cerr << "{"; + for (auto &&i : x) + cerr << (f++ ? "," : ""), print(i); + cerr << "}"; + } + else if constexpr (requires { x.pop(); }) /* Stacks, Priority Queues, Queues */ + { + auto temp = x; + int f = 0; + cerr << "{"; + if constexpr (requires { x.top(); }) + while (!temp.empty()) + cerr << (f++ ? "," : ""), print(temp.top()), temp.pop(); + else + while (!temp.empty()) + cerr << (f++ ? "," : ""), print(temp.front()), temp.pop(); + cerr << "}"; + } + else if constexpr (requires { x.first; x.second; }) /* Pair */ + { + cerr << '(', print(x.first), cerr << ',', print(x.second), cerr << ')'; + } + else if constexpr (requires { get<0>(x); }) /* Tuple */ + { + int f = 0; + cerr << '(', apply([&f](auto... args) + { ((cerr << (f++ ? "," : ""), print(args)), ...); }, + x); + cerr << ')'; + } + else + cerr << x; + } + template + void printer(const char *names, T &&head, V &&...tail) + { + int i = 0; + for (size_t bracket = 0; names[i] != '\0' and (names[i] != ',' or bracket != 0); i++) + if (names[i] == '(' or names[i] == '<' or names[i] == '{') + bracket++; + else if (names[i] == ')' or names[i] == '>' or names[i] == '}') + bracket--; + cerr.write(names, i) << " = "; + print(head); + if constexpr (sizeof...(tail)) + cerr << " ||", printer(names + i + 1, tail...); + else + cerr << "]\n"; + } + template + void printerArr(const char *names, T arr[], size_t N, V... tail) + { + size_t i = 0; + for (; names[i] and names[i] != ','; i++) + cerr << names[i]; + for (i++; names[i] and names[i] != ','; i++) + ; + cerr << " = {"; + for (size_t ind = 0; ind < N; ind++) + cerr << (ind ? "," : ""), print(arr[ind]); + cerr << "}"; + if constexpr (sizeof...(tail)) + cerr << " ||", printerArr(names + i + 1, tail...); + else + cerr << "]\n"; + } + +} +#define deb(...) std::cerr << __LINE__ << ": [", __DEBUG_UTIL__::printer(#__VA_ARGS__, __VA_ARGS__) +#define debArr(...) std::cerr << __LINE__ << ": [", __DEBUG_UTIL__::printerArr(#__VA_ARGS__, __VA_ARGS__) \ No newline at end of file