├── .gitignore ├── Famous-Coding-Interview-Problems ├── JumpGame2.cpp ├── OopsAllConcepts.cpp ├── TheCoinChangeProblem.cpp ├── TheDuplicateXorArrayProblem-I.cpp ├── TheDuplicateXorArrayProblem-II.cpp ├── TheRecusriveStackProblem.cpp └── TheSplitwiseProblem.cpp ├── LeetCode ├── 1.two-sum.cpp ├── 121.best-time-to-buy-and-sell-stock.cpp ├── 1282.group-the-people-given-the-group-size-they-belong-to.cpp ├── 1288.remove-covered-intervals.cpp ├── 1302.deepest-leaves-sum.cpp ├── 1306.jump-game3.cpp ├── 1314.matrix-block-sum.cpp ├── 1371.find-the-longest-substring-containing-vowels-in-even-counts.cpp ├── 1402.reducing-dishes.cpp ├── 1409.queries-on-a-permutation-with-key.cpp ├── 155.min-stack.cpp ├── 1769.minimum-number-of-operations-to-move-all-balls-to-each-box.cpp ├── 3.longest-substring-without-repeating-characters.cpp ├── 3.longest-substring-without-repeating-characters.py ├── 322.coin-change.py ├── 39.combination-sum.cpp ├── 41.first-missing-positive.cpp ├── 41.first-missing-positive.py ├── 45.jump-game2.cpp ├── 476.number-complement.cpp ├── 53.maximum-subarray.cpp ├── 532.k-diff-pairs-in-an-array.cpp ├── 542.01-matrix.cpp ├── 55.jump-game.cpp ├── 647.panlindrmoic-substrings.cpp ├── 7.reverse-integer.cpp ├── 765.couples-holding-hands.cpp ├── 797.all-paths-from-source-to-target.cpp ├── 841.keys-and-room.cpp ├── 877.stone-game.cpp ├── 878.nth-magical-number.cpp ├── 878.nth-magical-number.py ├── 890.find-and-replace-patterns.cpp ├── 929.unique-email-address.cpp ├── 933.number-of-recent-calls.cpp └── 997.find-the-town-judge.cpp ├── Library ├── DP │ ├── dp-on-digits-tutorial.cpp │ └── dp-on-digits.cpp ├── DS │ ├── 2DBIT.cpp │ ├── 2dSparseTable.cpp │ ├── ConvexHulDynamicMin.cpp │ ├── ConvexHull.cpp │ ├── ConvexHullDynamicMax.cpp │ ├── ConvexHullDynamicMinMax.cpp │ ├── HV-Intersection-PBDS.cpp │ ├── MaxBIT_with_pos_track.cpp │ ├── UnionFind.cpp │ ├── bit.cpp │ ├── bitset.cpp │ ├── convex-hull-min-nikalsb.cpp │ ├── heap.cpp │ ├── persistent_segment_tree.cpp │ ├── points-in-rectangle-KDTREE.cpp │ ├── policy-based-set.cpp │ ├── segment_tree_on_map.cpp │ ├── segment_tree_point_update.cpp │ ├── sparse_table_2d.cpp │ ├── treap_reversal.cpp │ └── treaps.cpp ├── Graph │ ├── BCC.cpp │ ├── Dijkstra.cpp │ ├── Dijkstra_Khattar_Style.cpp │ ├── Euler_Circuit.cpp │ ├── MST.cpp │ └── MinCostMaxFlow.cpp ├── Math │ ├── FibGP.cpp │ ├── GP.cpp │ ├── MatrixPow.cpp │ ├── NcR.cpp │ ├── Seive │ │ ├── euler_phi.cpp │ │ ├── extended_gcd.cpp │ │ └── seive_totient.cpp │ ├── SmallestPrimeSeive.cpp │ ├── bigint.cpp │ ├── dec2bin.cpp │ ├── fact_ncr.cpp │ ├── geometry.cpp │ ├── linear_recurrence.cpp │ ├── matrix.cpp │ ├── matrix_math_operations.cpp │ ├── projecteuelr │ │ ├── Euler.py │ │ └── Miller-rabin-primality-test.cpp │ └── vector_physics.cpp ├── Miscellanious │ ├── 2-sat.cpp │ ├── MosMaxFrequency.cpp │ ├── RollingHash.cpp │ ├── SmallToLarge.cpp │ ├── fast_input.cpp │ ├── hash_adjaceny_list.cpp │ ├── hash_unordered_map.cpp │ ├── meet-in-middle.cpp │ ├── normal_round.cpp │ ├── overlapping_intervals.cpp │ ├── parallel_binary_search.cpp │ ├── popcount.cpp │ ├── range_sum.cpp │ ├── sliding_window.cpp │ ├── sliding_window_2.cpp │ ├── sos_dp.cpp │ ├── template-short.cpp │ ├── template.cpp │ ├── template2024.cpp │ ├── template_demo.cpp │ ├── ternary_search.cpp │ └── z-algo.cpp ├── Tree │ ├── Centroid.cpp │ ├── HLD.cpp │ ├── centroid_decomposition.cpp │ ├── centroid_example.cpp │ ├── dp-on-tree-type-c-LCA.cpp │ ├── lca.cpp │ ├── lca_in_out_dp.cpp │ ├── lca_sparse_min.cpp │ ├── trie-xor.cpp │ └── trie.cpp ├── Utils │ ├── bits │ │ └── stdc++.h │ ├── codeforces.sh │ └── logger.h └── galt │ └── 2Dsparse_table.cpp ├── MyOnlineSubmissions ├── Codechef │ ├── DEC17 │ │ └── CHEFEXQ.cpp │ ├── MAY20 │ │ └── CHANDF.cpp │ └── NOV17 │ │ └── CSUBQ.cpp ├── Google-CodeJam │ ├── 2019 │ │ ├── QualificationRound │ │ │ ├── Problem A.cpp │ │ │ ├── Problem B.cpp │ │ │ └── Problem C.cpp │ │ └── Round1C │ │ │ ├── Problem A[Robot Programming Strategy].cpp │ │ │ └── Problem B[Power Arrangers].cpp │ └── 2020 │ │ └── QualificationRound │ │ ├── A-Vestigium.cpp │ │ ├── B-NestingDepth.cpp │ │ ├── C-ParentingActivities.cpp │ │ └── D-interactive.cpp └── ProjectEuler │ ├── 63.py │ ├── 70.py │ └── 81.py ├── README.md └── Tricks ├── CacheStoreWithTTL.cpp ├── iterative-tree-traversal-1.cpp ├── iterative-tree-traversal-2.cpp └── tricky-oops-problem.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | # Temp Codeforces Contest Env 35 | CodeforcesContestRunner -------------------------------------------------------------------------------- /Famous-Coding-Interview-Problems/JumpGame2.cpp: -------------------------------------------------------------------------------- 1 | //https://www.youtube.com/watch?v=hZkb_Dqu7YY 2 | class Solution { 3 | public: 4 | int jump(vector& nums) { 5 | int n = nums.size(); 6 | if(n < 2) return 0; 7 | int maxIndexReachable = nums[0]; 8 | int ans = 1, lim = nums[0]; 9 | 10 | for(int i = 1; i < n; i++) { 11 | if(i > lim) { 12 | ans++; 13 | lim = maxIndexReachable; 14 | } 15 | maxIndexReachable = max(maxIndexReachable, i+nums[i]); 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Famous-Coding-Interview-Problems/OopsAllConcepts.cpp: -------------------------------------------------------------------------------- 1 | //Video explanation at : https://youtu.be/qsMahidcehY 2 | #include 3 | using namespace std; 4 | 5 | class A{ 6 | public: 7 | static int x; 8 | A(){ 9 | 10 | } 11 | ~A(){ 12 | 13 | } 14 | void* operator new(size_t sz) { 15 | x++; 16 | } 17 | }; 18 | 19 | int A::x = 0; 20 | 21 | int main() 22 | { 23 | A a, b; //local --> stack 24 | A c, d, e; 25 | 26 | //dynamic --> heap 27 | //A* ptr = (A*)malloc(sizeof(A)); //allocates memory, doesnt call ctor 28 | A* ptr = new A; //ctor as well 29 | A* ptr2 = new A; 30 | //free(ptr); //doesn't call the destructor 31 | delete ptr; // TO DO: overload delete and decrement counter.. 32 | 33 | 34 | cout << A::x << endl; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Famous-Coding-Interview-Problems/TheCoinChangeProblem.cpp: -------------------------------------------------------------------------------- 1 | //The Coin Change Problem 2 | //Given an Array of coins C, and money S, print number of ways to make a change for S 3 | //Eg: A=[1,2] S=4 answer is {1,1,1,1}, {2,2}, {2,1,1} i.e 3 ways 4 | #include 5 | using namespace std; 6 | 7 | const int N = 1e3; 8 | int A[N], n; 9 | int vis[N][N], dp[N][N]; 10 | 11 | int ways(int pos, int S) { 12 | if(pos == n) return S == 0; 13 | int &ans = dp[pos][S]; 14 | if(vis[pos][S]) return ans; vis[pos][S] = 1, ans = 0; 15 | int times = 0; 16 | while(times*A[pos] <= S) ans += ways(pos+1, S-times*A[pos]), times++; 17 | return ans; 18 | } 19 | 20 | //Faster than ways function as it causes only two transitions 21 | int fasterWays(int pos, int S) { 22 | if(pos == n) return S == 0; 23 | if(S < 0) return 0; 24 | int &ans = dp[pos][S]; 25 | if(vis[pos][S]) return ans; vis[pos][S] = 1, ans = 0; 26 | ans = ways(pos, S-A[pos]) + ways(pos+1, S); 27 | return ans; 28 | } 29 | 30 | int main() { 31 | 32 | int i, S; 33 | cin >> n >> S; 34 | for(i=0; i> A[i]; 35 | cout << fasterWays(0, S) << endl; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Famous-Coding-Interview-Problems/TheDuplicateXorArrayProblem-I.cpp: -------------------------------------------------------------------------------- 1 | //Given: An array A with all elements occuring twice except for x that occur once. 2 | //To Do: Find the element x O(1) space and O(N) time 3 | #include 4 | using namespace std; 5 | const int N = 1e6; 6 | int arr[N]; 7 | 8 | int main() { 9 | int n; 10 | cin >> n; 11 | 12 | int all = 0; 13 | for(int i=0; i> arr[i]; 15 | all ^= arr[i]; 16 | } 17 | 18 | cout << all << endl; 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Famous-Coding-Interview-Problems/TheDuplicateXorArrayProblem-II.cpp: -------------------------------------------------------------------------------- 1 | //Given: An array A with all elements occuring twice except for x and y that occur once. 2 | //To Do: Find the x and y in O(1) space and O(N) time 3 | #include 4 | using namespace std; 5 | const int N = 1e6; 6 | int arr[N]; 7 | 8 | bool hasBitSet(int n, int x) { 9 | int tem = n & (1<> n; 16 | 17 | int all = 0; 18 | int ans[2] = {0,0}; 19 | 20 | for(int i=0; i> arr[i]; 22 | all ^= arr[i]; 23 | } 24 | 25 | //assert(all != 0); 26 | int k = 0; 27 | while( hasBitSet(all, k) == 0 ) k++; 28 | 29 | //parition array into two sets: kth bit on v/s off 30 | for (int i=0; i en; 4 | int go(int lo, int hi) { 5 | if(lo+1 == hi) return 1; 6 | int mid = en[lo]; 7 | if(mid == hi) return 2*go(lo+1, hi-1); 8 | return go(lo, mid) + go(mid+1, hi); 9 | } 10 | 11 | //calculates the score of string S 12 | //This is solution of my YouTube video "The Recursive Stack Problem on Strings" 13 | int scoreOfParentheses(string &S) { 14 | int i, n = (int)S.size(); 15 | n = max(n, 1); 16 | en.resize(n, 0); 17 | stack s; 18 | for(i=0; i 3 | using namespace std; 4 | const int N = 1e6; 5 | int balance[N]; 6 | int main() 7 | { 8 | int i, n, m, u, v, w, poor, x, rich, y; 9 | cin >> n >> m; 10 | for(i=0; i> u >> v >> w; 12 | //u has to pay v an amount w 13 | balance[u] -= w; 14 | balance[v] += w; 15 | } 16 | 17 | multiset> S; 18 | for(i=0; i 9 | class Solution { 10 | public: 11 | vector twoSum(vector& nums, int target) { 12 | map id; 13 | for(int i = 0; i < nums.size(); i++) { 14 | int make = target - nums[i]; 15 | if(id[make]) { 16 | return {id[make]-1, i}; 17 | } 18 | id[nums[i]] = i+1; 19 | } 20 | return {-1, -1}; 21 | } 22 | }; 23 | // @lc code=end 24 | 25 | -------------------------------------------------------------------------------- /LeetCode/121.best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int n = prices.size(); 5 | int ans = 0, suff_max = prices.back(); 6 | for(int i = n-2; i >= 0; i--) { 7 | ans = max(ans, suff_max - prices[i]); 8 | suff_max = max(suff_max, prices[i]); 9 | /* 10 | for(int j = i+1; j < n; j++) { 11 | ans = max(ans, prices[j] - prices[i]); 12 | } 13 | */ 14 | } 15 | return ans; 16 | } 17 | }; 18 | /* 19 | <---100---> 20 | _ _ _ 120 _ _ _ _ _ _ 21 | i 22 | 23 | max = 100 24 | */ 25 | 26 | 27 | -------------------------------------------------------------------------------- /LeetCode/1282.group-the-people-given-the-group-size-they-belong-to.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> groupThePeople(vector& groupSizes) { 4 | int n = groupSizes.size(); 5 | unordered_map> peopleInGroupSize = {}; 6 | for(int i = 0; i < n; i++) { 7 | int curSize = groupSizes[i]; 8 | peopleInGroupSize[curSize].push_back(i); 9 | } 10 | vector> ans = {}; 11 | for(auto [groupSize, people]: peopleInGroupSize) { 12 | // start making groups of |groupSize| 13 | vector cur = {}; 14 | for(int i = 0; i < people.size(); i++) { 15 | cur.push_back(people[i]); 16 | if ( cur.size() == groupSize) { 17 | ans.push_back(cur); 18 | cur = {}; 19 | } 20 | } 21 | } 22 | return ans; 23 | } 24 | }; 25 | /* 26 | [group_size] --> [ids of people in it] 27 | [3] --> [0,1,2,3,4,6] 28 | [1] --> [5] 29 | */ -------------------------------------------------------------------------------- /LeetCode/1288.remove-covered-intervals.cpp: -------------------------------------------------------------------------------- 1 | using interval = vector; // length 2 2 | // [1, 3] and [1, 19] 3 | // [1, 19] can contain [1, 3] 4 | bool comparator(const interval &left, const interval &right) { 5 | if(left[0] == right[0]) 6 | return left[1] > right[1]; 7 | return left[0] < right[0]; // asc order of starting time 8 | } 9 | 10 | class Solution { 11 | public: 12 | int removeCoveredIntervals(vector& intervals) { 13 | sort(intervals.begin(), intervals.end(), comparator); 14 | int ans = intervals.size(); 15 | 16 | int maxEnd = 0; 17 | 18 | for(interval cur: intervals) { 19 | // need to check if cur is already contained 20 | int curEnd = cur[1]; 21 | if (curEnd <= maxEnd) { 22 | ans--; // throw away the current interval 23 | } 24 | 25 | maxEnd = max(maxEnd, curEnd); 26 | } 27 | 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /LeetCode/1302.deepest-leaves-sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | pair getDepthAndSum(TreeNode* root) { 14 | if (root == NULL) return {0, 0}; 15 | if (root->left == NULL and root->right == NULL) 16 | return {1, root->val}; 17 | 18 | auto [left_depth, left_sum] = getDepthAndSum(root->left); 19 | auto [right_depth, right_sum] = getDepthAndSum(root->right); 20 | 21 | if (left_depth == right_depth) 22 | return {1 + left_depth, left_sum + right_sum}; 23 | if (left_depth > right_depth) 24 | return {1 + left_depth, left_sum}; 25 | return {1 + right_depth, right_sum}; 26 | } 27 | public: 28 | int deepestLeavesSum(TreeNode* root) { 29 | return getDepthAndSum(root).second; 30 | } 31 | }; -------------------------------------------------------------------------------- /LeetCode/1306.jump-game3.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | vector nums; 3 | set s; // what all indices are there in recursion stack 4 | 5 | bool isPossible(int cur) { // can we reach a zero from cur index 6 | if (s.find(cur) != s.end()) { 7 | return false; // we detected a cycle / deadlock 8 | } 9 | if(0 <= cur && cur < nums.size()) { 10 | if(nums[cur] == 0) return true; 11 | s.insert(cur); 12 | bool ans = false; 13 | if (isPossible(cur + nums[cur])) ans = true; 14 | else if (isPossible(cur - nums[cur])) ans = true; 15 | s.erase(cur); 16 | return ans; 17 | } 18 | return false; 19 | } 20 | public: 21 | bool canReach(vector& arr, int start) { 22 | //dp[i] <-- is it possible to reach a zero from i 23 | nums = arr; 24 | return isPossible(start); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode/1314.matrix-block-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> matrixBlockSum(vector>& mat, int k) { 4 | int n = mat.size(), m = mat[0].size(); 5 | vector> ans(n, vector(m, 0)); 6 | vector> dp(n+1, vector(m+1, 0)); // 1-based indexing <-- prefix sums,˘ 7 | 8 | // compute the prefix sums 9 | for(int i = 1; i <= n; i++) { 10 | for(int j = 1; j <= m; j++) { 11 | dp[i][j] = mat[i-1][j-1] + dp[i][j-1] + dp[i-1][j] - dp[i-1][j-1]; 12 | } 13 | } 14 | 15 | for(int i = 0; i < n; i++) { 16 | for(int j = 0; j < m; j++) { 17 | // compute the ans for (i,j) 18 | int i1 = max(0, i-k), j1 = max(0,j-k); 19 | int i2 = min(n-1, i+k), j2 = min(m-1, j+k); 20 | i1++, i2++, j1++, j2++; //1-based indexing 21 | 22 | ans[i][j] = dp[i2][j2] - dp[i2][j1-1] - dp[i1-1][j2] + dp[i1-1][j1-1]; 23 | } 24 | },™ 25 | return ans; 26 | } 27 | }; 28 | 29 | /* 30 | prefix sum in 2d approach 31 | dp[i][j] = sum of rect from (0,0) to (i,j) as diagnal points 32 | => it helps me in computing any rectangle sum in O(1) 33 | (i1, j1) and (i2, j2) i1 < i2 and j1 < j2 34 | 35 | dp[i2][j2] - dp[i1][j1-1] - dp[i1-1][j2] + dp[i1-1][j1-1] 36 | 37 | 38 | 39 | prefix sums can be used for each row individually 40 | => for given row, sum(j-k, j+k) => O(1) 41 | j-k j j+k 42 | 43 | 44 | i-k 45 | 46 | 47 | 48 | i x 49 | 50 | 51 | 52 | i+k 53 | 54 | (i,j) => O(k^2) 55 | O(N^2k^2) 56 | O(N^2 k) 57 | 58 | 59 | 60 | 61 | k = 1 62 | [1,2,3], 63 | [4,5,6], 64 | [7,8,9] 65 | 66 | 9*10/2 = 45 67 | 68 | 5+6+8+9 = 28 69 | */ 70 | -------------------------------------------------------------------------------- /LeetCode/1371.find-the-longest-substring-containing-vowels-in-even-counts.cpp: -------------------------------------------------------------------------------- 1 | string vowels = "aeiou"; 2 | class Solution { 3 | public: 4 | int findTheLongestSubstring(string s) { 5 | int n = s.size(); 6 | int ans = 0; 7 | unordered_map> pref = {}; 8 | for (char v: vowels) pref[v] = {0}; 9 | 10 | for(char cur: s) { 11 | for(char v: vowels) { 12 | int last_parity = *pref[v].rbegin(); 13 | if (cur == v) pref[v].push_back(1 - last_parity); 14 | else pref[v].push_back(last_parity); 15 | } 16 | } 17 | 18 | auto get_column = [&](int j) { // 1 based 19 | int id = 0; 20 | for(char v: vowels) { 21 | int x = pref[v][j]; 22 | id = 2*id + x; 23 | } 24 | return id; 25 | }; 26 | 27 | int rightmost[33]; 28 | rightmost[0] = 0; 29 | for (int i = 1; i <= n; i++) { 30 | int id = get_column(i); 31 | rightmost[id] = i; 32 | } 33 | 34 | for (int i = 1; i <= n; i++) { 35 | // find the rightmost j substring(i, j) is valid 36 | // ith column 37 | int id = get_column(i-1); 38 | int j = rightmost[id]; 39 | if (j < i) continue; 40 | ans = max(ans, j-i+1); 41 | } 42 | return ans; 43 | } 44 | }; 45 | 46 | /* 47 | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 48 | i ^ ^ 49 | maintain prefix count of all vowels pref[a][7] 50 | a,b,a,e,e,a,e 51 | i j 52 | a - 0,1,1,0,0,0,1,1 53 | e - 0,0,0,0,1,0,0,1 54 | i - ...,1,.....,1 55 | o - ...,0,.....,1 56 | u - ...,0,.....,0 57 | 10100 <-- 20 58 | n^2 substrings -> O(n) => overall O(n^3) 59 | */ -------------------------------------------------------------------------------- /LeetCode/1402.reducing-dishes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSatisfaction(vector& arr) { 4 | int n = arr.size(); 5 | sort(arr.begin(), arr.end()); 6 | int ans = 0; 7 | for(int i = 0; i < n; i++) { 8 | int cur = 0; 9 | // considering the suffix from pos i 10 | // [arr[i], arr[i+1], ... arr[n-1]] 11 | // 1 2 12 | for(int j = i; j < n; j++) { 13 | cur += (j-i+1) * arr[j]; 14 | } 15 | ans = max(ans, cur); 16 | } 17 | return ans; 18 | } 19 | }; 20 | 21 | /* 22 | a1 <= a2 <= a3 .... // we have proved 23 | (a1,a2,...,ak) <-- reordering of satisfaction array + you can remove elements 24 | max(a1 + 2*a2 + 3*a3 + k*ak) 25 | 26 | -9 -8 -1 0 5 27 | 28 | how long a prefix would you remove to get the max score 29 | */ 30 | -------------------------------------------------------------------------------- /LeetCode/1409.queries-on-a-permutation-with-key.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector processQueries(vector& queries, int m) { 4 | unordered_map pos, rev_pos; // pos[3] - 10 => 3 occurs at index 10 5 | for(int i = 1; i <= m; i++) { 6 | pos[i] = i-1, rev_pos[i-1] = i; 7 | } 8 | 9 | vector ans = {}; 10 | for(int q: queries) { 11 | ans.push_back(pos[q]); 12 | // increment the pos of all nos from 0 to pos[q]-1 13 | for (int i = pos[q]-1 ; i >= 0; i--) { 14 | int cur = rev_pos[i]; 15 | pos[cur] = i+1; // shift to right side 16 | rev_pos[i+1] = cur; 17 | } 18 | pos[q] = 0; 19 | rev_pos[0] = q; 20 | } 21 | return ans; 22 | } 23 | }; 24 | // 1,2,3,4,5 25 | // 3,1,2,4,5 26 | 27 | // _ _ _ _ _ _ _ _ _ _ _ 28 | // ^ -------------------------------------------------------------------------------- /LeetCode/155.min-stack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | public: 3 | /** initialize your data structure here. */ 4 | vector a, b; 5 | MinStack() { 6 | a = b = {}; 7 | } 8 | 9 | void push(int x) { 10 | a.push_back(x); 11 | if(b.empty()) b.push_back(x); 12 | else { 13 | int newMin = min(x, *b.rbegin()); 14 | b.push_back(newMin); 15 | } 16 | } 17 | 18 | void pop() { 19 | a.pop_back(); 20 | b.pop_back(); 21 | } 22 | 23 | int top() { 24 | return *a.rbegin(); 25 | } 26 | 27 | int getMin() { 28 | return *b.rbegin(); 29 | } 30 | }; 31 | 32 | /** 33 | * Your MinStack object will be instantiated and called as such: 34 | * MinStack* obj = new MinStack(); 35 | * obj->push(x); 36 | * obj->pop(); 37 | * int param_3 = obj->top(); 38 | * int param_4 = obj->getMin(); 39 | */ 40 | -------------------------------------------------------------------------------- /LeetCode/1769.minimum-number-of-operations-to-move-all-balls-to-each-box.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector minOperations(string boxes) { 4 | int n = boxes.size(); 5 | int left_cnt = 0, tot_cnt = 0; // cnt of 1s 6 | int left_sum = 0, tot_sum = 0; // sum of indices where its a 1 7 | 8 | 9 | for(int i = 0; i < n; i++) { 10 | if (boxes[i] == '1') tot_cnt++, tot_sum += i; 11 | } 12 | 13 | vector ans = {}; 14 | for(int i = 0; i < n; i++) { 15 | int right_cnt = tot_cnt - left_cnt; 16 | int right_sum = tot_sum - left_sum; 17 | 18 | int left = left_cnt * i - left_sum; 19 | int right = right_sum - right_cnt * i; 20 | ans.push_back(left + right); 21 | 22 | if (boxes[i] == '1') left_cnt++, left_sum += i; 23 | } 24 | return ans; 25 | } 26 | }; 27 | 28 | 29 | /* 30 | i=13 31 | j<13 32 | i-j1 + i-j2 => 2*i - (j1+j2) 33 | 34 | j>13 35 | j1-i + j2-i => (j1+j2) - 2 *(i) 36 | */ 37 | 38 | -------------------------------------------------------------------------------- /LeetCode/3.longest-substring-without-repeating-characters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=3 lang=cpp 3 | * 4 | * [3] Longest Substring Without Repeating Characters 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int lengthOfLongestSubstring(string s) { 11 | int n = s.size(); 12 | if(s.size()==0)return 0; 13 | int i,j; 14 | i=0, j=0; 15 | vector cnt(326, 0); 16 | cnt[s[0]]++; 17 | int ans=1; 18 | while(1){ 19 | if(j==n-1) break; 20 | if(cnt[s[j+1]] == 0) j++, cnt[s[j]]++, ans=max(ans,j-i+1); 21 | else { 22 | cnt[s[i++]]--; 23 | } 24 | } 25 | return ans; 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /LeetCode/3.longest-substring-without-repeating-characters.py: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | if(s.size()==0)return 0; // did you handle this? 5 | int n = s.size(); 6 | int i(0), j(0); 7 | 8 | // s[j] is a char, 'A' is 65, 'a' is 97 9 | vector cnt(300, 0); // ASCII length of 255 will be fine 10 | cnt[s[0]]++; // this can crash if string is empty 11 | 12 | int ans=1; 13 | while(j!=n-1){ 14 | if(cnt[s[j+1]] == 0) { 15 | j++; 16 | cnt[s[j]] = 1; 17 | ans = max(ans, j-i+1); 18 | } 19 | else { 20 | i++; 21 | cnt[s[i]]--; 22 | } 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode/322.coin-change.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode id=322 lang=python3 3 | # 4 | # [322] Coin Change 5 | # 6 | 7 | # @lc code=start 8 | INF = 10 ** 7 9 | class Solution: 10 | def coinChange(self, C: List[int], S: int) -> int: 11 | noCoins = len(C) 12 | dp = [[INF for _ in range(noCoins+1)] for _ in range(S+1)] 13 | # dp[i][j] is min coins needed to make sum "i" when first "j" coins are available 14 | dp[0][0] = 0 # no coin needed to make 0 15 | for i in range(0, S+1): 16 | for j in range(1, noCoins+1): 17 | curCoin = C[j-1] # 0-based indexing 18 | 19 | # Case A: I don't take jth coin 20 | dp[i][j] = dp[i][j-1] 21 | 22 | # Case B: I take jth coin 23 | if curCoin <= i: 24 | dp[i][j] = min(dp[i][j], 1 + dp[i-curCoin][j]) 25 | return dp[S][noCoins] if dp[S][noCoins] != INF else -1 26 | 27 | # @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /LeetCode/39.combination-sum.cpp: -------------------------------------------------------------------------------- 1 | using choice = vector; 2 | vector arr = {}; 3 | 4 | // returning all possible choices to make target sum by using suffix of array [curIndex, ...] 5 | vector getAllChoices(int curIndex, int target) { 6 | // base case 7 | if(target < 0) return {}; // no valid choice 8 | if(target == 0) return {{}}; // one choice, and you chose nothing 9 | if(curIndex == arr.size()) return {}; 10 | 11 | int curNumber = arr[curIndex]; 12 | 13 | vector ans = getAllChoices(curIndex+1, target); // curNumber is not used at all 14 | 15 | vector other = getAllChoices(curIndex, target - curNumber); // using it once 16 | for(choice c: other) { 17 | c.push_back(curNumber); 18 | // now c is a valid choice 19 | ans.push_back(c); 20 | } 21 | 22 | return ans; 23 | } 24 | 25 | class Solution { 26 | 27 | public: 28 | vector combinationSum(vector& candidates, int target) { 29 | arr = candidates; 30 | return getAllChoices(0, target); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /LeetCode/41.first-missing-positive.cpp: -------------------------------------------------------------------------------- 1 | // Check Youtube video for video explanation 2 | class Solution { 3 | public: 4 | int firstMissingPositive(vector A) 5 | { 6 | int n = A.size(); 7 | for(int i = 0; i < n; ++ i) { 8 | while(A[i] >= 1 && A[i] <= n && A[i] != A[A[i]-1]) 9 | swap(A[i], A[A[i] - 1]); 10 | } 11 | 12 | for(int i = 0; i < n; ++ i) 13 | if(A[i] != i + 1) 14 | return i + 1; 15 | 16 | return n + 1; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LeetCode/41.first-missing-positive.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | for i in range(n): 5 | correctPos = nums[i]-1 # number 3 goes to index 2 6 | while 1 <= nums[i] <= n and nums[i] != nums[correctPos]: 7 | nums[i], nums[correctPos] = nums[correctPos], nums[i] 8 | correctPos = nums[i]-1 # now nums[i] has changed 9 | 10 | 11 | for i in range(n): 12 | if i+1 != nums[i]: 13 | return i+1 14 | return n+1 15 | -------------------------------------------------------------------------------- /LeetCode/45.jump-game2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jump(vector& nums) { 4 | int n = nums.size(); 5 | vector dp(n, INT_MAX - 1); 6 | // dp[i] = min steps to reach the end of array if we are at ith index 7 | dp[n-1] = 0; 8 | for(int i = n-2; i >= 0; i--) { 9 | for(int j = i+1; j <= i+nums[i]; j++) { 10 | if(j >= n) break; 11 | dp[i] = min(dp[i], 1 + dp[j]); 12 | } 13 | } 14 | 15 | return dp[0]; 16 | } 17 | }; 18 | 19 | /* 20 | Find: min steps to reach the end of array 21 | 22 | Given: i -> we can jump a length of nums[i] 23 | 0 index 24 | 25 | _ _ _ _ 7 _ _ _ _ _ _ _ _ _ 26 | i x x x x x x x 27 | 28 | dp[i] = min steps to reach the end of array if we are at ith index 29 | 30 | for(j=i+1; j<=i+7; j++) { 31 | dp[i] = min(dp[i], 1 + dp[j]); 32 | } 33 | 34 | return dp[0] 35 | */ 36 | -------------------------------------------------------------------------------- /LeetCode/476.number-complement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bitwiseComplement(int n) { 4 | if(n == 0) return 1; 5 | int numberOfBits = log2(n) + 1; // 100 log10(100) => 2+1 => 3 6 | int mask = (1 << numberOfBits) - 1; // pow(2, numberOfBits) 7 | return mask ^ n; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /LeetCode/53.maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(vector& nums) { 4 | int n = nums.size(); 5 | int ans = INT_MIN; 6 | 7 | // vector dp(n+1, 0); // O(N) extra space 8 | // dp[i] = max subarray sum starting from index i 9 | // mandate to pick something 10 | int nextMax = 0; 11 | for(int i = n-1; i >= 0; i--) { 12 | // dp[i] = max(nums[i] + dp[i+1], 0) 13 | // dp[i] = nums[i] + max(dp[i+1], 0); 14 | int curMax = nums[i] + max(nextMax, 0); 15 | ans = max(ans, curMax); 16 | nextMax = curMax; 17 | } 18 | 19 | return ans; 20 | } 21 | }; 22 | 23 | /* 24 | _ _ _ _ _ 100 _ _ _ _ _ 25 | i ^ 26 | dp[i] = max(nums[i] + dp[i+1], 0) 27 | */ 28 | -------------------------------------------------------------------------------- /LeetCode/532.k-diff-pairs-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | using hashmap = unordered_map; 2 | 3 | class Solution { 4 | public: 5 | int findPairs(vector& nums, int k) { 6 | hashmap cnt; 7 | for(int x: nums) cnt[x]++; 8 | 9 | int ans = 0; 10 | for(auto p: cnt) { // iterating on unique numbers of the array 11 | int x = p.first; 12 | // check x+k exists in the array 13 | if(cnt.find(x+k) == cnt.end()) { 14 | continue; 15 | } 16 | ans += (k==0) ? cnt[x+k] >= 2 : cnt[x+k] >= 1; 17 | } 18 | 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/542.01-matrix.cpp: -------------------------------------------------------------------------------- 1 | using loc = pair; 2 | int dx[] = {1, -1, 0, 0}; 3 | int dy[] = {0, 0, 1, -1}; 4 | class Solution { 5 | public: 6 | vector> updateMatrix(vector>& mat) { 7 | int n = mat.size(), m = mat[0].size(); 8 | 9 | vector> dis(n, vector(m, INT_MAX)); 10 | // dis[i][j] = nearest distance (i, j) to nearest 0 11 | 12 | queue q; 13 | for(int i = 0; i < n; i++) { 14 | for(int j = 0; j < m; j++) { 15 | if (mat[i][j] == 0) { 16 | q.push({i, j}); 17 | dis[i][j] = 0; 18 | } 19 | } 20 | } 21 | 22 | while(!q.empty()) { 23 | // loc cur = q.front(); 24 | // int x = cur.first, y = cur.second; 25 | auto [x, y] = q.front(); // current loc in mat, structured binding in C++ 26 | q.pop(); 27 | // (2,3) -> (1, 3) up, (3, 3) down, +1 -1 on the columns as well 28 | for(int k = 0; k < 4; k++) { 29 | int nx = x + dx[k], ny = y + dy[k]; 30 | if (0 <= nx && nx < n && 0 <= ny && ny < m) { 31 | // valid neighbour 32 | if (dis[nx][ny] == INT_MAX) { 33 | dis[nx][ny] = 1 + dis[x][y]; 34 | q.push({nx, ny}); 35 | } 36 | } 37 | } 38 | } 39 | 40 | return dis; 41 | } 42 | }; 43 | 44 | /* 45 | // BFS gives the shortest path in unweighted graphs 46 | 47 | n * m <--- 0s and 1s 48 | 49 | for every 1: 50 | compute the smallest distance to 0 51 | 52 | dis[i][j] = 0 where mat[i][j] = 0 53 | 54 | queue<> Q = {(i,j)} where mat[i][j] = 0; 55 | 56 | cur = Q.front(); 57 | 58 | for(nei in neighbors(cur)) { 59 | dis[nei] = 1 + dis[cur] if nei is not alreaady in queue 60 | } 61 | 62 | */ 63 | 64 | -------------------------------------------------------------------------------- /LeetCode/55.jump-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int n = nums.size(); 5 | vector allowed(n, 0); // O(n) extra space 6 | allowed[0] = 1; 7 | for (int i = 0; i < n; i++) { 8 | if (allowed[i]) { 9 | for(int j = min(n-1, i+nums[i]); j >= i+1; j--) { 10 | if(allowed[j]) break; 11 | allowed[j] = 1; 12 | } 13 | } 14 | } 15 | return allowed[n-1]; 16 | } 17 | }; 18 | 19 | /* 20 | _ _ _ 7 _ _ 1 1 1 1 1 _ 21 | i x x x x x x x 22 | 23 | if i is allowerd and 100 24 | i+1,i+2,...,i+100 <-- allowed 25 | 26 | whether n-1 is allowed <-- true / false 27 | 28 | */ 29 | 30 | 31 | -------------------------------------------------------------------------------- /LeetCode/647.panlindrmoic-substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countSubstrings(string s) { 4 | int n = s.size(); 5 | vector> dp(n, vector(n, 0)); 6 | for(int i = 0; i < n; i++) 7 | dp[i][i] = 1; 8 | 9 | // fill this dp 10 | for(int len = 2; len <= n; len++) { 11 | for(int i = 0; i + len - 1 < n; i++) { 12 | // starting from i, and length len 13 | int j = i + len - 1; 14 | if (i+1 == j) { 15 | dp[i][j] = s[i] == s[j]; 16 | } 17 | else { 18 | dp[i][j] = s[i] == s[j] && dp[i+1][j-1]; 19 | } 20 | } 21 | } 22 | 23 | int ans = 0; 24 | for(int i = 0; i < n; i++) 25 | for(int j = 0; j < n; j++) 26 | ans += dp[i][j]; 27 | return ans; 28 | } 29 | }; 30 | /* 31 | for substring in all_subtrings; 32 | if palindrome(substring) 33 | ans++; 34 | 35 | 36 | dp[i][j] = substring(i, i+1, ..., j) = is this a palindrome 37 | 38 | s[i] == s[j] && dp[i+1][j-1] should be true 39 | */ -------------------------------------------------------------------------------- /LeetCode/7.reverse-integer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=7 lang=cpp 3 | * 4 | * [7] Reverse Integer 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int reverse(int x) { 11 | long long rev = 0; 12 | long long limit = (1LL<<31); 13 | while(x) { 14 | int d = x%10; 15 | x /= 10; 16 | rev = 10*rev + d; 17 | } 18 | if(rev >= limit or rev < -limit) 19 | return 0; 20 | return rev; 21 | } 22 | }; 23 | // @lc code=end 24 | 25 | -------------------------------------------------------------------------------- /LeetCode/765.couples-holding-hands.cpp: -------------------------------------------------------------------------------- 1 | const int N = 70; 2 | set g[N]; 3 | bool vis[N]; 4 | 5 | void fill_cluster_size(int u, int &cluster_size) { 6 | vis[u] = 1; 7 | // cout << "dfs::at couple " << u << endl; 8 | cluster_size++; 9 | for(int v: g[u]) { 10 | if(!vis[v]) { 11 | fill_cluster_size(v, cluster_size); 12 | } 13 | } 14 | } 15 | 16 | int get_couple_id(int person) { 17 | return person / 2; 18 | } 19 | 20 | 21 | class Solution { 22 | public: 23 | int minSwapsCouples(vector& row) { 24 | int n = row.size() / 2; 25 | // normalizing the seating arrangement in terms of couple ids 26 | for(int &x: row) x = get_couple_id(x); 27 | 28 | for(int i = 0; i < n; i++) { 29 | g[i].clear(); 30 | vis[i] = 0; 31 | } 32 | 33 | for(int i = 0; i < row.size(); i += 2) { 34 | int c1 = row[i], c2 = row[i+1]; 35 | if( c1 == c2 ) continue; 36 | g[c1].insert(c2); 37 | g[c2].insert(c1); 38 | // cout << i << " adding edge in couple " << c1 << " " << c2 << endl; 39 | } 40 | 41 | int ans = 0; 42 | for(int i = 0; i < n; i++) { 43 | if(!vis[i]) { 44 | int cluster_size = 0; 45 | fill_cluster_size(i, cluster_size); 46 | ans += cluster_size - 1; 47 | } 48 | } 49 | return ans; 50 | } 51 | }; 52 | /* 53 | 0,3,1,2 -> 0,1,3,2 54 | easy notation: 0,1,0,1 55 | - Find a swap that can make two couples happy. 56 | - 57 | (0, 1) --- 1st couple --- couple id = 0 58 | (2, 3) --- 2nd couple --- couple id = 1 59 | (4, 5) -- 3rd couple --- couple id = 2 60 | 0,3,5,2,1,4 --> 0,1,2,1,0,2 61 | 62 | 0---1---2 63 | \______/ 64 | 65 | x----y <--- 1 swap 66 | x----y----z <--- 2 swaps 67 | 68 | C couples --- C-1 swaps 69 | */ 70 | -------------------------------------------------------------------------------- /LeetCode/797.all-paths-from-source-to-target.cpp: -------------------------------------------------------------------------------- 1 | const int N = 20; 2 | vector g[N]; 3 | using path = vector; 4 | set get_all_paths(int src, int tar) { 5 | // cout << src << endl; 6 | if(src == tar) return { {tar} }; 7 | set ans = {}; 8 | for(int v: g[src]) { 9 | auto rem_paths = get_all_paths(v, tar); 10 | for (path p: rem_paths) { 11 | p.push_back(src); 12 | ans.insert(p); 13 | } 14 | } 15 | return ans; 16 | } 17 | 18 | 19 | class Solution { 20 | 21 | public: 22 | 23 | vector> allPathsSourceTarget(vector>& graph) { 24 | // paths from 0 to 4 25 | // iterate on children v of 0 26 | // find paths from child v to 4 27 | // [0,1,3,4] 28 | int n = graph.size(); 29 | 30 | if(n == 0) return {}; 31 | for(int i = 0; i < n; i++) g[i].clear(); 32 | 33 | for(int i = 0; i < n; i++) { 34 | for(int v: graph[i]) { 35 | g[i].push_back(v); 36 | } 37 | } 38 | 39 | vector ans = {}; 40 | set paths = get_all_paths(0, n-1); 41 | 42 | 43 | // O(# of paths * avg_size of path) 44 | for(auto p: paths) { 45 | reverse(p.begin(), p.end()); 46 | ans.push_back(p); 47 | } 48 | 49 | return ans; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /LeetCode/841.keys-and-room.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canVisitAllRooms(vector>& rooms) { 4 | int n = rooms.size(); 5 | vector vis(n, 0); 6 | 7 | queue q; 8 | q.push(0); 9 | vis[0] = 1; 10 | while(!q.empty()) { 11 | int cur = q.front(); 12 | q.pop(); 13 | for(int child: rooms[cur]) { 14 | if (!vis[child]) { 15 | vis[child] = 1; 16 | q.push(child); 17 | } 18 | } 19 | } 20 | for(int i = 0; i < n; i++) { 21 | if(!vis[i]) return 0; 22 | } 23 | return 1; 24 | } 25 | }; 26 | 27 | /* 28 | Input: [[1,3],[3,0,1],[2],[0]] 29 | 0 --> 1 30 | | 31 | | 32 | 3 33 | */ 34 | -------------------------------------------------------------------------------- /LeetCode/877.stone-game.cpp: -------------------------------------------------------------------------------- 1 | #define deb(x1, x2, x3) cout << #x1 << "=" << x1 << " " << #x2 << "=" << x2 << " "<< #x3 << "=" << x3 << endl; 2 | 3 | class Solution { 4 | public: 5 | bool stoneGame(vector& piles) { 6 | int n = piles.size(); 7 | // dp[i][j] = max profit for first player when the game is at state [i..j] 8 | vector> dp(n, vector(n, 0)); 9 | for(int i = 0; i < n; i++) { 10 | dp[i][i] = piles[i]; // 1 size subarrays have been computed 11 | // if(i+1 < n) { 12 | // dp[i][i+1] = abs(piles[i] - piles[i+1]); // subarrays of size 2 13 | // } 14 | } 15 | for(int len = 2; len <= n; len++) { 16 | for(int i = 0; i < n; i++) { 17 | int j = i + len - 1; 18 | if(j >= n) continue; 19 | // i .. j 20 | // take the Lth stone 21 | int choice1 = piles[i] - dp[i+1][j]; 22 | 23 | // take the Rth stone 24 | int choice2 = piles[j] - dp[i][j-1]; 25 | dp[i][j] = max(choice1, choice2); 26 | // cout << i << " " << j << " " << dp[i][j] << endl; 27 | // deb(i, j, dp[i][j]); 28 | } 29 | } 30 | 31 | 32 | return dp[0][n-1] > 0; 33 | } 34 | }; 35 | 36 | /* 37 | 5, 3, 4, 5 -> 3,4,5 -> 3,4 -> 3 38 | 39 | 5 40 | <---------------------->17 ==> 17 - 5 = 12 41 | 23,....................,17 42 | 23<----------------------> ===> 23-7 = 16 43 | 7 44 | 45 | 46 | state = [L, R] => by how much quantity the first player wins 47 | 48 | 49 | [0, n-1] => +ve => first player can win -> true 50 | [0, n-1] => -ve => first player cant win -> false 51 | 52 | // take the Lth stone 53 | choice1 = piles[L] - win(L+1, R) 54 | 55 | // take the Rth stone 56 | choice2 = piles[R] - win(L, R-1) 57 | 58 | win(L, R) = max(choice1, choice2); 59 | 60 | return win(0, n-1) > 0 61 | 62 | */ 63 | 64 | -------------------------------------------------------------------------------- /LeetCode/878.nth-magical-number.cpp: -------------------------------------------------------------------------------- 1 | int countMultiples(long long x, long long a, long long b) { 2 | // get # of multiples of a or b in range [1, x] 3 | long long lcm = a * b / __gcd(a, b); 4 | return x/a + x/b - x/lcm; 5 | } 6 | 7 | class Solution { 8 | public: 9 | int nthMagicalNumber(int n, int a, int b) { 10 | // a = 2, b = 3 in our example 11 | long long lo = 1, hi = min(a, b) * 1LL * n, mod = 1e9 + 7; 12 | while(lo < hi) { 13 | long long mid = lo + (hi - lo) / 2; 14 | if (countMultiples(mid, a, b) < n) 15 | lo = mid + 1; 16 | else 17 | hi = mid; 18 | } 19 | return hi % mod; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/878.nth-magical-number.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def countMultiples(x, a, b): 4 | '''returns # of multiples of a or b in range [1, x]''' 5 | lcm = a * b // math.gcd(a, b) 6 | return x//a + x//b - x//lcm # x/2 + x/3 - x/6 7 | 8 | class Solution: 9 | def nthMagicalNumber(self, n: int, a: int, b: int) -> int: 10 | # a = 2, b = 3 in our case 11 | lo, hi = 1, min(a, b) * n # hi = 2*n remember? 12 | while lo < hi: 13 | mid = (lo + hi) >> 1 14 | if countMultiples(mid, a, b) < n: 15 | lo = mid + 1 16 | else: 17 | hi = mid 18 | 19 | return hi % (10**9 + 7) 20 | 21 | -------------------------------------------------------------------------------- /LeetCode/890.find-and-replace-patterns.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | bool matches(string word, string pattern) { 3 | int n = word.size(); 4 | vector forward(26, -1), backward(26, -1); 5 | // map forward, backward; unordered_map 6 | for(int i = 0; i < n; i++) { 7 | int x = word[i] - 'a', y = pattern[i] - 'a'; 8 | // I am trying to map x to y 9 | if(forward[x] != -1 && forward[x] != y) return false; 10 | if(backward[y] != -1 && backward[y] != x) return false; 11 | forward[x] = y; 12 | backward[y] = x; 13 | } 14 | 15 | return true; 16 | } 17 | 18 | public: 19 | vector findAndReplacePattern(vector& words, string pattern) { 20 | vector ans = {}; 21 | // O(n * k) k is avg word size 22 | for (auto word: words) { 23 | if (matches(word, pattern)) ans.push_back(word); 24 | } 25 | 26 | return ans; 27 | } 28 | }; 29 | 30 | /* abb xyy yxx 31 | 32 | // abbccc 33 | // matches - xyyzzz yzzxxx 34 | // does not match - xyyxxx 35 | 36 | abbccc yzzxxx 37 | abbccc xyyxxx 38 | 39 | if a is mapped to y, then - 40 | - a shall never be mapped to anything else 41 | - no other char shall be mapped to y 42 | 43 | math background - 44 | 1:1 mapping 45 | */ -------------------------------------------------------------------------------- /LeetCode/929.unique-email-address.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | string get_normalized(string email) { 3 | int i; 4 | string local_name = ""; 5 | bool ignore_chars = false; 6 | for(i = 0; i < email.size(); i++) { 7 | char c = email[i]; 8 | if (c == '@') { 9 | break; 10 | } 11 | 12 | if (c == '.' || ignore_chars) continue; 13 | if (c == '+') { 14 | ignore_chars = true; 15 | continue; 16 | } 17 | 18 | local_name += c; 19 | } 20 | string domain = email.substr(i); 21 | return local_name + domain; 22 | } 23 | public: 24 | int numUniqueEmails(vector& emails) { 25 | set email_set; 26 | for(string email: emails) { 27 | email_set.insert(get_normalized(email)); 28 | } 29 | 30 | return email_set.size(); 31 | } 32 | }; -------------------------------------------------------------------------------- /LeetCode/933.number-of-recent-calls.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class RecentCounter { 4 | deque req; 5 | public: 6 | RecentCounter() { 7 | req = {}; 8 | } 9 | 10 | int ping(int t) { 11 | req.push_back(t); 12 | while(req.front() < t-3000) req.pop_front(); 13 | return req.size(); 14 | } 15 | }; 16 | 17 | /** 18 | * Your RecentCounter object will be instantiated and called as such: 19 | * RecentCounter* obj = new RecentCounter(); 20 | * int param_1 = obj->ping(t); 21 | */ 22 | -------------------------------------------------------------------------------- /LeetCode/997.find-the-town-judge.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findJudge(int n, vector>& trust) { 4 | vector followers(n+1, 0); // 1 based indexing 5 | vector does_follow(n+1, 0); 6 | 7 | map followers, does_follow; // O(logN) 8 | 9 | for(auto edge: trust) { 10 | int u = edge[0], v = edge[1]; 11 | // person u trusts v 12 | followers[v]++; // O(1) v/s in maps O(logN) --> O(1) 13 | does_follow[u] = 1; 14 | } 15 | 16 | vector final_candidates = {}; 17 | for(int i = 1; i <= n; i++) { 18 | if(followers[i] == n-1 && does_follow[i] == 0) { 19 | final_candidates.push_back(i); 20 | } 21 | } 22 | 23 | if(final_candidates.size() != 1) return -1; 24 | return final_candidates[0]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Library/DP/dp-on-digits-tutorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int N = 1003; 5 | int n, m, a[N][N], dp[N][N], vis[N][N]; 6 | 7 | //Returns the max sum you can achieve 8 | //when you start at (i,j) and end at (n-1, m-1) 9 | //and move only in down and right directions 10 | int go(int i, int j){ 11 | if(i == n-1 and j == m-1) 12 | return a[i][j]; 13 | 14 | if(vis[i][j]) return dp[i][j]; 15 | 16 | vis[i][j] = 1; 17 | 18 | int &ans = dp[i][j]; 19 | 20 | if(i> n >> m; 33 | 34 | for(i = 0; i < n; i++) 35 | for(j = 0; j < m; j++) 36 | cin >> a[i][j]; 37 | 38 | //Display the matrix 39 | for(i = 0; i < n; i++){ 40 | for(j = 0; j < m; j++) 41 | cout << a[i][j] << "\t"; 42 | cout << endl; 43 | } 44 | 45 | //Print the answer 46 | cout << go(0, 0) << endl; 47 | //It should be 73 i.e 1+5+9+13+14+15+16 48 | 49 | 50 | return 0; 51 | 52 | } 53 | 54 | //Input: 55 | //4 4 56 | //1 2 3 4 57 | //5 6 7 8 58 | //9 10 11 12 59 | //13 14 15 16 60 | -------------------------------------------------------------------------------- /Library/DP/dp-on-digits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int vis[20][200]; 4 | long long dp[20][200]; 5 | 6 | //nos such that their # of digits <= X and digit sum = S 7 | long long count(int dig, int S){ 8 | 9 | if(dig == 0 or S < 0) return 0; 10 | if(S == 0) return 1; 11 | if(dig == 1) return S <= 9; 12 | 13 | long long &ans = dp[dig][S]; 14 | if(vis[dig][S]) return ans; 15 | vis[dig][S] = 1; 16 | ans = 0; 17 | 18 | for(int i = 0; i <= 9; i++) ans += count(dig-1, S-i); 19 | 20 | return ans; 21 | } 22 | 23 | //nos < X with digit sum S 24 | long long go(long long X, int S){ 25 | string x = to_string(X); 26 | long long ans = 0; 27 | 28 | int remLen = x.size()-1; 29 | 30 | for(char c: x){ 31 | int currDig = c-'0'; 32 | 33 | //The first digit position where they differ is "i" 34 | for(int i = 0; i < currDig; i++){ 35 | ans += count(remLen, S-i); 36 | } 37 | 38 | //Update the remaining lenght as well as the S 39 | //S is updated because currDig i.e x[i] is added to the prefix as 40 | //the next position where they differ will be i+1. 41 | remLen--; 42 | S -= currDig; 43 | } 44 | 45 | return ans; 46 | 47 | } 48 | 49 | int main() { 50 | long long L = 100, R = 1000, S = 13; 51 | cout << go(R+1, S)-go(L, S) << "<" << endl; 52 | // cout << count(3, 10) << " " << count(1, 8) << endl; 53 | int i, ans = 0; 54 | auto digsum = [](int x){ 55 | int s = 0; 56 | while(x) s+=x%10, x/=10; 57 | return s; 58 | 59 | }; 60 | for(i=L; i<=R; i++) ans += digsum(i)==S; 61 | cout < m) 38 | break; 39 | dp[i][j][k][0] = max(dp[i][j][k - 1][0], dp[i][j + nval][k - 1][0]); 40 | } 41 | } 42 | } 43 | Fo(j, 0, m) 44 | { 45 | Fo(k, 1, lg) 46 | { 47 | int val = (1 << k); 48 | int nval = val / 2; 49 | Fo(i, 0, n) 50 | { 51 | if (i + val > n) 52 | break; 53 | dp[i][j][0][k] = max(dp[i][j][0][k - 1], dp[i + nval][j][0][k - 1]); 54 | } 55 | } 56 | } 57 | int k1,k2,st2; 58 | 59 | int st1=st2=lg-1; 60 | 61 | Fo(k1, 1, st1 + 1) 62 | { 63 | int val1 = (1 << k1); 64 | int nval1 = val1 / 2; 65 | Fo(k2, 1, st2 + 1) 66 | { 67 | int val2 = (1 << k2); 68 | int nval2 = val2 / 2; 69 | Fo(i, 0, n) 70 | { 71 | Fo(j, 0, m) 72 | { 73 | if ((j + val1 > m) || (i + val2 > n)) 74 | continue; 75 | 76 | 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]); 77 | } 78 | } 79 | } 80 | } 81 | 82 | } 83 | 84 | int query(int i, int j, int down, int k){ 85 | int dx = down - i + 1; 86 | int dy = k - j + 1; 87 | int k1 = st[dy]; 88 | int k2 = st[dx]; 89 | int val1 = (1 << k1); 90 | int val2 = (1 << k2); 91 | int dp1 = max(dp[i][j][k1][k2], dp[i][k-val1+1][k1][k2]); 92 | int dp2 = max(dp[down - val2 + 1][j][k1][k2], dp[down - val2 + 1][k - val1 + 1][k1][k2]); 93 | return max(dp1,dp2); 94 | 95 | } 96 | -------------------------------------------------------------------------------- /Library/DS/ConvexHulDynamicMin.cpp: -------------------------------------------------------------------------------- 1 | struct cht{ 2 | struct Line{ 3 | int a; 4 | long long b; 5 | long long val; 6 | double xLeft; 7 | bool type; 8 | Line(long long _a = 0 , long long _b = 0){ 9 | a = _a; 10 | b = _b; 11 | xLeft = -1e16; 12 | type = 0; 13 | val = 0; 14 | } 15 | long long valueAt(int x) const{ 16 | return 1LL * a * x + b; 17 | } 18 | friend bool areParallel(const Line &l1, const Line &l2){ 19 | return l1.a == l2.a; 20 | } 21 | friend double intersectX(const Line &l1 , const Line &l2){ 22 | return areParallel(l1 , l2) ? 1e16 : 1.0 * (l2.b - l1.b) / (l1.a - l2.a); 23 | } 24 | bool operator < (const Line &l2) const{ 25 | if(!l2.type) 26 | return a < l2.a; 27 | return xLeft > l2.val; 28 | } 29 | }; 30 | set < Line > hull; 31 | bool hasPrev(set < Line > :: iterator it){ 32 | return it != hull.begin(); 33 | } 34 | bool hasNext(set < Line > :: iterator it){ 35 | return it != hull.end() && next(it) != hull.end(); 36 | } 37 | bool irrelevant(const Line &l1 , const Line &l2 , const Line &l3){ 38 | return intersectX(l1,l3) <= intersectX(l1,l2); 39 | } 40 | bool irrelevant(set < Line > :: iterator it){ 41 | return hasPrev(it) && hasNext(it) && (irrelevant(*next(it) , *it , *prev(it))); 42 | } 43 | set < Line > :: iterator updateLeftBorder(set < Line > :: iterator it){ 44 | if(!hasNext(it)){ 45 | return it; 46 | } 47 | double val = intersectX(*it , *next(it)); 48 | Line buf(*it); 49 | it = hull.erase(it); 50 | buf.xLeft = val; 51 | it = hull.insert(it, buf); 52 | return it; 53 | } 54 | void addLine(int a , long long b){ 55 | Line l3 = Line(a, b); 56 | auto it = hull.lower_bound(l3); 57 | if(it != hull.end() && areParallel(*it , l3)){ 58 | if(it -> b > b){ 59 | it = hull.erase(it); 60 | } 61 | else{ 62 | return; 63 | } 64 | } 65 | it = hull.insert(it, l3); 66 | if(irrelevant(it)){ 67 | hull.erase(it); 68 | return; 69 | } 70 | while(hasPrev(it) && irrelevant(prev(it))){ 71 | hull.erase(prev(it)); 72 | } 73 | while(hasNext(it) && irrelevant(next(it))){ 74 | hull.erase(next(it)); 75 | } 76 | it = updateLeftBorder(it); 77 | if(hasPrev(it)){ 78 | updateLeftBorder(prev(it)); 79 | } 80 | if(hasNext(it)){ 81 | updateLeftBorder(next(it)); 82 | } 83 | } 84 | long long getBest(int x){ 85 | Line q; 86 | q.val = x; 87 | q.type = 1; 88 | auto bestLine = hull.lower_bound(q); 89 | if(bestLine == hull.end()){ 90 | return 1e16; 91 | } 92 | return bestLine -> valueAt(x); 93 | } 94 | }; 95 | -------------------------------------------------------------------------------- /Library/DS/ConvexHull.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 18 | typedef pair pll; 19 | typedef vector vi; 20 | typedef vector vl; 21 | typedef vector vpii; 22 | typedef vector vpll; 23 | typedef vector vvi; 24 | typedef vector vvl; 25 | const int mod = 1000000007; 26 | const int N = 2e5; 27 | vi g[N]; 28 | int a[N]; 29 | //Takes query values in increasing order 30 | //Add lines in sorted order 31 | class ConvexHull{ 32 | int ptr; 33 | typedef pii Line; 34 | vector lines; 35 | public: 36 | ConvexHull(){ 37 | ptr = 0; 38 | lines.clear(); 39 | } 40 | int f(Line l, int x){ 41 | return l.F*x+l.S; 42 | } 43 | bool bad(Line l1, Line l2, Line l3){ 44 | return (l3.S-l1.S)*(l1.F-l2.F) <= (l1.F-l3.F)*(l2.S-l1.S); 45 | } 46 | void addLine(Line l3){ 47 | lines.pb(l3); 48 | while(lines.size()>=3){ 49 | int tot = lines.size(); 50 | Line l3 = lines[tot-1]; 51 | Line l2 = lines[tot-2]; 52 | Line l1 = lines[tot-3]; 53 | if (bad(l1, l2, l3)){ 54 | lines.erase(lines.end()-2); 55 | } 56 | else break; 57 | } 58 | } 59 | //Returns Minimum 60 | //Query values must be in non-decreasing order 61 | //Otherwise use Binary Search (Maintain the end points of lines) 62 | int get(int x){ 63 | if (ptr >= lines.size()) ptr = lines.size()-1; 64 | while(ptr < lines.size()-1 and f(lines[ptr], x) > f(lines[ptr+1], x)) 65 | ptr++; 66 | return f(lines[ptr], x); 67 | } 68 | }; 69 | //END 70 | bool f(pii a, pii b){ 71 | if (a.F != b.F) return a.F > b.F; 72 | return a.S < b.S; 73 | } 74 | int main() 75 | { 76 | ios_base::sync_with_stdio(false); 77 | cin.tie(NULL); 78 | int i,n; 79 | vpii data; 80 | cin>>n; 81 | fo(i, n){ 82 | int m, c; 83 | cin>>m>>c; 84 | data.pb({m, c}); 85 | } 86 | sort(data.begin(), data.end(), f); 87 | ConvexHull A; 88 | fo(i, n) A.addLine(data[i]); 89 | cin>>n; 90 | vi points; 91 | fo(i, n){ 92 | int x; 93 | cin>>x; 94 | points.pb(x); 95 | } 96 | sort(points.begin(), points.end()); 97 | for(int x: points) 98 | cout< succ; 5 | bool operator<(const Line& rhs) const { 6 | if (rhs.b != is_query) return m < rhs.m; 7 | const Line* s = succ(); 8 | if (!s) return 0; 9 | ll x = rhs.m; 10 | return b - s->b < (s->m - m) * x; 11 | } 12 | }; 13 | struct HullDynamic : public multiset { // will maintain upper hull for maximum 14 | bool bad(iterator y) { 15 | auto z = next(y); 16 | if (y == begin()) { 17 | if (z == end()) return 0; 18 | return y->m == z->m && y->b <= z->b; 19 | } 20 | auto x = prev(y); 21 | if (z == end()) return y->m == x->m && y->b <= x->b; 22 | return (x->b - y->b)*(z->m - y->m) >= (y->b - z->b)*(y->m - x->m); 23 | } 24 | void insert_line(ll m, ll b) { 25 | auto y = insert({ m, b }); 26 | y->succ = [=] { return next(y) == end() ? 0 : &*next(y); }; 27 | if (bad(y)) { erase(y); return; } 28 | while (next(y) != end() && bad(next(y))) erase(next(y)); 29 | while (y != begin() && bad(prev(y))) erase(prev(y)); 30 | } 31 | ll eval(ll x) { 32 | auto l = *lower_bound((Line) { x, is_query }); 33 | return l.m * x + l.b; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Library/DS/HV-Intersection-PBDS.cpp: -------------------------------------------------------------------------------- 1 | //intersection of horizontal and vertical lines https://www.codechef.com/NOV16/problems/URBANDEV 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | using namespace __gnu_pbds; 8 | typedef tree,rb_tree_tag,tree_order_statistics_node_update> ordered_set; 9 | typedef tree,null_type,less>,rb_tree_tag,tree_order_statistics_node_update> ordered_mset; 10 | #define gc getchar_unlocked 11 | #define fo(i,n) for(i=0;in;k pii; 30 | typedef pair pll; 31 | typedef vector vi; 32 | typedef vector vll; 33 | typedef vector vpii; 34 | typedef vector vpll; 35 | typedef vector vvi; 36 | typedef vector vvl; 37 | const int mod = 1000000007; 38 | const int N = 1e5+12; 39 | using namespace std; 40 | int cnt[N]; 41 | typedef pair pii; 42 | 43 | class CBF 44 | { 45 | public: 46 | bool operator()(const pii& p1, const pii& p2)const 47 | { 48 | return p1.first < p2.first; 49 | } 50 | }; 51 | 52 | 53 | vi lo[N], hi[N]; 54 | vector< pair > ver[N]; 55 | set events; 56 | unordered_map hai[2][N]; 57 | #define x1 u.F 58 | #define y1 u.S 59 | #define x2 v.F 60 | #define y2 v.S 61 | int n; 62 | 63 | struct node{ 64 | pii u,v; 65 | int o; 66 | void read(int i){ 67 | si(u.F); si(u.S); 68 | si(v.F); si(v.S); 69 | events.insert(x1); 70 | events.insert(x2); 71 | if(u.S > v.S or u.F > v.F) swap(u, v); 72 | find(i); 73 | } 74 | void find(int pos){ 75 | if(u.F==v.F){ 76 | o=1; 77 | ver[u.F].pb({pos, {u.S, v.S}}); 78 | } 79 | else{ 80 | o=0; 81 | lo[u.F].pb(u.S); 82 | hi[v.F].pb(v.S); 83 | } 84 | hai[o][u.F][u.S] = 1; 85 | 86 | hai[o][v.F][v.S] = 1; 87 | } 88 | void change(int i){ 89 | swap(x1, y1); swap(x2, y2); 90 | if(u.S > v.S or u.F > v.F) swap(u, v); 91 | find(i); 92 | } 93 | }seg[N]; 94 | 95 | void input(){ 96 | int i; 97 | si(n); 98 | fo(i, n){ 99 | seg[i].read(i); cnt[i] = 0; 100 | } 101 | 102 | } 103 | void reset(){ 104 | int i; 105 | // fo(i, N) hai[0][i].clear(), hai[1][i].clear(); 106 | fo(i, N) lo[i].clear(), hi[i].clear(), ver[i].clear(); 107 | events.clear(); 108 | fo(i, n) seg[i].change(i), events.insert(seg[i].x1), events.insert(seg[i].x2); 109 | 110 | } 111 | int T = 1; 112 | int inf = mod; 113 | void solve(){ 114 | int i; 115 | 116 | ll ans = 0; 117 | 118 | ordered_mset con; 119 | int xx; 120 | 121 | for(int xx: events){ 122 | //cout<<"AT "< line: ver[xx]){ 129 | int j = line.F; 130 | pii span = line.S; 131 | cnt[j] += con.order_of_key({span.S, inf}) 132 | - con.order_of_key({span.F-1, inf}); 133 | //cout<<"LINE "< 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 20 | typedef pair pll; 21 | typedef vector vi; 22 | typedef vector vl; 23 | typedef vector vpii; 24 | typedef vector vpll; 25 | typedef vector vvi; 26 | typedef vector vvl; 27 | const int mod = 1000000007; 28 | const int N = 2e6; 29 | vi g[N]; 30 | int pos_; 31 | ll a[N], MX; 32 | int dp[N], b1[N], b2[N], p1[N], p2[N], from[N]; 33 | int L, R; 34 | //http://codeforces.com/problemset/problem/474/E 35 | //pos_ is the 'i' in a[i] while adding a[i] to BIT. 36 | //p1[pos] represents what position in array gives the max till pos. 37 | void add1(int pos, int val){ 38 | while(pos < N){ 39 | if (b1[pos] <= val) b1[pos] = val, p1[pos] = pos_; 40 | pos += pos&-pos; 41 | } 42 | } 43 | void add2(int pos, int val){ 44 | pos = MX-pos+1; 45 | while(pos < N){ 46 | if (b2[pos] <= val) b2[pos] = val, p2[pos] = pos_; 47 | pos += pos&-pos; 48 | } 49 | } 50 | int get1(int pos){ 51 | int ans = -1; 52 | while(pos){ 53 | if (b1[pos] > ans) ans = b1[pos], L = p1[pos]; 54 | ans = max(b1[pos], ans); 55 | pos -= pos&-pos; 56 | } 57 | return ans; 58 | } 59 | int get2(int pos){ 60 | pos = MX-pos+1; 61 | int ans = -1; 62 | while(pos){ 63 | if (b2[pos] > ans) ans = b2[pos], R = p2[pos]; 64 | pos -= pos&-pos; 65 | } 66 | return ans; 67 | } 68 | set sett; 69 | map mep; 70 | map at; 71 | int main() 72 | { 73 | ios_base::sync_with_stdio(false); 74 | cin.tie(NULL); 75 | int i,n,k,j,d; 76 | cin >> n >> d; 77 | fo(i, n){ 78 | cin>>a[i]; 79 | sett.insert(a[i]); 80 | } 81 | int pos = 0; 82 | tr(it, sett) mep[*it] = ++pos, at[pos] = *it; 83 | i = 0; 84 | MX = mep[*sett.rbegin()]; 85 | pos_ = 1; 86 | fo(i, n) 87 | add1(mep[a[i]], 1), 88 | add2(mep[a[i]], 1); 89 | Fo(i, 1, n){ 90 | pos_ = i+1; L = R = 0; 91 | auto it = sett.lower_bound(a[i]-d); 92 | int left = 1, right = 1; 93 | if (*it != a[i]-d){ 94 | if (it == sett.begin()) left = 0; 95 | else it--; 96 | } 97 | if (left) left = get1( mep[*it]); 98 | it = sett.lower_bound(a[i]+d); 99 | if (it == sett.end()) right = 0; 100 | if (right) right = get2(mep[*it]); 101 | int cur = max(left, right); 102 | 103 | if (cur>-1){ 104 | from[i+1] = cur==left?L:R; 105 | cur++; 106 | dp[i] = cur; 107 | add1(mep[a[i]], cur); 108 | add2(mep[a[i]], cur); 109 | } 110 | } 111 | 112 | int cur = n, res = -1; 113 | fo(i, n) if (res < dp[i]) res = dp[i], cur = i+1; 114 | cout< z[v]) p[v] = u; 22 | else p[u] = v, z[v]++; 23 | return 1; 24 | } 25 | 26 | int get(int v){ 27 | if (v == p[v]) return v; 28 | return p[v] = get(p[v]); 29 | } 30 | int com(){ 31 | int i; 32 | int ans = 0; 33 | Fo(i, 1, n+1) ans += p[i] == i; 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Library/DS/bit.cpp: -------------------------------------------------------------------------------- 1 | //1-d bit 2 | int valR[N], valL[N], bit[N]; 3 | map id; 4 | void add(int x){ 5 | while(x no; 20 | //for suffix queries 21 | //add all no's in the set that you will add + query 22 | //otherwise use lower_bound to find the correct id 23 | fo(i, n) no.insert(valL[i]); 24 | fo(i, n) no.insert(valR[i]); 25 | int pos = 1; 26 | //give IDs in descending order so that 27 | //suffix is handles as prefix 28 | for(auto it = no.rbegin(); it != no.rend(); ++it) 29 | id[*it] = pos++; 30 | } 31 | int main() 32 | { 33 | ios_base::sync_with_stdio(false); 34 | cin.tie(NULL); 35 | int i,k,j; 36 | clr(bit); 37 | cin>>n; 38 | fo(i, n)cin>>a[i]; 39 | map cnt; 40 | Fo(i, n-1, -1) valR[i] = 1+cnt[a[i]]++; 41 | cnt.clear(); 42 | Fo(i, 0, n) valL[i] = 1+cnt[a[i]]++; 43 | suffix(); 44 | ll ans = 0; 45 | fo(i,n){ 46 | //since suffix stored as prefix 47 | //[1,x-1] represent ans for >x 48 | ans += query(id[valR[i]]-1); 49 | add(id[valL[i]]); 50 | } 51 | cout< { 9 | bool bad (iterator y) { 10 | iterator z = next(y), x; 11 | if (y == begin()) { 12 | if (z == end()) return 0; 13 | return y->a == z->a && y->b <= z->b; 14 | } 15 | x = prev(y); 16 | if (z == end()) { 17 | return y->a == x->a && y->b <= x->b; 18 | } 19 | return 1.0L * (x->b - y->b) * (z->a - y->a) >= 1.0L * (y->b - z->b) * (y->a - x->a); 20 | } 21 | 22 | void add (ll a, ll b) { 23 | a*=-1; 24 | b*=-1; 25 | cmpA = 1; 26 | iterator y = insert((Line){a,b,-INF}); 27 | if (bad(y)) { erase(y); return; } 28 | while (next(y) != end() && bad(next(y))) erase(next(y)); 29 | while (y != begin() && bad(prev(y))) erase(prev(y)); 30 | if (next(y) != end()) next(y)->xl = 1.0L * (y->b - next(y)->b) / (next(y)->a - y->a); 31 | if (y != begin()) y->xl = 1.0L * (y->b - prev(y)->b) / (prev(y)->a - y->a); 32 | } 33 | 34 | ll eval (ll x) { 35 | if (empty()) return -(-INF); 36 | cmpA = 0; 37 | iterator it = prev(lower_bound((Line){0,0,1.0L*x})); 38 | return -(it->a * x + it->b); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Library/DS/heap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class heap{ 4 | vector a; 5 | #define l(x) 2*x+1 6 | #define r(x) 2*x+2 7 | #define p(x) (x-1)/2 8 | #define null -INT_MAX 9 | public: 10 | void add(int x){ 11 | a.push_back(x); 12 | go(a.size()-1); 13 | } 14 | void go(int u){ 15 | if(u == 0) return; 16 | int P = p(u); 17 | if(a[P]>a[u]) swap(a[P], a[u]), go(P); 18 | } 19 | void heapify(int u){ 20 | int L = l(u), R = r(u), n = a.size(); 21 | if(L>=n and R>=n) return; 22 | int v = (La[v]) swap(a[u], a[v]), heapify(v); 24 | } 25 | int extract(){ 26 | if (a.empty()){ 27 | cout << "Oops! heap is empty!" << endl; 28 | return null; 29 | } 30 | int ans = a[0]; 31 | if(a.size() == 1) { 32 | a.clear(); 33 | return ans; 34 | } 35 | a[0] = a.back(); 36 | a.pop_back(); 37 | heapify(0); 38 | return ans; 39 | } 40 | }; 41 | 42 | int main() 43 | { 44 | ios_base::sync_with_stdio(false); 45 | cin.tie(NULL); 46 | int i,n,k,j; 47 | heap H; 48 | vector a{13, 1, 10, 34, 42, -10}; 49 | for(int x: a) H.add(x); 50 | for(int x: a) cout << H.extract() << " "; 51 | return 0; 52 | } 53 | 54 | 55 | -------------------------------------------------------------------------------- /Library/DS/persistent_segment_tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | // query l to r range for the no of integers between x and y 3 | #include 4 | using namespace std; 5 | int T = 1; 6 | const int N = 1e6; 7 | const int MX = N; 8 | struct node{ 9 | int l, r, cnt; 10 | }t[100*MX]; 11 | int root[N], a[N]; 12 | int build(int lo, int hi){ 13 | int id = T++; 14 | if(lo == hi) return id; 15 | int mid = (lo+hi)/2; 16 | t[id].l = build(lo, mid); 17 | t[id].r = build(mid+1, hi); 18 | return id; 19 | } 20 | int update(int rt, int lo, int hi, int val){ 21 | int id = T++; 22 | t[id] = t[rt]; t[id].cnt++; 23 | if(lo == hi) return id; 24 | int mid = (lo+hi)/2; 25 | if(val <= mid) t[id].l = update(t[rt].l, lo, mid, val); 26 | else t[id].r = update(t[rt].r, mid+1, hi, val); 27 | return id; 28 | } 29 | int query(int rt, int lo, int hi, int x, int y){ 30 | if(x==lo and y==hi) return t[rt].cnt; 31 | int mid = (lo+hi)/2; 32 | if(y <= mid) return query(t[rt].l, lo, mid, x, y); 33 | else if (x > mid) return query(t[rt].r, mid+1, hi, x, y); 34 | return query(t[rt].l, lo, mid, x, mid) + query(t[rt].r, mid+1, hi, mid+1, y); 35 | } 36 | int main() { 37 | int i, n, q; 38 | cin >> n >> q; 39 | for(i = 0; i < n; i++) cin >> a[i+1]; 40 | root[0] = build(0, MX); 41 | for(i = 1; i <= n; i++){ 42 | root[i] = update(root[i-1], 0, MX, a[i]); 43 | } 44 | while(q--){ 45 | int l, r, x, y; 46 | cin >> l >> r >> x >> y; 47 | cout << query(root[r], 0, MX, x, y) - query(root[l-1], 0, MX, x, y) << endl; 48 | } 49 | return 0; 50 | } -------------------------------------------------------------------------------- /Library/DS/policy-based-set.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | using namespace __gnu_pbds; 7 | typedef tree,rb_tree_tag,tree_order_statistics_node_update> ordered_set; 8 | typedef tree,null_type,less>,rb_tree_tag,tree_order_statistics_node_update> ordered_mset; 9 | //ENDS 10 | 11 | int t = 0; 12 | 13 | int main() 14 | { 15 | 16 | int x = 1; 17 | ordered_mset me; 18 | me.insert({x, t++}); 19 | // me.erase(me.lower_bound({x, 0})); 20 | cout << me.order_of_key({x, 0}) << "\n"; 21 | 22 | 23 | ordered_set A; 24 | A.insert(1); 25 | A.insert(2); 26 | A.insert(10); 27 | A.insert(100); 28 | //how many numbers are smaller than it 29 | cout< 2 | using namespace std; 3 | const int N = 2e6; 4 | map my[N]; 5 | void update(int st, int lo, int hi, int pos, int val){ 6 | my[st][val]++; 7 | if(lo == hi){ 8 | return; 9 | } 10 | int l = 2*st, r = l+1, mid = (lo+hi)/2; 11 | if(pos>mid) update(r, mid+1, hi, pos, val); 12 | else update(l, lo, mid, pos, val); 13 | } 14 | long long query(int st, int lo, int hi, int x, int y, int val){ 15 | if(lo == x and hi == y){ 16 | return my[st][val]; 17 | } 18 | int l = 2*st, r = l+1, mid = (lo+hi)/2; 19 | if(x>mid) return query(r, mid+1, hi, x, y, val); 20 | else if(y<=mid) return query(l, lo, mid, x, y, val); 21 | return query(l ,lo , mid, x, mid, val) + query(r, mid+1, hi, mid+1, y, val); 22 | } 23 | 24 | int main() { 25 | int n, i, q, k, l, t, r; 26 | cin >> n >> q; 27 | while(q--){ 28 | cin >> t >> l >> r; 29 | if(t == 1){ 30 | //add l to a[r] 31 | update(1, 0, n-1, r-1, l); 32 | } 33 | else{ 34 | //count of k from a[l] to a[r]. 35 | cin >> k; 36 | cout << query(1, 0, n-1, l-1, r-1, k) << endl; 37 | } 38 | } 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Library/DS/segment_tree_point_update.cpp: -------------------------------------------------------------------------------- 1 | struct node{ 2 | ll ans; 3 | void leaf(int val){ 4 | ans = val; 5 | } 6 | 7 | void merge(node r, node l){ 8 | ans = r.ans + l.ans; 9 | } 10 | 11 | }; 12 | class st{ 13 | int n; 14 | node* T; 15 | int* a; 16 | public: 17 | #define l(x) 2*x 18 | #define r(x) 2*x+1 19 | #define lpart left, lo, mid 20 | #define rpart right, mid+1, hi 21 | st() {} 22 | st(int x){ 23 | a = new int[x]; 24 | clr(a); 25 | n = 1; 26 | while(n <= x) n *= 2; n *= 2; 27 | T = new node[n]; 28 | n = x; 29 | build(1, 0, n-1); 30 | } 31 | st(int *arr, int x){ 32 | a = arr; 33 | n = 1; 34 | while(n <= x) n *= 2; n *= 2; 35 | T = new node[n]; 36 | n = x; 37 | build(1, 0, n-1); 38 | } 39 | void build(int id, int lo, int hi){ 40 | if(lo == hi){ 41 | T[id].leaf(a[lo]); 42 | return; 43 | } 44 | int left = l(id), right = r(id), mid = (lo+hi)/2; 45 | build(lpart); 46 | build(rpart); 47 | T[id].merge(T[left], T[right]); 48 | } 49 | void update(int pos, int val){ 50 | update(1, 0, n-1, pos, val); 51 | } 52 | void update(int id, int lo, int hi, int pos, int val){ 53 | if(lo==hi and lo==pos){ 54 | a[pos] = val; 55 | T[id].leaf(a[lo]); 56 | return; 57 | } 58 | int left = l(id), right = r(id), mid = (lo+hi)/2; 59 | if(pos <= mid) update(lpart, pos, val); 60 | else update(rpart, pos, val); 61 | T[id].merge(T[left], T[right]); 62 | } 63 | ll query(int x, int y){ 64 | return query(1, 0, n-1, x, y).ans; 65 | } 66 | node query(int id, int lo, int hi, int x, int y){ 67 | if(lo==x and hi==y){ 68 | return T[id]; 69 | } 70 | int left = l(id), right = r(id), mid = (lo+hi)/2; 71 | if(y <= mid) return query(lpart, x, y); 72 | else if(x>mid) return query(rpart, x, y); 73 | node L = query(lpart, x, mid); 74 | node R = query(rpart, mid+1, y); 75 | node res; 76 | res.merge(L, R); 77 | return res; 78 | } 79 | }; 80 | -------------------------------------------------------------------------------- /Library/DS/sparse_table_2d.cpp: -------------------------------------------------------------------------------- 1 | //2d sparse table for max 2 | //0 based index 3 | //LGN = 1 + lg2(N) 4 | //LGM = 1 + lg2(M) 5 | 6 | const int N = 1030; 7 | const int M = 1030; 8 | const int LGN = 11; 9 | const int LGM = 11; 10 | 11 | int a[N][M]; 12 | int dp[N][M][LGN][LGM]; 13 | const int MAXN = 2e6; //max(N, M) 14 | int lg2[MAXN]; 15 | void pre(){ 16 | //build lg2 17 | lg2[1] = log2(1); 18 | lg2[2] = log2(2); 19 | int val = 1, at = 4; 20 | int i; 21 | Fo(i, 3, MAXN){ 22 | if (i == at){ 23 | at *= 2; 24 | val++; 25 | } 26 | lg2[i] = log2(i); 27 | } 28 | } 29 | void build(int n, int m){ 30 | pre(); 31 | for(int i = 1; i <= n; ++ i) for(int j = 1; j <= m; ++ j) dp[i][j][0][0] = a[i-1][j-1]; 32 | for(int j1 = 0; (1 << j1) <= n; ++ j1) { 33 | for(int j2 = 0; (1 << j2) <= m; ++ j2) if(j1 || j2) { 34 | for(int i1 = 1; i1 + (1 << j1) - 1 <= n; ++ i1) { 35 | for(int i2 = 1; i2 + (1 << j2) - 1 <= m; ++ i2) { 36 | if(j1) dp[i1][i2][j1][j2] = max(dp[i1][i2][j1 - 1][j2], dp[i1 + (1 << (j1 - 1))][i2][j1 - 1][j2]); 37 | else dp[i1][i2][j1][j2] = max(dp[i1][i2][j1][j2 - 1], dp[i1][i2 + (1 << (j2 - 1))][j1][j2 - 1]); 38 | } 39 | } 40 | } 41 | } 42 | } 43 | 44 | int query(int x1, int Y1, int x2, int y2){ 45 | int k1 = lg2[x2-x1+1]; 46 | int k2 = lg2[y2-Y1+1]; 47 | return max(max(dp[x1][Y1][k1][k2], dp[x2 - (1 << k1) + 1][y2 - (1 << k2) + 1][k1][k2]), 48 | max(dp[x2 - (1 << k1) + 1][Y1][k1][k2], dp[x1][y2 - (1 << k2) + 1][k1][k2])); 49 | } 50 | -------------------------------------------------------------------------------- /Library/Graph/BCC.cpp: -------------------------------------------------------------------------------- 1 | class Bcc{ 2 | vector num,inS; 3 | stack roots,st; 4 | int cnt; 5 | public: 6 | vv bcc,tree; 7 | vector brdg,inv; 8 | void dfs(const vv &g,const vector &es,int v,int e){ 9 | num[v]=++cnt; 10 | st.push(v); inS[v]=1; roots.push(v); 11 | for(const int &i:g[v])if(i!=e){ 12 | int w=es[i].X+es[i].Y-v; 13 | if(!num[w]){ 14 | dfs(g,es,w,i); 15 | }else if(inS[w]){ 16 | while(num[roots.top()]>num[w]) roots.pop(); 17 | } 18 | } 19 | if(v==roots.top()){ 20 | brdg.pb(e); 21 | bcc.pb(vector()); 22 | while(1){ 23 | int w=st.top(); st.pop(); inS[w]=0; 24 | bcc.back().pb(w); 25 | if(v==w) break; 26 | } 27 | roots.pop(); 28 | } 29 | } 30 | 31 | Bcc(vv &g,vector es){ 32 | const int n=g.size(); 33 | num.resize(n); inS.resize(n); 34 | int cnt=0; 35 | rep(i,n)if(!num[i]){ 36 | dfs(g,es,i,-1); 37 | brdg.pop_back(); 38 | } 39 | const int m=bcc.size(); 40 | inv.resize(n); 41 | rep(i,m) for(const int &v:bcc[i]) inv[v]=i; 42 | for(pii &p:es){p.X=inv[p.X]; p.Y=inv[p.Y];} 43 | //sort(all(es)); UNIQUE(es); 44 | tree.resize(m); //tedge.resize(m); 45 | int i=0; 46 | for(const pii &p:es){ 47 | if(p.X!=p.Y){ 48 | tree[p.X].pb(p.Y); 49 | tree[p.Y].pb(p.X); 50 | // tedge[p.X].pb(i); 51 | // tedge[p.Y].pb(i); 52 | } 53 | ++i; 54 | } 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Library/Graph/Dijkstra.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 18 | typedef pair pll; 19 | typedef vector vi; 20 | typedef vector vl; 21 | typedef vector vpii; 22 | typedef vector vpll; 23 | typedef vector vvi; 24 | typedef vector vvl; 25 | const int mod = 1000000007; 26 | const int N = 2e5; 27 | struct compar{ 28 | //priority queue 29 | //u need top element.. sort such 30 | //that ur element comes at last 31 | bool operator() (pii a, pii b){ 32 | if (a.F != b.F) 33 | return a.F > b.F; 34 | return a.S < b.S; 35 | } 36 | }; 37 | //UNDIRECTED GRAPH 38 | class Dijkstra{ 39 | int n, m; 40 | ll *dis; 41 | bool *vis; 42 | int *par; 43 | ll inf; 44 | priority_queue,compar> Q; 45 | vpii *G; 46 | public: 47 | void setVertices(int no){ 48 | n = no; 49 | G = new vpii[n+1]; 50 | dis = new ll[n+1]; 51 | vis = new bool[n+1]; 52 | par = new int[n+1]; 53 | inf = 1e18; 54 | 55 | } 56 | void setEdges(int no){ 57 | m = no; 58 | } 59 | void addEdge(int u, int v, int w){ 60 | G[u].pb({w, v}); 61 | //UNDIRECTED-GRAPH 62 | G[v].pb({w, u}); 63 | } 64 | ll shortestPath(int source, int sink){ 65 | int i; 66 | for(i=1; i<=n; i++) 67 | dis[i] = inf, vis[i] = 0; 68 | dis[source] = 0; 69 | Q.push({0, source}); 70 | while(!Q.empty()){ 71 | pii cur = Q.top(); Q.pop(); 72 | if (vis[cur.S]) continue; 73 | vis[cur.S] = 1; 74 | dis[cur.S] = cur.F; 75 | for(pii x: G[cur.S]){ 76 | int to = x.S, w = x.F; 77 | Q.push({cur.F+w, to}); 78 | } 79 | 80 | } 81 | if (dis[sink] != inf) return dis[sink]; 82 | return -1; 83 | } 84 | }; 85 | int main() 86 | { 87 | ios_base::sync_with_stdio(false); 88 | cin.tie(NULL); 89 | int i, j, n, m; 90 | cin>>n>>m; 91 | Dijkstra A; 92 | A.setVertices(n); 93 | A.setEdges(m); 94 | while(m--){ 95 | int u, v, w; 96 | cin>>u>>v>>w; 97 | A.addEdge(u, v, w); 98 | } 99 | A.pathOfShortestPath(1, n); 100 | return 0; 101 | } 102 | 103 | 104 | -------------------------------------------------------------------------------- /Library/Graph/Dijkstra_Khattar_Style.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 18 | typedef pair pll; 19 | typedef vector vi; 20 | typedef vector vl; 21 | typedef vector vpii; 22 | typedef vector vpll; 23 | typedef vector vvi; 24 | typedef vector vvl; 25 | const int mod = 1000000007; 26 | const int N = 2e5; 27 | vi g[N]; 28 | int a[N]; 29 | 30 | int mpow(int base, int exp); 31 | void ipgraph(int n, int m); 32 | void dfs(int u, int par); 33 | //http://codeforces.com/problemset/problem/545/E 34 | //Begins 35 | //Works for 0/1 based index 36 | //Stores the edges used in shortest paths 37 | 38 | struct f{ 39 | bool operator()(pair a, pair b){ 40 | if (a.F != b.F) return a.F > b.F; 41 | if (a.S.S != b.S.S) return W[a.S.S] > W[b.S.S]; 42 | return a.S.F < b.S.F; 43 | 44 | } 45 | }; 46 | class Dijkstra{ 47 | int n, m; 48 | vi *G; 49 | set res; 50 | int *vis, *U, *V; 51 | int *W; 52 | ll *dis; 53 | 54 | typedef pair node; 55 | public: 56 | void init(int no, int edges){ 57 | n = no; 58 | m = edges; 59 | U = new int[m+3]; 60 | V = new int[m+3]; 61 | W = new int[m+3]; 62 | dis = new ll[m+3]; 63 | G = new vi[n+3]; 64 | vis = new int[n+3]; 65 | int i; 66 | fo(i, n+1) vis[i] = 0; 67 | clr(vis); 68 | } 69 | 70 | int adj(int u, int e){ 71 | return u == U[e]? V[e]:U[e]; 72 | } 73 | void addEdge(int pos, int u, int v, int w){ 74 | U[pos] = u; 75 | V[pos] = v; 76 | W[pos] = w; 77 | G[u].pb(pos); 78 | G[v].pb(pos); 79 | } 80 | void compute(int source){ 81 | priority_queue< node, vector, f > Q; 82 | Q.push({0, {source, -1}}); 83 | 84 | while(!Q.empty()){ 85 | node cur = Q.top(); Q.pop(); 86 | if (vis[cur.S.F]) continue; 87 | vis[cur.S.F] = 1; 88 | dis[cur.S.F] = cur.F; 89 | res.insert(cur.S.S); 90 | for(int e: G[cur.S.F]){ 91 | int to = adj(cur.S.F, e); 92 | int w = W[e]; 93 | Q.push({cur.F+w, {to, e}}); 94 | } 95 | } 96 | res.erase(-1); 97 | ll sum = 0; 98 | tr(it, res) sum += W[*it]; 99 | cout<>n>>m; 112 | A.init(n, m); 113 | fo(i, m){ 114 | int u, v, w; 115 | cin>>u>>v>>w; 116 | A.addEdge(i+1, u, v, w); 117 | } 118 | int u; 119 | cin>>u; 120 | A.compute(u); 121 | return 0; 122 | } 123 | 124 | int mpow(int base, int exp) { 125 | base %= mod; 126 | int result = 1; 127 | while (exp > 0) { 128 | if (exp & 1) result = ((ll)result * base) % mod; 129 | base = ((ll)base * base) % mod; 130 | exp >>= 1; 131 | } 132 | return result; 133 | } 134 | 135 | void ipgraph(int n, int m){ 136 | int i, u, v; 137 | while(m--){ 138 | cin>>u>>v; 139 | g[u-1].pb(v-1); 140 | g[v-1].pb(u-1); 141 | } 142 | } 143 | 144 | void dfs(int u, int par){ 145 | for(int v:g[u]){ 146 | if (v == par) continue; 147 | dfs(v, u); 148 | } 149 | } 150 | 151 | -------------------------------------------------------------------------------- /Library/Graph/Euler_Circuit.cpp: -------------------------------------------------------------------------------- 1 | //http://codeforces.com/problemset/problem/723/E 2 | //EULER - TOUR -> UNDIRECTED and DIRECTED GRAPH 3 | //for undirected i needed to mark edges that i have traversed 4 | #include 5 | using namespace std; 6 | #define gc getchar_unlocked 7 | #define fo(i,n) for(i=0;i pii; 23 | typedef pair pll; 24 | typedef vector vi; 25 | typedef vector vl; 26 | typedef vector vpii; 27 | typedef vector vpll; 28 | typedef vector vvi; 29 | typedef vector vvl; 30 | const int mod = 1000000007; 31 | const int N = 304; 32 | vpii g[N]; 33 | set has[N]; 34 | ll a[N], vis[N], cnt[N], in[N], mark[N*N]; 35 | vi ans; 36 | int mpow(int base, int exp); 37 | void ipgraph(int n, int m); 38 | void dfs(int u, int par); 39 | void go(int u, int par){ 40 | vis[u] = 1; 41 | while(cnt[u] < (int)g[u].size()){ 42 | cnt[u]++; 43 | if (mark[g[u][cnt[u]-1].S]) continue; 44 | else mark[g[u][cnt[u]-1].S] = 1, go(g[u][cnt[u]-1].F, u); 45 | } 46 | ans.pb(u); 47 | } 48 | int main() 49 | { 50 | ios_base::sync_with_stdio(false); 51 | cin.tie(NULL); 52 | int n, m, t, i, u,j, v, w; 53 | //freopen("input.txt", "r". stdin); 54 | //freopen("output.txt", "w". stdout); 55 | cin>>t; 56 | while(t--){ 57 | cin>>n>>m; 58 | ans.clear(); 59 | Fo(i, 0, n+1) g[i].clear(), has[i].clear(), in[i] = cnt[i] = vis[i] = 0; 60 | fo(i, m){ 61 | cin>>u>>v; 62 | g[u].pb({v, i}); 63 | g[v].pb({u, i}); 64 | mark[i] = 0; 65 | has[u].insert(v); 66 | has[v].insert(u); 67 | in[v]++; 68 | in[u]++; 69 | } 70 | int x = m; 71 | //add pseudo-vertex 72 | int res = 0; 73 | Fo(i, 1, n+1) res += 1 - (in[i]%2); 74 | Fo(i, 0, n+1) if (in[i]&1) mark[x] = 0, g[i].pb({0, x}), g[0].pb({i, x++}); 75 | 76 | //graph has all vertices with even degree 77 | //finding euler circuit makes sure all even degree vertices 78 | //have equal no of incoming and outgoing edges 79 | //later on removing extra edges we added 80 | // will not affect even degree vertices :D 81 | Fo(i, 1, n+1){ 82 | if (!vis[i]){ 83 | vis[i] = 1; 84 | go(i, -1); 85 | ans.pb(i); 86 | } 87 | } 88 | cout< z[v]) p[v] = u; 21 | else p[u] = v, z[v]++; 22 | return 1; 23 | } 24 | 25 | int get(int v){ 26 | if (v == p[v]) return v; 27 | return p[v] = get(p[v]); 28 | } 29 | 30 | }; 31 | bool f(pair a, pair b){ 32 | return a.F < b.F; 33 | } 34 | class MST{ 35 | int n, m; 36 | typedef pair pii; 37 | #define pb push_back 38 | typedef pair edge; 39 | vector Edges; 40 | UnionFind *forest; 41 | vector res; 42 | public: 43 | MST(int size){ 44 | n = size; 45 | forest = new UnionFind(n); 46 | } 47 | void addEdge(int u, int v, int w){ 48 | Edges.pb({w, {u, v}}); 49 | } 50 | void compute(){ 51 | sort(Edges.begin(), Edges.end(), f); 52 | for(edge E:Edges){ 53 | if (forest->addEdge(E.S.F, E.S.S)) 54 | res.pb(E); 55 | } 56 | } 57 | void out(){ 58 | int sum = 0; 59 | for(edge E: res) 60 | sum += E.F; 61 | cout< 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 18 | typedef pair pll; 19 | typedef vector vi; 20 | typedef vector vl; 21 | typedef vector vpii; 22 | typedef vector vpll; 23 | typedef vector vvi; 24 | typedef vector vvl; 25 | const int mod = 1000000007; 26 | const int N = 2e5; 27 | vi g[N]; 28 | int a[N]; 29 | //http://codeforces.com/problemset/problem/237/E 30 | 31 | // min-cost max-flow ... SOURCE: Unknown 32 | // Not tested for multi edges, negative edge weight 33 | typedef vector VI; 34 | typedef vector VVI; 35 | typedef long long L; 36 | typedef vector VL; 37 | typedef vector VVL; 38 | typedef pair PII; 39 | typedef vector VPII; 40 | 41 | const L INF = numeric_limits::max() / 4; 42 | 43 | struct MinCostMaxFlow { 44 | int N; 45 | VVL cap, flow, cost; 46 | VI found; 47 | VL dist, pi, width; 48 | VPII dad; 49 | 50 | MinCostMaxFlow(int N) : 51 | N(N), cap(N, VL(N)), flow(N, VL(N)), cost(N, VL(N)), 52 | found(N), dist(N), pi(N), width(N), dad(N) {} 53 | 54 | // 0 based indexing 55 | void AddEdge(int from, int to, L cap, L cost) { 56 | this->cap[from][to] = cap; 57 | this->cost[from][to] = cost; 58 | } 59 | 60 | void Relax(int s, int k, L cap, L cost, int dir) { 61 | L val = dist[s] + pi[s] - pi[k] + cost; 62 | if (cap && val < dist[k]) { 63 | dist[k] = val; 64 | dad[k] = make_pair(s, dir); 65 | width[k] = min(cap, width[s]); 66 | } 67 | } 68 | 69 | L Dijkstra(int s, int t) { 70 | fill(found.begin(), found.end(), false); 71 | fill(dist.begin(), dist.end(), INF); 72 | fill(width.begin(), width.end(), 0); 73 | dist[s] = 0; 74 | width[s] = INF; 75 | 76 | while (s != -1) { 77 | int best = -1; 78 | found[s] = true; 79 | for (int k = 0; k < N; k++) { 80 | if (found[k]) continue; 81 | Relax(s, k, cap[s][k] - flow[s][k], cost[s][k], 1); 82 | Relax(s, k, flow[k][s], -cost[k][s], -1); 83 | if (best == -1 || dist[k] < dist[best]) best = k; 84 | } 85 | s = best; 86 | } 87 | 88 | for (int k = 0; k < N; k++) 89 | pi[k] = min(pi[k] + dist[k], INF); 90 | return width[t]; 91 | } 92 | 93 | pair GetMaxFlow(int s, int t) { 94 | L totflow = 0, totcost = 0; 95 | while (L amt = Dijkstra(s, t)) { 96 | totflow += amt; 97 | for (int x = t; x != s; x = dad[x].first) { 98 | if (dad[x].second == 1) { 99 | flow[dad[x].first][x] += amt; 100 | totcost += amt * cost[dad[x].first][x]; 101 | } else { 102 | flow[x][dad[x].first] -= amt; 103 | totcost -= amt * cost[x][dad[x].first]; 104 | } 105 | } 106 | } 107 | return make_pair(totflow, totcost); 108 | } 109 | }; 110 | // END 111 | int cnt[28]; 112 | int main() 113 | { 114 | int i,n,j; 115 | string t; 116 | cin>>t; 117 | int lenT = t.length(); 118 | clr(cnt); 119 | fo(i, lenT)cnt[t[i]-'a']++; 120 | cin>>n; 121 | MinCostMaxFlow A(n+28); 122 | int source = n+26 , sink = n+27; 123 | fo(i, 26) A.AddEdge(n+i, sink, cnt[i], 0); 124 | fo(i, n){ 125 | string s; 126 | cin>>s; 127 | int v; 128 | cin>>v; 129 | clr(cnt); 130 | fo(j, s.size()) cnt[s[j]-'a']++; 131 | fo(j, 26) 132 | A.AddEdge(i, n+j, cnt[j], 0); 133 | A.AddEdge(source, i, v, i+1); 134 | } 135 | pair res = A.GetMaxFlow(source, sink); 136 | if (res.F != lenT)cout<<-1; 137 | else cout< 2 | using namespace std; 3 | const int mod = 1'000'000'007; 4 | 5 | int mpow(int base, int exp) { 6 | int result = 1; 7 | while (exp > 0) { 8 | if (exp & 1) result = ((long long)result * base) % mod; 9 | base = ((long long)base * base) % mod; 10 | exp >>= 1; 11 | } 12 | return result; 13 | } 14 | 15 | namespace NcR { 16 | int fact[200005],ifact[200005]; 17 | int get(int n, int r) { 18 | if(n=0; i--) { 30 | ifact[i] = (ifact[i+1] * 1LL * (i+1))%mod; 31 | } 32 | } 33 | }; 34 | 35 | int main() { 36 | 37 | NcR::init(); 38 | cout << NcR::get(4, 2) << endl; 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Library/Math/Seive/euler_phi.cpp: -------------------------------------------------------------------------------- 1 | const int MAX = 1000001; 2 | int phi[MAX]; 3 | 4 | void euler_phi() { 5 | phi[1] = 1; 6 | for(int i=2; i extended_gcd(var a, var b){ 7 | bool swp = 0; 8 | if (a K; 12 | var k, r, FF, SS; 13 | while(1){ 14 | k = a/b; 15 | r = a - k*b; 16 | if(r == 1){ 17 | FF = 1, SS = -k; 18 | reverse(all(K)); 19 | for(int k: K){ 20 | var tem = FF; 21 | FF = SS; 22 | SS = tem - SS * k; 23 | } 24 | return swp?mp(SS, FF):mp(FF, SS); 25 | } 26 | else{ 27 | K.pb(k); 28 | } 29 | a = b; 30 | b = r; 31 | } 32 | } 33 | var solve(var a, var b, var n){ 34 | pair ans = extended_gcd(a, n); 35 | var x = ( ans.F * b ) % n; 36 | if ( x < 0) 37 | x += n; 38 | 39 | //a*x is b (mod n) 40 | return x; 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Library/Math/Seive/seive_totient.cpp: -------------------------------------------------------------------------------- 1 | //prime[i] is smallest prime that divides i 2 | vector primes; 3 | const int NN = 1e6+1; 4 | int prime[NN]; 5 | void seive(){ 6 | ll i; 7 | Fo(i, 1, NN) prime[i] = i; 8 | prime[0] = prime[1] = 0; 9 | for(i=2; i < NN; i++){ 10 | if (prime[i] == i){ 11 | 12 | for(ll j = 2*i; j < NN; j += i) 13 | if (prime[j] == j) 14 | prime[j] = i; 15 | } 16 | } 17 | for(i=2; i1){ 32 | n2 /= n; 33 | n1 *= n-1; 34 | } 35 | return n1*n2; 36 | } 37 | -------------------------------------------------------------------------------- /Library/Math/SmallestPrimeSeive.cpp: -------------------------------------------------------------------------------- 1 | const int M = 1e6+3; 2 | int pr[M]; 3 | //pr[6] = 2 and not 3 4 | void pre() 5 | { 6 | int i; 7 | pr[1] = 1; pr[2] = 2; 8 | fo(i, M) pr[i] = i; 9 | for(i=2; i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | 8 | int main() 9 | { 10 | bigint a = bigint("1"); 11 | int b = 2; 12 | for(int i=1; i<100; i++) 13 | { 14 | a = a*b; 15 | } 16 | 17 | cout << a << endl; 18 | 19 | for(int i=1; i<99; i++) 20 | { 21 | a /= b; 22 | } 23 | 24 | cout << a << endl; 25 | } 26 | -------------------------------------------------------------------------------- /Library/Math/dec2bin.cpp: -------------------------------------------------------------------------------- 1 | //the bit size 2 | #define szz 17 3 | void go(ll no, vector &a){ 4 | a.clear(); 5 | while(no){ 6 | a.push_back(no%2); 7 | no /= 2; 8 | } 9 | int left = szz-a.size(); 10 | while(left--) a.pb(0); 11 | //If you uncomment the following 10 will become -> 00000000000001010 12 | // reverse(a.begin(), a.end()); 13 | } 14 | -------------------------------------------------------------------------------- /Library/Math/fact_ncr.cpp: -------------------------------------------------------------------------------- 1 | const int N = 1e6; 2 | ll fac[N], inv[N], b[N]; 3 | void pre(){ 4 | int i; 5 | fac[0] = inv[0] = 1; 6 | fac[1] = inv[1] = 1; 7 | Fo(i, 2, N){ 8 | fac[i] = (i*fac[i-1])%mod; 9 | inv[i] = (mpow(i, mod-2)*inv[i-1])%mod; 10 | } 11 | } 12 | ll C(int n, int r){ 13 | if (r>n)return 0; 14 | ll ans = fac[n]; 15 | ans *= inv[r]; 16 | ans %= mod; 17 | ans *= inv[n-r]; 18 | ans %= mod; 19 | return ans; 20 | } 21 | -------------------------------------------------------------------------------- /Library/Math/matrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | template class matrix 5 | { 6 | public: 7 | typedef T value_type; 8 | private: 9 | vector > M; 10 | public: 11 | matrix(){} 12 | 13 | matrix(int rSize,int cSize) 14 | { 15 | M.assign(rSize,vector(cSize)); 16 | } 17 | void assign(int rSize,int cSize) 18 | { 19 | M.assign(rSize,vector(cSize)); 20 | } 21 | 22 | vector& operator[](int i) 23 | { 24 | return M[i]; 25 | } 26 | 27 | int rowSize() const 28 | { 29 | return M.size(); 30 | } 31 | int columnSize() const 32 | { 33 | if(M.size()==0) 34 | return 0; 35 | else 36 | return M[0].size(); 37 | } 38 | matrix operator *(matrix B) //assumes matricces are multiplicable 39 | { 40 | matrix &A=*this; 41 | matrix temp(A.rowSize(),B.columnSize()); 42 | 43 | for(int i=0;i operator %(value_type MOD) 52 | { 53 | matrix temp(rowSize(),columnSize()); 54 | for(int i=0;i identity(int i) 65 | { 66 | matrix X; 67 | X.assign(i,i); 68 | for(int j=0;j T p(T &n,long long m,int MOD) 74 | { 75 | if(m==0) 76 | return matrix::identity(n.rowSize()); 77 | 78 | T x=p(n,m/2,MOD); 79 | if(m%2==0) 80 | return (x*x)%MOD; 81 | else 82 | return (((x*x)%MOD)*n)%MOD; 83 | } 84 | template void printMatrix(matrix X) 85 | { 86 | for(int i=0;i T(26,26); 97 | for(int i=0;i>T[i][j]; 100 | 101 | const int MOD = 1000000007; 102 | int t; 103 | cin>>t; 104 | while(t--){ 105 | char endChar; 106 | long long length; 107 | cin>>endChar>>length; 108 | matrix solutionMatrix = p(T,length-1, MOD); 109 | long long solution = 0; 110 | for(int i=0;i mat; 4 | matrix(){ 5 | ; 6 | } 7 | matrix(int x, int y = 0, int iden = 0){ 8 | n = x; m = y; 9 | if(y==0) m = n; 10 | mat = vector(n, vi(m, 0)); 11 | if(iden){ 12 | int i; 13 | fo(i, n) mat[i][i] = 1; 14 | } 15 | } 16 | void out(){ 17 | int i, j; 18 | fo(i, n){fo(j, m)cout<=mod) ans -= mod; 26 | } 27 | return ans; 28 | } 29 | int colsum(int x){ 30 | int i; 31 | ll ans = 0; 32 | fo(i, n){ 33 | ans += mat[i][x]; 34 | if (ans>=mod) ans -= mod; 35 | } 36 | return ans; 37 | } 38 | }; 39 | matrix operator *(matrix a, matrix b){ 40 | matrix c = matrix(a.n); 41 | int i, j, k, n = c.n; 42 | fo(i, n)fo(j, n){ 43 | int &val = c.mat[i][j]; 44 | val = 0; 45 | fo(k, n){ 46 | val += (a.mat[i][k]*1LL*b.mat[k][j])%mod; 47 | if (val >= mod) val -= mod; 48 | } 49 | } 50 | return c; 51 | } 52 | matrix operator *(int a, matrix b){ 53 | matrix c = matrix(a.n); 54 | int i, j, k, n = c.n; 55 | fo(i, n)fo(j, n){ 56 | int &val = c.mat[i][j]; 57 | val = (a*b.mat[i][j])%mod; 58 | } 59 | return c; 60 | } 61 | matrix operator +(matrix a, matrix b){ 62 | matrix c = matrix(a.n); 63 | int i, j, k, n = c.n; 64 | fo(i, n)fo(j, n){ 65 | int &val = c.mat[i][j]; 66 | val = (a.mat[i][j]+b.mat[i][j]); 67 | if (val >= mod) val -= mod; 68 | } 69 | return c; 70 | } 71 | matrix operator -(matrix a, matrix b){ 72 | matrix c = matrix(a.n); 73 | int i, j, k, n = c.n; 74 | fo(i, n)fo(j, n){ 75 | int &val = c.mat[i][j]; 76 | val = (a.mat[i][j]-b.mat[i][j]); 77 | if (val >= mod) val -= mod; 78 | if (val < 0) val += mod; 79 | } 80 | return c; 81 | } 82 | matrix operator %(matrix M, int MOD) 83 | { 84 | matrix temp(M.n); 85 | for(int i=0;i 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | 6 | int T; 7 | ll mod; 8 | 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}; 9 | ll a[]={1996011519951206ll,1995120619960115ll,1995100319960115ll,195100319951206ll,1996011519951003ll}; 10 | 11 | 12 | ll multi(ll x,ll y) 13 | { 14 | ll w=x*y-mod*(ll(double(x)*y/mod+1e-3)); 15 | while(w<0) 16 | w+=mod; 17 | while(w>=mod) 18 | w-=mod; 19 | return w; 20 | } 21 | 22 | ll pow(ll x,ll y) 23 | { 24 | ll t=1; 25 | while(y) 26 | { 27 | if(y&1) 28 | t=multi(t,x); 29 | x=multi(x,x); 30 | y>>=1; 31 | } 32 | return t; 33 | } 34 | 35 | bool judge(ll n) 36 | { 37 | if(n==2) return true; 38 | if(n<2||!(n&1)) return false; 39 | for(int i=0;i<25;i++) 40 | if(n%b[i]==0&&n!=b[i]) 41 | return false; 42 | mod=n; 43 | int t=0; 44 | ll u=n-1; 45 | while(!(u&1)) t++,u>>=1; 46 | for(int i=0;i<5;i++) 47 | { 48 | ll x=a[i]%(n-1)+1; 49 | x=pow(x,u); 50 | ll y=x; 51 | for(int j=1;j<=t;j++) 52 | { 53 | x=multi(x,x); 54 | if(x==1&&y!=1&&y!=n-1) 55 | return false; 56 | y=x; 57 | } 58 | if(x!=1) return false; 59 | } 60 | return true; 61 | } 62 | 63 | int main() 64 | { 65 | // judge(n) check whether a number is prime or not 66 | // ll n,lower,upper,count=0,numcount=0; 67 | // lower=3; upper=19; 68 | // for(n=lower;n<=upper;n=n+4) 69 | // { 70 | // if(judge(n)) cout< 2 | using namespace std; 3 | struct PT{ 4 | double x, y; 5 | PT(){} 6 | PT(int a, int b){ 7 | x = a, y = b; 8 | } 9 | PT unit(){ 10 | return PT(x/mag(), y/mag()); 11 | } 12 | double mag(){ 13 | return sqrt(x*x+y*y); 14 | } 15 | }; 16 | //returns dot product 17 | double operator*(PT &a, PT &b){ 18 | return a.x*b.x + a.y*b.y; 19 | } 20 | #define PI 3.1415926535897932384626 21 | double ang(PT &a, PT &b){ 22 | double c0 = (a*b)/(a.mag()*b.mag()); 23 | return acos(c0)*180/PI; 24 | } 25 | 26 | int main() { 27 | // your code goes here 28 | PT a(1, 0); 29 | PT b(-2, 2); 30 | cout< 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;in;k pii; 20 | typedef pair pll; 21 | typedef vector vi; 22 | typedef vector vl; 23 | typedef vector vpii; 24 | typedef vector vpll; 25 | typedef vector vvi; 26 | typedef vector vvl; 27 | const int mod = 1000000007; 28 | //http://codeforces.com/gym/100570/problem/D 29 | //"2-sat" and "small to large" merging 30 | //N must be atleast twice the value of nodes 31 | const int N = 5e5; 32 | 33 | int a[N], par[N], n, q; 34 | map mep; 35 | vi comp[N]; 36 | 37 | void add(ll &x){ 38 | if (mep.find(x) == mep.end()) 39 | mep[x] = mep.size(); 40 | x = mep[x]; 41 | } 42 | 43 | void out(){ 44 | while(q++ < n) printf("No\n"); 45 | exit(0); 46 | } 47 | void merge(int u, int v){ 48 | u = par[u]; 49 | v = par[v]; 50 | if (u == v) return; 51 | if ((int)comp[u].size() > (int)comp[v].size()) swap(u, v); 52 | //v is bada 53 | vi &r = comp[v]; 54 | // each time we merge two components 55 | // size increases atleast by 2 * chote set ka size 56 | //each node can move at most log2(n) times 57 | // n * log(n) complexity mei merge hojayega 58 | for(int x: comp[u]){ 59 | if (par[x^1] == v) out(); 60 | r.pb(x); 61 | par[x] = v; 62 | } 63 | } 64 | int main() 65 | { 66 | //ios_base::sync_with_stdio(false); 67 | //cin.tie(NULL); 68 | int i,k,j; 69 | si(n); 70 | ll x, y, a, b; 71 | fo(i, N) par[i] = i, comp[i].clear(), comp[i].pb(i); 72 | fo(i, n){ 73 | q = i; 74 | sl(x); sl(y); sl(a); sl(b); 75 | y = -y; 76 | add(x); add(y); 77 | x *= 2; 78 | y *= 2; 79 | if (a == b){ 80 | merge(x, y); 81 | merge(x^1, y^1); 82 | } 83 | else{ 84 | merge(x, y^1); 85 | merge(x^1, y); 86 | } 87 | printf("Yes\n"); 88 | } 89 | 90 | return 0; 91 | } 92 | 93 | -------------------------------------------------------------------------------- /Library/Miscellanious/MosMaxFrequency.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 20 | typedef pair pll; 21 | typedef vector vi; 22 | typedef vector vl; 23 | typedef vector vpii; 24 | typedef vector vpll; 25 | typedef vector vvi; 26 | typedef vector vvl; 27 | const int mod = 2e5; 28 | const int N = 3e5; 29 | vi g[N]; 30 | int a[N]; 31 | void dfs(int u, int par); 32 | //http://codeforces.com/contest/600/problem/E 33 | static int t = 0; 34 | int BLOCK = sqrt(mod); 35 | bool f(pair a, pair b){ 36 | if (a.S.F / BLOCK != b.S.F / BLOCK) return a.S.F < b.S.F; 37 | return a.S.S < b.S.S; 38 | } 39 | 40 | ll sum = 0, occ = 0; 41 | ll ans[N], val[N]; 42 | int cnt[N], col[N], rep[N], in[N], out[N], agla[N], pre[N]; 43 | set dom; 44 | set mx; 45 | //ADD , DEL a number and store the sum of max occuring nos in 'sum' 46 | void add(int pos){ 47 | //c is the variable that we are adding here 48 | int c = rep[pos]; 49 | val[cnt[c]] -= c; 50 | int pr = pre[cnt[c]]; 51 | int nxt = agla[cnt[c]]; 52 | if (val[cnt[c]] == 0) { 53 | if (nxt == cnt[c]){ 54 | //this is highest 55 | occ = pr; 56 | agla[pr] = pr; 57 | } 58 | else{ 59 | pre[nxt] = pr; 60 | agla[pr] = nxt; 61 | } 62 | agla[cnt[c]] = pre[cnt[c]] = -1; 63 | } 64 | cnt[c]++; 65 | val[cnt[c]] += c; 66 | 67 | if (cnt[c] > occ){ 68 | agla[occ] = cnt[c]; 69 | pre[cnt[c]] = occ; 70 | occ = cnt[c]; 71 | } 72 | else if (cnt[c] < nxt){ 73 | agla[pr] = cnt[c]; 74 | pre[cnt[c]] = pr; 75 | agla[cnt[c]] = nxt; 76 | pre[nxt] = cnt[c]; 77 | } 78 | agla[occ] = occ; 79 | sum = val[occ]; 80 | } 81 | void del(int pos){ 82 | int c = rep[pos]; 83 | val[cnt[c]] -= c; 84 | int pr = pre[cnt[c]]; 85 | int nxt = agla[cnt[c]]; 86 | if (val[cnt[c]] == 0) { 87 | if (nxt == cnt[c]){ 88 | //this is highest 89 | occ = pr; 90 | agla[pr] = pr; 91 | } 92 | else{ 93 | pre[nxt] = pr; 94 | agla[pr] = nxt; 95 | } 96 | agla[cnt[c]] = pre[cnt[c]] = -1; 97 | } 98 | cnt[c]--; 99 | val[cnt[c]] += c; 100 | if (cnt[c] > occ){ 101 | agla[occ] = cnt[c]; 102 | pre[cnt[c]] = occ; 103 | occ = cnt[c]; 104 | } 105 | else if (cnt[c] > pr){ 106 | agla[pr] = cnt[c]; 107 | pre[cnt[c]] = pr; 108 | agla[cnt[c]] = nxt; 109 | pre[nxt] = cnt[c]; 110 | } 111 | agla[occ] = occ; 112 | sum = val[occ]; 113 | } 114 | int main() 115 | { 116 | ios_base::sync_with_stdio(false); 117 | cin.tie(NULL); 118 | int n, i; 119 | si(n); 120 | set dis_col; 121 | fo (i, n) si(col[i+1]), dis_col.insert(col[i+1]); 122 | tr(it, dis_col) val[0] += *it; 123 | 124 | fo(i, n-1){ 125 | int u, v; 126 | si(u); si(v); 127 | g[u].pb(v); 128 | g[v].pb(u); 129 | } 130 | dfs(1, 0); 131 | vector< pair > Q; 132 | Fo(i, 1, n+1) Q.pb( { i, {in[i], out[i]} } ); 133 | sort(Q.begin(), Q.end(), f); 134 | int L , R, curl, curr; 135 | curl = curr = 0; 136 | fo(i, n){ 137 | pair q = Q[i]; 138 | L = q.S.F, R = q.S.S; 139 | 140 | while( curl > L){ 141 | add(curl-1); 142 | curl--; 143 | } 144 | while( curr < R){ 145 | add(curr+1); 146 | curr++; 147 | } 148 | while( curl < L){ 149 | del(curl); 150 | curl++; 151 | } 152 | while( curr > R){ 153 | del(curr); 154 | curr--; 155 | } 156 | ans[q.F] = sum; 157 | } 158 | Fo(i, 1, n+1) printf("%I64d ",ans[i]); 159 | return 0; 160 | } 161 | 162 | void dfs(int u, int par){ 163 | in[u] = ++t; 164 | rep[t] = col[u]; 165 | for(int v:g[u]){ 166 | if (v == par) continue; 167 | dfs(v, u); 168 | } 169 | out[u] = ++t; 170 | rep[t] = col[u]; 171 | } 172 | -------------------------------------------------------------------------------- /Library/Miscellanious/RollingHash.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | typedef long long HashInt; 6 | static const HashInt HASH_MOD = 2'000'000'033; 7 | struct ModBasedHashInt { 8 | HashInt x; ModBasedHashInt(HashInt x=0) : x(x) {} 9 | ModBasedHashInt operator+(ModBasedHashInt o) { 10 | HashInt y = x + o.x; 11 | return y - (y >= HASH_MOD) * HASH_MOD; 12 | } 13 | ModBasedHashInt operator*(ModBasedHashInt o) { return x*o.x % HASH_MOD; } 14 | HashInt operator-(ModBasedHashInt o) { 15 | HashInt y = x - o.x; 16 | return y + (y < 0) * HASH_MOD; 17 | } 18 | }; 19 | struct RollingHash { 20 | #define sz(x) ((int)x.size()) 21 | vector hash, power; 22 | HashInt C; 23 | RollingHash(string& str, HashInt Co) : hash(sz(str)+1, 0), power(hash) { 24 | C = Co; 25 | power[0] = 1; 26 | for(int i=0; i 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 20 | typedef pair pll; 21 | typedef vector vi; 22 | typedef vector vl; 23 | typedef vector vpii; 24 | typedef vector vpll; 25 | typedef vector vvi; 26 | typedef vector vvl; 27 | const int mod = 1000000007; 28 | const int N = 3e5; 29 | vi g[N]; 30 | int a[N]; 31 | 32 | //BEGIN 33 | map cnt[N], val[N]; 34 | int id[N], col[N]; 35 | ll ans[N]; 36 | //http://codeforces.com/contest/600/problem/E 37 | //Notice how ids of u and v swap due to & 38 | void merge(int &u, int &v){ 39 | if ((int)cnt[u].size() > (int)cnt[v].size()) swap(u, v); 40 | for (auto it: cnt[u]){ 41 | int c = it.F; int occ = it.S; 42 | val[v][cnt[v][c]] -= c; 43 | cnt[v][c] += occ; 44 | val[v][cnt[v][c]] += c; 45 | } 46 | } 47 | void dfs(int u, int par){ 48 | id[u] = u; 49 | cnt[u][col[u]] = 1; 50 | val[u][1] = col[u]; 51 | for(int v: g[u]){ 52 | if (v == par) continue; 53 | dfs(v, u); 54 | merge(id[v], id[u]); 55 | } 56 | ans[u] = val[id[u]].rbegin()->S; 57 | } 58 | //END 59 | int main() 60 | { 61 | ios_base::sync_with_stdio(false); 62 | cin.tie(NULL); 63 | int i,n,k,j, u, v; 64 | cin>>n; 65 | fo(i, n) cin>>col[i+1]; 66 | fo(i, n-1){ 67 | cin>>u>>v; 68 | g[u].pb(v); 69 | g[v].pb(u); 70 | } 71 | dfs(1, 0); 72 | Fo(i, 1, n+1) cout<'9';ip=gc()) 3 | if(ip=='-'){flag=-1;ip=gc();break;} 4 | for(;ip>='0'&&ip<='9';ip=gc())ret=(ret<<1)+(ret<<3)+ip-'0';ret*=flag; 5 | } 6 | 7 | void sl(ll &ret) { 8 | int ip=gc(),flag=1;ret=0;for(;ip<'0'||ip>'9';ip=gc()) 9 | if(ip=='-'){flag=-1;ip=gc();break;} 10 | for(;ip>='0'&&ip<='9';ip=gc())ret=(ret<<1)+(ret<<3)+ip-'0';ret*=flag; 11 | } -------------------------------------------------------------------------------- /Library/Miscellanious/hash_adjaceny_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | //http://codeforces.com/contest/794/submission/27087664 3 | using namespace std; 4 | #define gc getchar_unlocked 5 | #define fo(i,n) for(i=0;in;k pii; 24 | typedef pair pl; 25 | typedef vector vi; 26 | typedef vector vl; 27 | typedef vector vpii; 28 | typedef vector vpl; 29 | typedef vector vvi; 30 | typedef vector vvl; 31 | int mpow(int base, int exp); 32 | void ipgraph(int m); 33 | void dfs(int u, int par); 34 | const ll mod = 1000000007*1LL*1000000007; 35 | const int N = 3e5 + 3, M = N; 36 | //======================= 37 | 38 | set g[N]; 39 | int sz[N], par[N]; 40 | int rep(int x){ 41 | if(x == par[x]) return x; 42 | return par[x] = rep(par[x]); 43 | } 44 | void unite(int x, int y){ 45 | x = rep(x); 46 | y = rep(y); 47 | if(x==y)return; 48 | if(sz[x] taken; 60 | set allvals; 61 | map com; 62 | int ass[N], T; 63 | void go(int u){ 64 | 65 | int cur = ass[u]; 66 | for(int v: g[u]){ 67 | if(ass[v]){ 68 | if(abs(ass[v]-ass[u])>1){ 69 | cout <<"NO\n"; 70 | exit(0); 71 | } 72 | } 73 | else{ 74 | if(!taken[cur+1]) 75 | ass[v] = cur+1; 76 | else if(!taken[cur-1]) 77 | ass[v] = cur-1; 78 | else{ 79 | cout <<"NO\n"; 80 | exit(0); 81 | } 82 | T = max(T, ass[v]+2); 83 | taken[ass[v]] = 1; 84 | go(v); 85 | } 86 | } 87 | } 88 | int main() 89 | { 90 | ios_base::sync_with_stdio(false); 91 | cin.tie(NULL); 92 | int i,n,k,j, u, v, x, y, a, b, c, m; 93 | cin >> n >> m; 94 | srand(1234); 95 | Fo(i, 1, n+1) h[i] = (r()*r()+r())%mod; 96 | Fo(i, 1, n+1){ 97 | par[i] = i; 98 | sz[i] = 0; 99 | } 100 | fo(i, m) { 101 | cin >> u >> v; 102 | g[u].insert(v); 103 | g[v].insert(u); 104 | } 105 | Fo(i, 1, n+1){ 106 | val[i] = h[i]; 107 | for(int x: g[i]){ 108 | val[i] = (val[i] + h[x])%mod; 109 | } 110 | allvals.insert(val[i]); 111 | com[val[i]].pb(i); 112 | } 113 | for(ll c: allvals){ 114 | int x = com[c].size(); 115 | if(x>1){ 116 | u = com[c][0]; 117 | for(int v: com[c]) 118 | unite(u, v); 119 | } 120 | } 121 | Fo(i, 1, n+1){ 122 | set allnew; allnew.clear(); 123 | for(int v: g[i]){ 124 | allnew.insert(rep(v)); 125 | } 126 | g[i].clear(); 127 | for(int v: allnew) { 128 | if(v != i) 129 | g[i].insert(v); 130 | } 131 | int nsz = g[i].size(); 132 | if(nsz > 2 and i == rep(i)){ 133 | cout <<"NO\n"; 134 | return 0; 135 | } 136 | } 137 | T = n+2; //take it bigger enough to avoid negative values 138 | Fo(i, 1, n+1){ 139 | u = rep(i); 140 | if(u != i) continue; 141 | if(!ass[i]) ass[i] = T,taken[T] = 1, go(i); 142 | } 143 | cout<<"YES\n"; 144 | Fo(i, 1, n+1){ 145 | cout << ass[rep(i)] << " "; 146 | } 147 | return 0; 148 | } 149 | -------------------------------------------------------------------------------- /Library/Miscellanious/hash_unordered_map.cpp: -------------------------------------------------------------------------------- 1 | template 2 | inline void hash_combine(std::size_t & seed, const T & v) 3 | { 4 | std::hash hasher; 5 | seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); 6 | } 7 | 8 | namespace std 9 | { 10 | template struct hash> 11 | { 12 | inline size_t operator()(const pair & v) const 13 | { 14 | size_t seed = 0; 15 | ::hash_combine(seed, v.first); 16 | ::hash_combine(seed, v.second); 17 | return seed; 18 | } 19 | }; 20 | } 21 | //use it now 22 | unordered_map dp; 23 | -------------------------------------------------------------------------------- /Library/Miscellanious/meet-in-middle.cpp: -------------------------------------------------------------------------------- 1 | //http://codeforces.com/contest/525/problem/E 2 | #include 3 | using namespace std; 4 | #define gc getchar_unlocked 5 | #define fo(i,n) for(i=0;in;k pii; 24 | typedef pair pll; 25 | typedef vector vi; 26 | typedef vector vll; 27 | typedef vector vpii; 28 | typedef vector vpll; 29 | typedef vector vvi; 30 | typedef vector vvl; 31 | const int mod = 1000000007; 32 | const int N = 3e5; 33 | vi g[N]; 34 | int a[N]; 35 | vi rep(int no, int len, int base){ 36 | vi ans; 37 | while(no){ 38 | ans.pb(no%base); 39 | no /= base; 40 | } 41 | while((int)ans.size() != len) ans.pb(0); 42 | reverse(all(ans)); 43 | return ans; 44 | } 45 | map cnt[30]; 46 | ll fac[20]; 47 | int main() 48 | { 49 | ios_base::sync_with_stdio(false); 50 | cin.tie(NULL); 51 | int i,n,k,j, mask; 52 | ll s, ans = 0; 53 | cin>>n>>k>>s; 54 | fo(i, n) cin>>a[i]; 55 | int len = n/2, left = n-len; 56 | int lim = pow(3, len); 57 | fo(i, n+1) cnt[i].clear(); 58 | fac[1] = 1; 59 | Fo(i, 2, 20) fac[i] = fac[i-1]*i; 60 | fo(mask, lim){ 61 | vi bit = rep(mask, len, 3); 62 | int used = 0; 63 | ll sum = 0; 64 | fo(i, bit.size()){ 65 | int dig = bit[i]; 66 | if(dig==0)continue; 67 | else if(dig==1) sum += a[i]; 68 | else if (a[i]<20)sum += fac[a[i]], used++; 69 | else if(a[i]>=20) { 70 | sum = -1; 71 | break; 72 | } 73 | } 74 | if(sum>=0){ 75 | // for(int x:bit) cout<=20) { 95 | sum = -1; 96 | break; 97 | } 98 | } 99 | if(sum>=0){ 100 | int remk = k-used; 101 | ll need = s-sum; 102 | while(remk>=0 and need>=0 ){ 103 | if(cnt[remk].count(need)) 104 | ans += cnt[remk][need]; 105 | remk--; 106 | } 107 | } 108 | } 109 | 110 | cout< 2.35 and not 2.34 as in scientific 2 | void out(double x, int n){ 3 | cout< 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;in;k pii; 23 | typedef pair pl; 24 | typedef vector vi; 25 | typedef vector vl; 26 | typedef vector vpii; 27 | typedef vector vpl; 28 | typedef vector vvi; 29 | typedef vector vvl; 30 | int mpow(int base, int exp); 31 | void ipgraph(int m); 32 | void dfs(int u, int par); 33 | const int mod = 1000000007; 34 | const int N = 3e5, M = N; 35 | //======================= 36 | 37 | vi g[N]; 38 | int a[N]; 39 | /* 40 | Input: A vector of intervals in any random order 41 | Output: 42 | 1. Removes redundant intervals ie remove [2,3] if [1,4] is present. 43 | 2. does NOT merge overlapping intervals. 44 | 3. Sorted in ascending order of starting interval which are distinct. 45 | */ 46 | void fun_interval(vpii &in){ 47 | int i = 1, n = in.size(); 48 | 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; 53 | hi = in[i].S; 54 | took.pb(in[i]); 55 | } 56 | in.clear(); 57 | for(pii x: took) in.pb(x); 58 | // Uncomment the following lines, if you wish to sort intervals on asc order of HI value. 59 | // for(auto& x: in) swap(x.F,x.S); // [lo, hi] is converted to [hi, lo]. 60 | // sort(in.begin(), in.end(), [](pii x, pii y){return x.F> n; 68 | vpii in(n, {0,0}); 69 | fo(i, n) cin >> in[i].F >> in[i].S ; 70 | fun_interval(in); 71 | for(pii x: in) cout << x.F << " " << x.S << endl; 72 | 73 | return 0; 74 | } 75 | /* 76 | Input: 77 | 5 78 | 1 4 79 | 0 3 80 | 2 3 81 | 0 5 82 | 3 9 83 | Output: 84 | 0 5 85 | 3 9 86 | */ 87 | -------------------------------------------------------------------------------- /Library/Miscellanious/parallel_binary_search.cpp: -------------------------------------------------------------------------------- 1 | //http://agc002.contest.atcoder.jp/tasks/agc002_d 2 | #include 3 | using namespace std; 4 | #define gc getchar_unlocked 5 | #define fo(i,n) for(i=0;i pii; 21 | typedef pair pll; 22 | typedef vector vi; 23 | typedef vector vl; 24 | typedef vector vpii; 25 | typedef vector vpll; 26 | typedef vector vvi; 27 | typedef vector vvl; 28 | const int mod = 1000000007; 29 | const ll N = 3e5; 30 | vi g[N]; 31 | pii E[N]; 32 | int mpow(int base, int exp); 33 | void ipgraph(int n, int m); 34 | void dfs(int u, int par); 35 | struct node{ 36 | int i, a, b, z; 37 | }; 38 | int T, n, m, ans[N], rep[N], sz[N]; 39 | vector Q; 40 | int get(int x){ 41 | if (x == rep[x]) return x; 42 | return rep[x] = get(rep[x]); 43 | } 44 | void merge(int x, int y){ 45 | x = get(x); 46 | y = get(y); 47 | if (x == y) return; 48 | if (sz[x] < sz[y]) rep[x] = y, sz[y] += sz[x]; 49 | else if (sz[x] > sz[y]) rep[y] = x, sz[x] += sz[y]; 50 | else rep[x] = y, sz[y]+=sz[x]; 51 | } 52 | void init(){ 53 | int i; 54 | T = 0; 55 | Fo(i, 1, n+1) rep[i] = i, sz[i] = 1; 56 | } 57 | int go(int x, int y){ 58 | x = get(x), y = get(y); 59 | if (x == y) return sz[x]; 60 | return sz[x] + sz[y]; 61 | } 62 | void solve(){ 63 | queue< tuple> > q; 64 | vector query; 65 | q.push(make_tuple(0, m, Q)); 66 | int L, R, i; 67 | while(!q.empty()){ 68 | 69 | tie(L, R, query) = q.front(); q.pop(); 70 | if (L+1 == R){ 71 | for(auto it: query) 72 | ans[it.i] = R; 73 | continue; 74 | } 75 | int mid = (L+R)/2; 76 | vector left, right; left.clear(); right.clear(); 77 | //execute till mid 78 | if (T > mid){ 79 | init(); 80 | T = 0; 81 | } 82 | Fo(i, T+1, mid+1){ 83 | merge(E[i].F, E[i].S); 84 | } 85 | T = mid; 86 | //update range for each query 87 | for(auto it: query){ 88 | if (go(it.a, it.b) >= it.z) left.pb(it); 89 | else right.pb(it); 90 | } 91 | 92 | q.push(make_tuple(L, mid, left)); 93 | q.push(make_tuple(mid, R, right)); 94 | } 95 | 96 | } 97 | int main() 98 | { 99 | ios_base::sync_with_stdio(false); 100 | cin.tie(NULL); 101 | int i,k,j,u,v,w; 102 | cin>>n>>m; 103 | fo(i, m){ 104 | cin>>u>>v; 105 | g[u].pb(v); 106 | g[v].pb(u); 107 | E[i+1] = {u, v}; 108 | } 109 | int q; 110 | cin>>q; 111 | Fo(i, 1, q+1){ 112 | cin>>u>>v>>w; 113 | Q.pb({i, u, v, w}); 114 | } 115 | init(); 116 | solve(); 117 | Fo(i, 1, q+1) 118 | cout<>16) & 0xffff]; 5 | } 6 | 7 | string ThueMorseGame::get(int n,int m) 8 | { 9 | popc[0] = 0; 10 | for (int i = 1; i < (1<<16); i++) popc[i] = popc[i & (i-1)] + 1; 11 | 12 | int currl = 0; 13 | while(currl + m + 1 <= n) 14 | { 15 | currl+= m + 1; 16 | while(currl<=n && (popcount(currl) & 1))++currl; 17 | } 18 | if(currl == n)return "Bob"; 19 | return "Alice"; 20 | } 21 | -------------------------------------------------------------------------------- /Library/Miscellanious/range_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // http://ideone.com/jsXeQn 3 | using namespace std; 4 | #define gc getchar_unlocked 5 | #define fo(i,n) for(i=0;in;k pii; 24 | typedef pair pl; 25 | typedef vector vi; 26 | typedef vector vl; 27 | typedef vector vpii; 28 | typedef vector vpl; 29 | typedef vector vvi; 30 | typedef vector vvl; 31 | int mpow(int base, int exp); 32 | void ipgraph(int m); 33 | void dfs(int u, int par); 34 | const int mod = 1000000007; 35 | const int N = 3e5, M = N; 36 | //======================= 37 | 38 | vi g[N]; 39 | ll a[N]; 40 | //Input: Array and queries asking {sum, no} 41 | // of elements less than given x 42 | //log(n) per query 43 | class RangeSum{ 44 | int n; 45 | vector A; 46 | set> my; 47 | public: 48 | RangeSum(long long a[], int nn){ 49 | sort(a, a+nn); 50 | int i; 51 | n = nn; 52 | A = {0}; 53 | fo(i, n){ 54 | A.push_back(A[i]+a[i]); 55 | my.insert({a[i], i+1}); 56 | } 57 | } 58 | RangeSum(vector &a){ 59 | sort(a.begin(), a.end()); 60 | int i; 61 | n = a.size(); 62 | A = {0}; 63 | fo(i, n){ 64 | A.push_back(A[i]+a[i]); 65 | my.insert({a[i], i+1}); 66 | } 67 | } 68 | //Returns {sum, no} where 69 | // sum = sum of ele <= val 70 | // no = # of ele <= val 71 | pair sum(long long val){ 72 | if(n == 0) return {0, 0}; 73 | auto it = my.lower_bound({val, n+1}); 74 | if(it == my.end()) return {A[n], n}; 75 | if((*it).F == val) return {A[(*it).S], (*it).S}; 76 | return {A[(*it).S-1], (*it).S-1}; 77 | } 78 | pair sum(long long x, long long y){ 79 | if(x>y) swap(x,y); 80 | pl p = sum(y); 81 | pl q = sum(x-1); 82 | return {p.first-q.first, p.second-q.second}; 83 | } 84 | }; 85 | int main() 86 | { 87 | ios_base::sync_with_stdio(false); 88 | cin.tie(NULL); 89 | int i,n,k,j; 90 | cin >> n; 91 | fo(i, n) cin >> a[i]; 92 | RangeSum my(a, n); 93 | cout << my.sum(5).F << " " < 5 | using namespace std; 6 | #define gc getchar_unlocked 7 | #define fo(i,n) for(i=0;in;k pii; 26 | typedef pair pll; 27 | typedef vector vi; 28 | typedef vector vll; 29 | typedef vector vpii; 30 | typedef vector vpll; 31 | typedef vector vvi; 32 | typedef vector vvl; 33 | const int mod = 1000000007; 34 | const int N = 3e5; 35 | vi g[N]; 36 | ll a[N], b[N], t[N]; 37 | ll dp[3][N]; 38 | int main() 39 | { 40 | ios_base::sync_with_stdio(false); 41 | cin.tie(NULL); 42 | int i,n,k,j,m,d; 43 | cin>>n>>m>>d; 44 | fo(i, m) cin>>a[i]>>b[i]>>t[i]; 45 | int cur = 1, pre = 0; 46 | Fo(i, 1, n+1) 47 | dp[cur][i] = b[m-1]-abs(a[m-1]-i); 48 | swap(cur, pre); 49 | Fo(i, m-2, -1){ 50 | deque window; 51 | ll dt = t[i+1]-t[i]; 52 | dt *= d; 53 | k = min(n-1LL, dt); 54 | //moving from right to left 55 | //initially install [n-k+1, n] 56 | //j-k to j+k 57 | Fo(j, n, n-k){ 58 | while(!window.empty() and window.back().F <= dp[pre][j]) 59 | window.pop_back(); 60 | window.pb({dp[pre][j], j}); 61 | } 62 | Fo(j, n, 0){ 63 | 64 | int x = j-k; 65 | //add j-k to window 66 | if (x>0) { 67 | while(!window.empty() and window.back().F <= dp[pre][x]) 68 | window.pop_back(); 69 | window.pb({dp[pre][x], x}); 70 | } 71 | //remove elements at pos > j+k 72 | while(!window.empty() and window.front().S > j+k) window.pop_front(); 73 | dp[cur][j] = b[i]-abs(a[i]-j) + window.front().F; 74 | } 75 | swap(cur, pre); 76 | } 77 | ll ans = -1e17; 78 | Fo(i, 1, n+1) ans = max(ans, dp[pre][i]); 79 | cout< win; 7 | int i; 8 | //move from left to right 9 | //initialse window [0, b-1] 10 | fo(i, b){ 11 | while(!win.empty() and win.back().F <= A[i]) win.pop_back(); 12 | win.pb({A[i], i}); 13 | } 14 | fo(i, n){ 15 | dp[i] = win.front().F; 16 | int x = i+b; 17 | if(x - inf 23 | if(i+b-1 >= n) dp[i] = -inf; 24 | } 25 | } 26 | int main() 27 | { 28 | ios_base::sync_with_stdio(false); 29 | cin.tie(NULL); 30 | int i,n,k,j; 31 | cin >> n; 32 | vi A; 33 | A.resize(n, 0); 34 | fo(i, n) cin >> A[i]; 35 | slide(A, 3); 36 | fo(i, n) cout << dp[i] << " " ; 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Library/Miscellanious/sos_dp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // https://www.hackerearth.com/practice/algorithms/dynamic-programming/bit-masking/practice-problems/algorithm/special-pairs-7/description/ 3 | using namespace std; 4 | #define gc getchar_unlocked 5 | #define fo(i,n) for(i=0;in;k pii; 24 | typedef pair pl; 25 | typedef vector vi; 26 | typedef vector vl; 27 | typedef vector vpii; 28 | typedef vector vpl; 29 | typedef vector vvi; 30 | typedef vector vvl; 31 | int mpow(int base, int exp); 32 | void ipgraph(int m); 33 | void dfs(int u, int par); 34 | const int mod = 1000000007; 35 | const int N = 1LL<<20, M = N; 36 | //======================= 37 | 38 | vi g[N]; 39 | int a[N]; 40 | const int B = 20; 41 | ll dp[N][B]; 42 | int cnt[N]; 43 | void sosdp(){ 44 | int i, j; 45 | fo(i, N){ 46 | dp[i][0] = cnt[i]; 47 | if(i&1) dp[i][0] += cnt[i^1]; 48 | Fo(j, 1, B){ 49 | dp[i][j] = dp[i][j-1]; 50 | if(i&(1<> t; 61 | int allone = 1<> n; 64 | fo(i, n) cin >> a[i], cnt[a[i]]++; 65 | sosdp(); 66 | ll ans = 0; 67 | fo(i, n) ans += dp[allone^a[i]][B-1], cnt[a[i]] = 0; 68 | cout << ans << endl; 69 | } 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /Library/Miscellanious/template-short.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;in;k g[N]; 16 | int a[N]; 17 | 18 | void solve() { 19 | 20 | } 21 | 22 | int main() { 23 | ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); 24 | int t = 1; 25 | cin >> t; 26 | while(t--) { 27 | solve(); 28 | } 29 | return 0; 30 | } 31 | 32 | int mpow(int base, int exp) { 33 | base %= MOD; 34 | int result = 1; 35 | while (exp > 0) { 36 | if (exp & 1) result = ((ll)result * base) % MOD; 37 | base = ((ll)base * base) % MOD; 38 | exp >>= 1; 39 | } 40 | return result; 41 | } -------------------------------------------------------------------------------- /Library/Miscellanious/template_demo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;in;k> t; 99 | deb(t); 100 | 101 | while(t--) { 102 | solve(); 103 | } 104 | 105 | return 0; 106 | } 107 | 108 | int mpow(int base, int exp) { 109 | base %= mod; 110 | int result = 1; 111 | while (exp > 0) { 112 | if (exp & 1) result = ((ll)result * base) % mod; 113 | base = ((ll)base * base) % mod; 114 | exp >>= 1; 115 | } 116 | return result; 117 | } 118 | 119 | void ipgraph(int n, int m){ 120 | int i, u, v; 121 | while(m--){ 122 | cin>>u>>v; 123 | g[u-1].pb(v-1); 124 | g[v-1].pb(u-1); 125 | } 126 | } 127 | 128 | void dfs(int u, int par){ 129 | for(int v:g[u]){ 130 | if (v == par) continue; 131 | dfs(v, u); 132 | } 133 | } 134 | 135 | 136 | -------------------------------------------------------------------------------- /Library/Miscellanious/ternary_search.cpp: -------------------------------------------------------------------------------- 1 | double f(double x){ 2 | double ans = T(dis(x1,Y1, x,0), v1); 3 | ans += T(dis(x2,y2, x,0), v2); 4 | return ans; 5 | } 6 | double ter(double lo, double hi, int iter = 0){ 7 | if (iter == 300) return lo; 8 | double m1 = lo + (hi-lo)/3; 9 | double m2 = hi - (hi-lo)/3; 10 | if (f(m1) > f(m2)) return ter(m1, hi, iter+1); 11 | else return ter(lo, m2, iter+1); 12 | } 13 | -------------------------------------------------------------------------------- /Library/Miscellanious/z-algo.cpp: -------------------------------------------------------------------------------- 1 | //Z-Algorithm 2 | //z[i] is length of prefix starting from i 3 | 4 | // always pass stirng by reference, weird how it got me SIGSEGV in a Codechef problem 5 | // https://codeforces.com/blog/entry/77906 6 | vector go(const string &s){ 7 | vector z(s.size(), 0); 8 | int i, n = s.size(), L = 0, R = 0; 9 | z[0] = 0; 10 | Fo(i, 1, n){ 11 | if (i > R){ 12 | L = R = i; 13 | while(R 35 | vector z_function(int n, const T &s) { 36 | vector z(n, n); 37 | int l = 0, r = 0; 38 | for (int i = 1; i < n; i++) { 39 | z[i] = (i > r ? 0 : min(r - i + 1, z[i - l])); 40 | while (i + z[i] < n && s[z[i]] == s[i + z[i]]) { 41 | z[i]++; 42 | } 43 | if (i + z[i] - 1 > r) { 44 | l = i; 45 | r = i + z[i] - 1; 46 | } 47 | } 48 | return z; 49 | } 50 | 51 | template 52 | vector z_function(const T &s) { 53 | return z_function((int) s.size(), s); 54 | } 55 | 56 | -------------------------------------------------------------------------------- /Library/Tree/Centroid.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 18 | typedef pair pll; 19 | typedef vector vi; 20 | typedef vector vl; 21 | typedef vector vpii; 22 | typedef vector vpll; 23 | typedef vector vvi; 24 | typedef vector vvl; 25 | const int mod = 1000000007; 26 | const int N = 5e5; 27 | vi g[N]; 28 | int a[N], par[N], ans[N], sz[N]; 29 | int cen, n; 30 | void ipgraph(int n, int m); 31 | void dfs(int u, int p){ 32 | sz[u] = 1; 33 | for( int v: g[u]){ 34 | if (v == p) continue; 35 | dfs(v, u); 36 | sz[u] += sz[v]; 37 | } 38 | } 39 | void dfs2(int u, int p){ 40 | sz[u] = 1; 41 | if ( p == cen ) par[u] = u; 42 | else par[u] = par[p]; 43 | for( int v: g[u]){ 44 | if (v == p) continue; 45 | dfs2(v, u); 46 | sz[u] += sz[v]; 47 | } 48 | } 49 | void go(int u, int p){ 50 | int hai = 1; 51 | for(int v: g[u]){ 52 | if ( v == p ) continue; 53 | if ( sz[v] > n/2 ) hai = 0; 54 | go(v, u); 55 | } 56 | int other = n - sz[u]; 57 | if ( other > n/2 ) hai = 0; 58 | if (hai) cen = u; 59 | } 60 | int main() 61 | { 62 | ios_base::sync_with_stdio(false); 63 | cin.tie(NULL); 64 | int i, m; 65 | cin >> n ; 66 | m = n - 1; 67 | ipgraph(n, n-1); 68 | clr(sz); 69 | par[0] = 0; 70 | dfs(1, 0); 71 | go(1, 0); 72 | dfs2(cen, 0); 73 | int F, S, idx; 74 | F = S = idx = -1; 75 | Fo(i, 1, n+1) { 76 | if (par[i] == i) { 77 | if (sz[i] >= F){ 78 | idx = i; 79 | S = F; 80 | F = sz[i]; 81 | } 82 | else if (sz[i] > S) S = sz[i]; 83 | } 84 | } 85 | Fo(i, 1, n+1){ 86 | if ( i == cen ) { 87 | ans[i] = 1; 88 | continue; 89 | } 90 | int rep = par[i]; 91 | int mx, other; 92 | if ( rep == idx ){ 93 | mx = max(S, F - sz[i]); 94 | } 95 | else mx = F; 96 | other = n - sz[i] - mx; 97 | ans[i] = other <= n/2; 98 | } 99 | Fo(i, 1, n+1) cout<>u>>v; 109 | u++, v++; 110 | g[u-1].pb(v-1); 111 | g[v-1].pb(u-1); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Library/Tree/dp-on-tree-type-c-LCA.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 18 | typedef pair pll; 19 | typedef vector vi; 20 | typedef vector vl; 21 | typedef vector vpii; 22 | typedef vector vpll; 23 | typedef vector vvi; 24 | typedef vector vvl; 25 | const int mod = 1000000007; 26 | const int N = 2e5; 27 | vi g[N]; 28 | const int LG = 20; 29 | //LCA begins 30 | //1 based index 31 | int a[N], lvl[N], P[N][LG]; 32 | void dfs(int u, int par){ 33 | lvl[u] = 1+lvl[par]; 34 | P[u][0] = par; 35 | for(int v:g[u]){ 36 | if (v == par) continue; 37 | dfs(v, u); 38 | } 39 | } 40 | 41 | int lca(int u, int v){ 42 | int i, lg; 43 | if (lvl[u] < lvl[v]) swap(u, v); 44 | 45 | for(lg = 0; (1<=0; i--){ 49 | if (lvl[u] - (1<= lvl[v]) 50 | u = P[u][i]; 51 | } 52 | 53 | if (u == v) 54 | return u; 55 | 56 | for(i=lg; i>=0; i--){ 57 | if (P[u][i] != -1 and P[u][i] != P[v][i]) 58 | u = P[u][i], v = P[v][i]; 59 | } 60 | 61 | return P[u][0]; 62 | } 63 | 64 | //Get the ancestor of node "u" 65 | //which is "dis" distance above. 66 | int getAncestor(int u, int dis){ 67 | dis = lvl[u] - dis; 68 | int i, lg = 0; 69 | for(; (1<=0; i--){ 72 | if (lvl[u] - (1<= dis) 73 | u = P[u][i]; 74 | } 75 | 76 | return u; 77 | } 78 | 79 | //returns the distance between 80 | //two nodes "u" and "v". 81 | int dis(int u, int v){ 82 | if (lvl[u] < lvl[v]) swap(u, v); 83 | int w = lca(u, v); 84 | return lvl[u] + lvl[v] - 2*lvl[w]; 85 | } 86 | 87 | int main() 88 | { 89 | ios_base::sync_with_stdio(false); 90 | cin.tie(NULL); 91 | int i, n, q, m, j; 92 | int u, v; 93 | cin >> n >> m; 94 | fo(i, n-1){ 95 | cin>>u>>v; 96 | g[u].pb(v); 97 | g[v].pb(u); 98 | } 99 | 100 | fo(i, LG) fo(j, n+1) P[j][i] = -1; 101 | lvl[0] = -1; 102 | 103 | dfs(1, 0); 104 | 105 | for(i=1; i 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 18 | typedef pair pll; 19 | typedef vector vi; 20 | typedef vector vl; 21 | typedef vector vpii; 22 | typedef vector vpll; 23 | typedef vector vvi; 24 | typedef vector vvl; 25 | const int mod = 1000000007; 26 | const int N = 2e5; 27 | vi g[N]; 28 | const int LG = 20; 29 | //LCA begins 30 | //1 based index 31 | int a[N], lvl[N], P[N][LG], sz[N]; 32 | void dfs(int u, int par){ 33 | sz[u] = 1; 34 | lvl[u] = 1+lvl[par]; 35 | P[u][0] = par; 36 | for(int v:g[u]){ 37 | if (v == par) continue; 38 | dfs(v, u); 39 | sz[u] += sz[v]; 40 | } 41 | } 42 | 43 | int lca(int u, int v){ 44 | int i, lg; 45 | if (lvl[u] < lvl[v]) swap(u, v); 46 | for(lg = 0; (1<=0; i--){ 49 | if (lvl[u] - (1<= lvl[v]) 50 | u = P[u][i]; 51 | } 52 | if (u == v) return u; 53 | for(i=lg; i>=0; i--){ 54 | if (P[u][i] != -1 and P[u][i] != P[v][i]) 55 | u = P[u][i], v = P[v][i]; 56 | } 57 | return P[u][0]; 58 | } 59 | int get(int u, int dis){ 60 | dis = lvl[u] - dis; 61 | int i, lg = 0; 62 | for(; (1<=0; i--){ 64 | if (lvl[u] - (1<= dis) 65 | u = P[u][i]; 66 | } 67 | return u; 68 | } 69 | int dis(int u, int v){ 70 | if (lvl[u] < lvl[v]) swap(u, v); 71 | int w = lca(u, v); 72 | return lvl[u] + lvl[v] - 2*lvl[w]; 73 | } 74 | int main() 75 | { 76 | ios_base::sync_with_stdio(false); 77 | cin.tie(NULL); 78 | int i,n,q, m, j; 79 | int u, v; 80 | cin>>n>>m; 81 | fo(i, n-1){ 82 | cin>>u>>v; 83 | g[u].pb(v); 84 | g[v].pb(u); 85 | } 86 | fo(i, LG) fo(j, n+1) P[j][i] = -1; 87 | lvl[0] = -1; 88 | dfs(1, 0); 89 | for(i=1; i 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 18 | typedef pair pll; 19 | typedef vector vi; 20 | typedef vector vl; 21 | typedef vector vpii; 22 | typedef vector vpll; 23 | typedef vector vvi; 24 | typedef vector vvl; 25 | const int mod = 1000000007; 26 | const int N = 2e5; 27 | vi g[N]; 28 | const int LG = 20; 29 | #define red 1 30 | #define blue 0 31 | int a[N], col[N], lvl[N], P[N][LG], sz[N]; 32 | ll in[N], out[N]; 33 | void dfs(int u, int par){ 34 | sz[u] = 1; 35 | lvl[u] = 1+lvl[par]; 36 | P[u][0] = par; 37 | in[u] = col[u]==blue?0:mod; 38 | for(int v:g[u]){ 39 | if (v == par) continue; 40 | dfs(v, u); 41 | in[u] = min(in[u], 1+in[v]); 42 | sz[u] += sz[v]; 43 | } 44 | } 45 | void dfs1(int u, int par){ 46 | if (par == 0) out[u] = mod; 47 | else out[u] = 1 + out[par]; 48 | ll F, S; F = S = mod; 49 | for(int v:g[u]){ 50 | if (v == par) continue; 51 | if (F >= in[v]){ 52 | S = F; 53 | F = in[v]; 54 | } 55 | else if ( in[v] < S) S = in[v]; 56 | } 57 | for(int v: g[u]){ 58 | if (v == par) continue; 59 | ll use = F; 60 | if (F == in[v]) use = S; 61 | dfs1(v, u); 62 | out[v] = min(out[v], 2+use); 63 | } 64 | } 65 | //lvl[u] > lvl[v] 66 | int lca(int u, int v){ 67 | int i, lg; 68 | for(lg = 0; (1<=0; i--){ 71 | if (lvl[u] - (1<= lvl[v]) 72 | u = P[u][i]; 73 | } 74 | if (u == v) return u; 75 | for(i=lg; i>=0; i--){ 76 | if (P[u][i] != -1 and P[u][i] != P[v][i]) 77 | u = P[u][i], v = P[v][i]; 78 | } 79 | return P[u][0]; 80 | } 81 | int get(int u, int dis){ 82 | dis = lvl[u] - dis; 83 | int i, lg = 0; 84 | for(; (1<=0; i--){ 86 | if (lvl[u] - (1<= dis) 87 | u = P[u][i]; 88 | } 89 | return u; 90 | } 91 | int dis(int u, int v){ 92 | if (lvl[u] < lvl[v]) swap(u, v); 93 | int w = lca(u, v); 94 | return lvl[u] + lvl[v] - 2*lvl[w]; 95 | } 96 | int main() 97 | { 98 | ios_base::sync_with_stdio(false); 99 | cin.tie(NULL); 100 | int i,n,q, m, j; 101 | int u, v; 102 | cin>>n>>m; 103 | fo(i, n-1){ 104 | cin>>u>>v; 105 | g[u].pb(v); 106 | g[v].pb(u); 107 | } 108 | fo(i, LG) fo(j, n+1) P[j][i] = -1; 109 | lvl[0] = -1; 110 | dfs(1, 0); 111 | dfs1(1, 0); 112 | for(i=1; i>ty>>u; 130 | if (ty == 1) col[u]= red, redd.pb(u); 131 | else { 132 | int ans = mod; 133 | ans = min(in[u], out[u]); 134 | for(int x: redd) ans = min(ans, dis(u, x)); 135 | cout< 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;i pii; 20 | typedef pair pll; 21 | typedef vector vi; 22 | typedef vector vl; 23 | typedef vector vpii; 24 | typedef vector vpll; 25 | typedef vector vvi; 26 | typedef vector vvl; 27 | const ll mod = 1e16; 28 | const int N = 1004, M = 1e5+3; 29 | vi g[M]; 30 | vpii tic[M]; 31 | 32 | //BEGINS 33 | //LCA implemented with sparse table.. 34 | //dp[u][i] gives uth node se 2^i length ke parent tak min value in node. 35 | ll dp[M][20]; 36 | int lvl[M], P[M][20]; 37 | int vis[N]; 38 | 39 | void dfs(int u, int p){ 40 | P[u][0] = p; 41 | lvl[u] = 1+lvl[p]; 42 | for(int v: g[u]){ 43 | if (v != p) dfs(v, u); 44 | } 45 | } 46 | ll get(int u, int l){ 47 | int lg = 0, i; 48 | if (l == 1) return dp[u][0]; 49 | //cout<<"from "<=0; i--){ 55 | if (lvl[u] - (1<= nlev ) 56 | ans = min(ans, dp[u][i]), u = P[u][i]; 57 | } 58 | return ans; 59 | } 60 | 61 | 62 | int main() 63 | { 64 | ios_base::sync_with_stdio(false); 65 | cin.tie(NULL); 66 | if (0){ 67 | freopen("input.txt", "r", stdin); 68 | freopen("output.txt", "w", stdout); 69 | } 70 | int i,n,k,j,m,u,v,w,x; 71 | int t; 72 | cin>>n>>m; 73 | fo(i, n-1){ 74 | cin>>u>>v; 75 | g[v].pb(u); 76 | g[u].pb(v); 77 | } 78 | fo(i, m){ 79 | cin>>u>>k>>w; 80 | tic[u].pb({k, w}); 81 | } 82 | Fo(i, 0, 20) 83 | Fo(j, 0, n+1) P[j][i] = -1; 84 | lvl[0] = -1; 85 | dfs(1, 0); 86 | 87 | Fo(i, 1, 20){ 88 | Fo(j, 1, n+1){ 89 | if (P[j][i-1] != -1) 90 | P[j][i] = P[P[j][i-1]][i-1]; 91 | } 92 | } 93 | 94 | int q; 95 | cin >> q; 96 | set city; 97 | Fo(i, 1, n+1) city.insert({lvl[i], i}); 98 | tr(it, city){ 99 | pii cur = *it; 100 | int lev = cur.F; 101 | u = cur.S; 102 | if (u == 1){ 103 | //cout<<1<<" "<<0<>x; 125 | cout<>n; 83 | fo(i, N) trie[i][0].init(), trie[1][0].init(); 84 | fo(i, n) cin>>a[i]; 85 | add(0); 86 | ll res1 = 0; 87 | ll ans = 0; 88 | ll res = 0; 89 | a[n] = 0; 90 | for(i=n-1; i>=0; i--) res1 ^= a[i]; 91 | for(i=n-1; i>=0; i--) ans = max(ans, res1^get(res1)), res1 ^= a[i], res ^= a[i], add(res); 92 | // fo(i, n) res ^= a[i], ans = max(ans, res^get(res)), del(res1), res1 ^= a[i+1]; 93 | ans = max(ans, 0LL+get(0)); 94 | 95 | cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Trie { 9 | map m_keys = {}; // what are the next avail chars in trie node 10 | int m_traversed = 0; // how many words in trie are proper prefix 11 | bool m_isLeaf = 0; // is this trie node a leaf node i.e a word ends here 12 | int m_depth = 0; // depth of trie node 13 | 14 | public: 15 | Trie() = default; 16 | Trie(int depth): m_depth(depth) {} 17 | int getDepth() { return m_depth; } 18 | bool isKeyPresent(const char &c) { return m_keys.find(c) != m_keys.end(); } 19 | bool isLeaf() { return m_isLeaf; } 20 | void setLeaf() { m_isLeaf = 1; } 21 | void add(const string &word); 22 | int matchLength(const string &prefix); // returns the length of max prefix that exists in trie 23 | vector getAllWords(); 24 | vector autoComplete(const string &prefix); 25 | bool isPresent(const string &word); 26 | void addKey(const char &c); 27 | Trie *to(const char &c); 28 | }; 29 | 30 | template 31 | void assertVectors(const vector& lhs, const vector& rhs) { 32 | // for(auto e: lhs) 33 | // cout << e << " "; 34 | // cout << endl; 35 | // for(auto e: rhs) 36 | // cout << e << " "; 37 | // cout << endl; 38 | assert(lhs.size() == rhs.size()); 39 | for (int i = 0; i < lhs.size(); i++) 40 | { 41 | assert(lhs[i] == rhs[i]); 42 | } 43 | } 44 | 45 | int main() { 46 | 47 | Trie t; 48 | 49 | vector words = {"Rachit", "Ramesh", "Ankit", "Ankita", "Rachit1"}; 50 | sort(words.begin(), words.end()); 51 | for (auto w : words) 52 | { 53 | t.add(w); 54 | } 55 | 56 | assertVectors(t.autoComplete(""), words); 57 | assertVectors(t.autoComplete("Ra"), {"Rachit", "Rachit1", "Ramesh"}); 58 | assertVectors(t.autoComplete("Rachit"), {"Rachit", "Rachit1"}); 59 | assertVectors(t.autoComplete("Rachit1"), {"Rachit1"}); 60 | assertVectors(t.autoComplete("Rachit12"), {}); 61 | 62 | assert(t.isPresent("")); 63 | assert(!t.isPresent("Racht")); 64 | assert(t.isPresent("Rachit")); 65 | assert(t.isPresent("Rachit1")); 66 | assert(!t.isPresent("Rachit12")); 67 | 68 | assert(t.matchLength("Ract") == 3); 69 | assert(t.matchLength("") == 0); 70 | 71 | return 0; 72 | } 73 | 74 | // add the given char to current Trie node 75 | void Trie::addKey(const char& c) { 76 | if(!isKeyPresent(c)) { 77 | m_keys[c] = new Trie(m_depth + 1); 78 | } 79 | m_traversed++; 80 | } 81 | 82 | Trie* Trie::to(const char& c) { 83 | if(!isKeyPresent(c)) { 84 | return NULL; 85 | } 86 | return m_keys[c]; 87 | } 88 | 89 | // add the word to trie, duplicates are ignored 90 | void Trie::add(const string &word) { 91 | Trie *cur = this; 92 | for (char c: word) 93 | { 94 | cur->addKey(c); 95 | cur = cur->to(c); 96 | } 97 | cur->setLeaf(); 98 | } 99 | 100 | // returns the length of max prefix that exists in trie 101 | int Trie::matchLength(const string &prefix) { 102 | Trie *cur = this; 103 | int match = 0; 104 | for (char c: prefix) { 105 | if (cur->isKeyPresent(c)) { 106 | match++; 107 | cur = cur->to(c); 108 | } 109 | else { 110 | return match; 111 | } 112 | } 113 | return match; 114 | } 115 | 116 | vector Trie::getAllWords() { 117 | vector ans = {}; 118 | for (auto it: m_keys) { 119 | char c = it.first; 120 | Trie *t = it.second; 121 | if (t->isLeaf()) { 122 | ans.push_back(string("") + c); 123 | } 124 | for (auto word: t->getAllWords()) { 125 | ans.push_back(c + word); 126 | } 127 | } 128 | 129 | return ans; 130 | } 131 | 132 | vector Trie::autoComplete(const string &prefix) { 133 | if (!isPresent(prefix)) { 134 | return {}; 135 | } 136 | vector ans = {}; 137 | 138 | Trie *cur = this; 139 | for (char c: prefix) { 140 | if (cur->isKeyPresent(c)) { 141 | cur = cur->to(c); 142 | } 143 | else { 144 | break; 145 | } 146 | } 147 | 148 | if (cur->isLeaf()) { 149 | ans.push_back(prefix); 150 | } 151 | 152 | for (auto restWord: cur->getAllWords()) { 153 | ans.push_back(prefix + restWord); 154 | } 155 | return ans; 156 | } 157 | 158 | bool Trie::isPresent(const string &word) { 159 | return matchLength(word) == word.size(); 160 | } 161 | -------------------------------------------------------------------------------- /Library/Utils/bits/stdc++.h: -------------------------------------------------------------------------------- 1 | // C++ includes used for precompiling -*- C++ -*- 2 | 3 | // Copyright (C) 2003-2015 Free Software Foundation, Inc. 4 | // 5 | // This file is part of the GNU ISO C++ Library. This library is free 6 | // software; you can redistribute it and/or modify it under the 7 | // terms of the GNU General Public License as published by the 8 | // Free Software Foundation; either version 3, or (at your option) 9 | // any later version. 10 | 11 | // This library is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | 16 | // Under Section 7 of GPL version 3, you are granted additional 17 | // permissions described in the GCC Runtime Library Exception, version 18 | // 3.1, as published by the Free Software Foundation. 19 | 20 | // You should have received a copy of the GNU General Public License and 21 | // a copy of the GCC Runtime Library Exception along with this program; 22 | // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see 23 | // . 24 | 25 | /** @file stdc++.h 26 | * This is an implementation file for a precompiled header. 27 | */ 28 | 29 | // 17.4.1.2 Headers 30 | 31 | // C 32 | #ifndef _GLIBCXX_NO_ASSERT 33 | #include 34 | #endif 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | 51 | #if __cplusplus >= 201103L 52 | #include 53 | #include 54 | #include 55 | // #include 56 | #include 57 | #include 58 | #include 59 | #include 60 | #include 61 | #endif 62 | 63 | // C++ 64 | #include 65 | #include 66 | #include 67 | #include 68 | #include 69 | #include 70 | #include 71 | #include 72 | #include 73 | #include 74 | #include 75 | #include 76 | #include 77 | #include 78 | #include 79 | #include 80 | #include 81 | #include 82 | #include 83 | #include 84 | #include 85 | #include 86 | #include 87 | #include 88 | #include 89 | #include 90 | #include 91 | #include 92 | #include 93 | #include 94 | #include 95 | #include 96 | 97 | #if __cplusplus >= 201103L 98 | #include 99 | #include 100 | #include 101 | #include 102 | #include 103 | #include 104 | #include 105 | #include 106 | #include 107 | #include 108 | #include 109 | #include 110 | #include 111 | #include 112 | #include 113 | #include 114 | #include 115 | #include 116 | #include 117 | #endif -------------------------------------------------------------------------------- /Library/Utils/codeforces.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Get the root directory of the Git repository 4 | GIT_ROOT=$(git rev-parse --show-toplevel) 5 | 6 | function enter() { 7 | mkdir -p $GIT_ROOT/CodeforcesContestRunner; 8 | cd $GIT_ROOT/CodeforcesContestRunner; 9 | cp $GIT_ROOT/Library/Miscellanious/template2024.cpp a.cpp 10 | cp $GIT_ROOT/Library/Miscellanious/template2024.cpp b.cpp 11 | cp $GIT_ROOT/Library/Miscellanious/template2024.cpp c.cpp 12 | cp $GIT_ROOT/Library/Miscellanious/template2024.cpp d.cpp 13 | cp $GIT_ROOT/Library/Miscellanious/template2024.cpp e.cpp 14 | echo '' > in.txt 15 | } 16 | 17 | function build() { 18 | problem=$1 19 | g++ -std=c++20 $problem.cpp -o run_$problem -isystem $GIT_ROOT/Library/Utils 20 | } 21 | 22 | function run() { 23 | problem=$1 24 | ./run_$problem 25 | } 26 | 27 | function runtxt() { 28 | problem=$1 29 | ./run_$problem < in.txt 30 | } -------------------------------------------------------------------------------- /Library/Utils/logger.h: -------------------------------------------------------------------------------- 1 | #include 2 | // #define cerr cout 3 | namespace __DEBUG_UTIL__ 4 | { 5 | using namespace std; 6 | template 7 | concept is_iterable = requires(T &&x) { begin(x); } && 8 | !is_same_v, string>; 9 | void print(const char *x) { cerr << x; } 10 | void print(char x) { cerr << "\'" << x << "\'"; } 11 | void print(bool x) { cerr << (x ? "T" : "F"); } 12 | void print(string x) { cerr << "\"" << x << "\""; } 13 | void print(vector &v) 14 | { /* Overloaded this because stl optimizes vector by using 15 | _Bit_reference instead of bool to conserve space. */ 16 | int f = 0; 17 | cerr << '{'; 18 | for (auto &&i : v) 19 | cerr << (f++ ? "," : "") << (i ? "T" : "F"); 20 | cerr << "}"; 21 | } 22 | template 23 | void print(T &&x) 24 | { 25 | if constexpr (is_iterable) 26 | if (size(x) && is_iterable) 27 | { /* Iterable inside Iterable */ 28 | int f = 0; 29 | cerr << "\n~~~~~\n"; 30 | for (auto &&i : x) 31 | { 32 | cerr << setw(2) << left << f++, print(i), cerr << "\n"; 33 | } 34 | cerr << "~~~~~\n"; 35 | } 36 | else 37 | { /* Normal Iterable */ 38 | int f = 0; 39 | cerr << "{"; 40 | for (auto &&i : x) 41 | cerr << (f++ ? "," : ""), print(i); 42 | cerr << "}"; 43 | } 44 | else if constexpr (requires { x.pop(); }) /* Stacks, Priority Queues, Queues */ 45 | { 46 | auto temp = x; 47 | int f = 0; 48 | cerr << "{"; 49 | if constexpr (requires { x.top(); }) 50 | while (!temp.empty()) 51 | cerr << (f++ ? "," : ""), print(temp.top()), temp.pop(); 52 | else 53 | while (!temp.empty()) 54 | cerr << (f++ ? "," : ""), print(temp.front()), temp.pop(); 55 | cerr << "}"; 56 | } 57 | else if constexpr (requires { x.first; x.second; }) /* Pair */ 58 | { 59 | cerr << '(', print(x.first), cerr << ',', print(x.second), cerr << ')'; 60 | } 61 | else if constexpr (requires { get<0>(x); }) /* Tuple */ 62 | { 63 | int f = 0; 64 | cerr << '(', apply([&f](auto... args) 65 | { ((cerr << (f++ ? "," : ""), print(args)), ...); }, 66 | x); 67 | cerr << ')'; 68 | } 69 | else 70 | cerr << x; 71 | } 72 | template 73 | void printer(const char *names, T &&head, V &&...tail) 74 | { 75 | int i = 0; 76 | for (size_t bracket = 0; names[i] != '\0' and (names[i] != ',' or bracket != 0); i++) 77 | if (names[i] == '(' or names[i] == '<' or names[i] == '{') 78 | bracket++; 79 | else if (names[i] == ')' or names[i] == '>' or names[i] == '}') 80 | bracket--; 81 | cerr.write(names, i) << " = "; 82 | print(head); 83 | if constexpr (sizeof...(tail)) 84 | cerr << " ||", printer(names + i + 1, tail...); 85 | else 86 | cerr << "]\n"; 87 | } 88 | template 89 | void printerArr(const char *names, T arr[], size_t N, V... tail) 90 | { 91 | size_t i = 0; 92 | for (; names[i] and names[i] != ','; i++) 93 | cerr << names[i]; 94 | for (i++; names[i] and names[i] != ','; i++) 95 | ; 96 | cerr << " = {"; 97 | for (size_t ind = 0; ind < N; ind++) 98 | cerr << (ind ? "," : ""), print(arr[ind]); 99 | cerr << "}"; 100 | if constexpr (sizeof...(tail)) 101 | cerr << " ||", printerArr(names + i + 1, tail...); 102 | else 103 | cerr << "]\n"; 104 | } 105 | 106 | } 107 | #define deb(...) std::cerr << __LINE__ << ": [", __DEBUG_UTIL__::printer(#__VA_ARGS__, __VA_ARGS__) 108 | #define debArr(...) std::cerr << __LINE__ << ": [", __DEBUG_UTIL__::printerArr(#__VA_ARGS__, __VA_ARGS__) -------------------------------------------------------------------------------- /MyOnlineSubmissions/Codechef/DEC17/CHEFEXQ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // #include "stdafx.h" 3 | // #pragma warning(disable : 4996) //_CRT_SECURE_NO_WARNINGS 4 | using namespace std; 5 | #define gc getchar_unlocked 6 | #define fo(i,n) for(i=0;in;k=0) compute(b); 72 | b++, _i = 0; 73 | } 74 | 75 | bkt[i] = b; 76 | local[i] = _i; 77 | en[b] = _i; 78 | mat[b][_i] = a[i]; 79 | _i++; 80 | } 81 | compute(b); 82 | 83 | while(q--){ 84 | si(type); 85 | si(i); 86 | si(x); 87 | i--; 88 | if(type == 1){ 89 | //update a[i] = x; 90 | b = bkt[i]; 91 | _i = local[i]; 92 | mat[b][_i] = x; 93 | compute(b); 94 | } 95 | else{ 96 | //query prefixes with xor = x, and end before i 97 | int b = bkt[i]; 98 | int ans = 0, ptr = 0, pre = 0; 99 | while(bkt[ptr] < b){ 100 | int cur_bkt = bkt[ptr]; 101 | int need = x ^ pre; 102 | ans += cnt[cur_bkt][need]; 103 | pre ^= dp[cur_bkt][en[cur_bkt]]; 104 | ptr += rtn; 105 | } 106 | Fo(j, 0, local[i]+1){ 107 | pre ^= mat[b][j]; 108 | if(pre == x) ans++; 109 | } 110 | printf("%d\n", ans); 111 | } 112 | } 113 | 114 | return 0; 115 | } 116 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/Codechef/MAY20/CHANDF.cpp: -------------------------------------------------------------------------------- 1 | // Video Explanation at https://www.youtube.com/watch?v=-F7cHQ-gWS4 2 | #include 3 | using namespace std; 4 | 5 | #define ll long long 6 | 7 | ll f(ll &x, ll &y, ll &z) { 8 | return (x&z) * (y&z); 9 | } 10 | 11 | class Bit{ 12 | ll x; 13 | int _bits; // we need only these many bits, in this case 40 14 | 15 | #define mask(b) (1LL<<(_bits-b)) // remember 0th bit is actually 39th bit 16 | public: 17 | Bit() {} 18 | 19 | Bit(ll &y, int bits=40) { 20 | init(y, bits); 21 | } 22 | 23 | void init(ll &y, int bits=40) { 24 | x = y; 25 | _bits = bits-1; 26 | } 27 | 28 | bool get(int &b) { 29 | return (x & mask(b)) != 0; 30 | } 31 | 32 | void set(int &b) { 33 | x |= mask(b); 34 | } 35 | 36 | void reset(int &b) { 37 | if(get(b)) 38 | x ^= mask(b); 39 | } 40 | 41 | void set(int &b,int k) { 42 | if(k == 1) { 43 | set(b); 44 | } 45 | else { 46 | reset(b); 47 | } 48 | } 49 | 50 | ll toInt() { 51 | return x; 52 | } 53 | } bitX, bitY; 54 | 55 | vector getValidZValues(ll &L, ll &R) { 56 | vector Zcandidates = {L, R}; // L and R are always valid Z values we should handle 57 | Bit bitL(L); 58 | Bit bitR(R); 59 | int k = 0; 60 | while(k<40 and bitL.get(k) == bitR.get(k)) k++; 61 | 62 | for(int l = k+1; l < 40; l++) { 63 | if(bitL.get(l) != 0) continue; 64 | Bit z(L); 65 | z.set(l); 66 | for(int i=l+1; i<40; i++) { 67 | if(bitX.get(i) == 0 and bitY.get(i) == 0) { 68 | z.set(i, 0); // minimize Z 69 | } 70 | else { 71 | z.set(i, 1); // maximize F(X,Y,Z) 72 | } 73 | } 74 | Zcandidates.push_back(z.toInt()); 75 | } 76 | for(int r = k+1; r < 40; r++) { 77 | if(bitR.get(r) != 1) continue; 78 | Bit z(R); 79 | z.reset(r); 80 | for(int i=r+1; i<40; i++) { 81 | if(bitX.get(i) == 0 and bitY.get(i) == 0) { 82 | z.set(i, 0); 83 | } 84 | else { 85 | z.set(i, 1); 86 | } 87 | } 88 | Zcandidates.push_back(z.toInt()); 89 | } 90 | 91 | sort(Zcandidates.begin(), Zcandidates.end()); 92 | return Zcandidates; 93 | } 94 | 95 | int main() { 96 | ios_base::sync_with_stdio(0); 97 | int t; 98 | cin >> t; 99 | 100 | while(t--) { 101 | ll x, y, l, r; 102 | cin >> x >> y >> l >> r; 103 | 104 | bitX.init(x); 105 | bitY.init(y); 106 | 107 | vector Zcandidates = getValidZValues(l, r); 108 | 109 | ll mx = -1, ans = r; 110 | for(ll z: Zcandidates) { 111 | ll currentF = f(x, y, z); 112 | if(currentF > mx) { 113 | mx = currentF; 114 | ans = z; 115 | } 116 | } 117 | 118 | cout << ans << endl; 119 | } 120 | 121 | return 0; 122 | } 123 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/Codechef/NOV17/CSUBQ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // #include "stdafx.h" 3 | // #pragma warning(disable : 4996) //_CRT_SECURE_NO_WARNINGS 4 | using namespace std; 5 | #define gc getchar_unlocked 6 | #define fo(i,n) for(i=0;in;k> s; 16 | 17 | int n = s.size(); 18 | 19 | vector other(n, 0); 20 | 21 | for(int j = 0; j < n; j++) { 22 | if(s[j] == '4') s[j] = '3', other[j] = 1; 23 | } 24 | 25 | cout << s << " " ; 26 | 27 | 28 | int j; 29 | for(j = 0; other[j] == 0 and j < n; j++); 30 | for(; j < n; j++) cout << other[j]; 31 | cout << endl; 32 | 33 | 34 | } 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/Google-CodeJam/2019/QualificationRound/Problem B.cpp: -------------------------------------------------------------------------------- 1 | //Problem Link: https://codingcompetitions.withgoogle.com/codejam/round/0000000000051705/00000000000881da 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int t,n; 7 | cin >> t; 8 | for(int ii = 0; ii < t; ii++){ 9 | cout << "Case #" << 1+ii << ": "; 10 | string s; 11 | cin >> n; 12 | cin >> s; 13 | for(char c: s) { 14 | char p = 'S'; 15 | if (c == p) 16 | p = 'E'; 17 | cout << p; 18 | } 19 | cout << endl; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/Google-CodeJam/2019/Round1C/Problem A[Robot Programming Strategy].cpp: -------------------------------------------------------------------------------- 1 | //Problem Link: https://codingcompetitions.withgoogle.com/codejam/round/00000000000516b9/0000000000134c90 2 | #include 3 | using namespace std; 4 | const char R = 'R'; 5 | const char P = 'P'; 6 | const char S = 'S'; 7 | map win, l; 8 | 9 | char M[300][603]; 10 | int len[300], ign[300]; 11 | char winner(set a) 12 | { 13 | char x = *a.begin(); 14 | char y = *a.rbegin(); 15 | string z = ""; z += x; z += y; 16 | if (z == "PR") return R; 17 | if (z == "PS") return P; 18 | if (z == "RS") return S; 19 | } 20 | 21 | int main() { 22 | win[R]=P; 23 | win[P]=S; 24 | win[S]=R; 25 | 26 | l[R]=S; 27 | l[P]=R; 28 | l[S]=P; 29 | ios_base::sync_with_stdio(0); 30 | int t, i, j, nj, n; 31 | string s; 32 | cin >> t; 33 | int T = t; 34 | while(t--) { 35 | for(i=0; i < 300; i++) len[i] = ign[i] = 0; 36 | cout << "Case #" << T-t << ": "; 37 | cin >> n; 38 | int mxl = 0; 39 | for(i = 0; i < n; i++) { 40 | cin >> s; 41 | len[i] = s.length(); len[i] = min(len[i], 500); 42 | mxl = max(mxl, len[i]); mxl = min(mxl, 500); 43 | 44 | for(j = 0; j < 500; j++) { 45 | nj = j%len[i]; 46 | M[i][j] = s[nj]; 47 | } 48 | } 49 | 50 | int flag = 0;int count = 0; 51 | string ans = ""; 52 | for( j = 0; j < 500; j++) { 53 | set choices = {R, P, S}; 54 | set want = {}; 55 | for( i = 0; i < n; i++) { 56 | if(ign[i]) continue; 57 | char c = M[i][j]; 58 | choices.erase(l[c]); 59 | want.insert(win[c]); 60 | } 61 | if(choices.empty() or want.size() == 3) { 62 | flag = -1; //IMPOSSIBLE 63 | break; 64 | } 65 | if(want.size() == 0) { 66 | flag = 1; // WE WON 67 | break; 68 | } 69 | if(want.size() == 1) { 70 | flag = 1; // WE WON 71 | ans += *want.begin(); 72 | break; 73 | } 74 | //want 2 75 | char chala = winner(want); 76 | ans += chala; 77 | for( i = 0; i < n; i++) { 78 | if(l[chala] == M[i][j]) ign[i] = 1; 79 | } 80 | } 81 | 82 | for(i = 0; i < n; i++) if(ign[i] == 1) count++; 83 | if(count == n) flag = 1; 84 | if(flag == -1) cout << "IMPOSSIBLE\n"; 85 | else cout << ans << "\n"; 86 | } 87 | 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/Google-CodeJam/2019/Round1C/Problem B[Power Arrangers].cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int i, j, tt, n, f, F; 6 | char p; 7 | cin >> tt >> F; 8 | while(tt--) { 9 | map cnt; 10 | map pos; 11 | cnt.clear(); 12 | pos.clear(); 13 | 14 | f = F; 15 | //1 to 595 abcde,badce, 16 | //ask first three chars of 119 nos //357 17 | vector my(119, ""); 18 | for(i=0; i<119; i++){ 19 | my[i] = ""; 20 | int x = (i*5)+1; 21 | cout << x << "\n" << flush; 22 | cin >> p; 23 | my[i] += p; 24 | 25 | cout << x+1 << "\n" << flush; 26 | cin >> p; 27 | my[i] += p; 28 | 29 | cout << x+2 << "\n" << flush; 30 | cin >> p; 31 | my[i] += p; 32 | 33 | cnt[my[i]]++; 34 | pos[my[i]] = i; 35 | } 36 | int cx = 0; 37 | for(i=0; i<119; i++) if(cnt[my[i]] == 1) cx = i; 38 | 39 | int ign = 0; 40 | if(cx == ign) ign = 1; 41 | 42 | string ans = my[cx]; 43 | i = cx; 44 | int x = (i*5)+4; 45 | cout << x << "\n" << flush; 46 | cin >> p; 47 | my[i] += p; 48 | 49 | set xx = {'A', 'B', 'C', 'D', 'E'}; 50 | for(char cc: my[cx]) xx.erase(cc); 51 | char fin = *xx.begin(); 52 | ans = ans + fin + p; 53 | cout << ans << "\n" << flush; 54 | cin >> p; 55 | if(p != 'Y') exit(0); 56 | 57 | } 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/A-Vestigium.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;in;k 0) { 86 | if (exp & 1) result = ((ll)result * base) % mod; 87 | base = ((ll)base * base) % mod; 88 | exp >>= 1; 89 | } 90 | return result; 91 | } 92 | 93 | void ipgraph(int n, int m){ 94 | int i, u, v; 95 | while(m--){ 96 | cin>>u>>v; 97 | g[u-1].pb(v-1); 98 | g[v-1].pb(u-1); 99 | } 100 | } 101 | 102 | void dfs(int u, int par){ 103 | for(int v:g[u]){ 104 | if (v == par) continue; 105 | dfs(v, u); 106 | } 107 | } 108 | 109 | 110 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/B-NestingDepth.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;in;k 0) { 68 | if (exp & 1) result = ((ll)result * base) % mod; 69 | base = ((ll)base * base) % mod; 70 | exp >>= 1; 71 | } 72 | return result; 73 | } 74 | 75 | void ipgraph(int n, int m){ 76 | int i, u, v; 77 | while(m--){ 78 | cin>>u>>v; 79 | g[u-1].pb(v-1); 80 | g[v-1].pb(u-1); 81 | } 82 | } 83 | 84 | void dfs(int u, int par){ 85 | for(int v:g[u]){ 86 | if (v == par) continue; 87 | dfs(v, u); 88 | } 89 | } 90 | 91 | 92 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/C-ParentingActivities.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;in;k 0) { 94 | if (exp & 1) result = ((ll)result * base) % mod; 95 | base = ((ll)base * base) % mod; 96 | exp >>= 1; 97 | } 98 | return result; 99 | } 100 | 101 | void ipgraph(int n, int m){ 102 | int i, u, v; 103 | while(m--){ 104 | cin>>u>>v; 105 | g[u-1].pb(v-1); 106 | g[v-1].pb(u-1); 107 | } 108 | } 109 | 110 | void dfs(int u, int par){ 111 | for(int v:g[u]){ 112 | if (v == par) continue; 113 | dfs(v, u); 114 | } 115 | } 116 | 117 | 118 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/Google-CodeJam/2020/QualificationRound/D-interactive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define gc getchar_unlocked 4 | #define fo(i,n) for(i=0;in;k> verdict; 92 | assert(verdict == 'Y'); 93 | } 94 | 95 | return 0; 96 | } 97 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/ProjectEuler/63.py: -------------------------------------------------------------------------------- 1 | # The 5-digit number, 16807=7^5, is also a fifth power. 2 | # Similarly, the 9-digit number, 134217728=8^9, is a ninth power. 3 | # How many n-digit positive integers exist which are also an nth power? 4 | 5 | def digits(x): 6 | ans = 0 7 | while x > 0: 8 | x //= 10 9 | ans += 1 10 | return ans 11 | 12 | ans = 1 # 1^1 = 1 13 | for k in range(2, 11): 14 | for p in range(1, 22): 15 | # check if k^p has p digits 16 | if digits(pow(k, p)) == p: 17 | ans += 1 18 | print(f'{k}^{p} = {pow(k, p)} has {p} digits.') 19 | print(ans) 20 | -------------------------------------------------------------------------------- /MyOnlineSubmissions/ProjectEuler/70.py: -------------------------------------------------------------------------------- 1 | # Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation of 79180. 2 | # 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. 3 | N = 10**7 4 | rat = N + 1 5 | ans = -1 6 | 7 | def same(x, y): 8 | return sorted(str(x)) == sorted(str(y)) 9 | 10 | def euler_phi(MAX=N+1): 11 | phi = [0 for _ in range(MAX+1)] 12 | phi[1] = 1 13 | for i in range(2, MAX+1): 14 | if not phi[i]: 15 | phi[i] = i-1 16 | for j in range((i<<1), MAX+1, i): 17 | if not phi[j]: 18 | phi[j] = j 19 | phi[j] = (phi[j]//i) * (i-1) 20 | return phi 21 | 22 | phi = euler_phi() 23 | 24 | for n in range(2, N + 1): 25 | p = phi[n] 26 | if same(p, n): 27 | print(n, p) 28 | if rat > n/p: 29 | rat = n/p 30 | ans = n 31 | 32 | print(ans) 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # My YouTube Channel 2 | I make Video Lectures on YouTube for 3 | 1. Data Structures 4 | 2. Algorithms 5 | 3. Interview Tips for Software Engineering Jobs 6 | 4. Math Puzzles 7 | 5. Brain Teasers 8 | 6. Logical Reasoning 9 | 10 | Youtube Channel ► http://www.youtube.com/c/RachitJain 11 | Facebook Page ► http://fb.me/AlgorithmsWithRachitJain 12 | Blog ► http://rachitiitr.blogspot.com 13 | 14 | # My Profile Links 15 | CodeForces ► http://www.codeforces.com/profile/rachitjain 16 | CodeChef ► http://www.codechef.com/users/rachitiitr 17 | 18 | # About Me 19 | I am Rachit Jain, currently working as Software Engineer in Microsoft. 20 | I have graduated from IIT Roorkee in 2017. 21 | I have done my majors in Electrical Engineering, 22 | and minors in Computer Science Engineering. 23 | Competitive Programming is my hobby, as I like to keep my mind sharp. 24 | I love to explore and learn new algorithms and programming techniques. 25 | I like teaching, and hence launched my YouTube channel recently. 26 | 27 | # Achievements 28 | 1. JEE Mains All India Rank: #69 among 1.4 million candidates 29 | 2. IITian 30 | 3. Despite majors in Electrical Engineering: 31 | a. Cracked job interviews for Microsoft, Directi. 32 | b. Google APAC Global Rank: #25 (Round D, 2017) 33 | c. Codeforces Rating: 2018 (DIV 1) 34 | d. Did internships in Flipkart(III Year) and Grofers(II Year). 35 | e. Launched YouTube Channel for DS, Algos for teaching. 36 | -------------------------------------------------------------------------------- /Tricks/CacheStoreWithTTL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int getCurrentTimeStamp(){ 5 | return 0; //assume this is a system function that returns the current timestamp 6 | } 7 | 8 | //Implement a CacheStore that can store key values with some TTL info as well 9 | template 10 | class CacheStore 11 | { 12 | //mapping key to value as well as a timestamp till its valid 13 | unordered_map> _mep; 14 | public: 15 | void Add(K key, V value, int ttl) { 16 | if(_mep.find(key) == _mep.end()) { 17 | int expirationTime = getCurrentTimeStamp() + ttl; 18 | _mep[key] = {value, expirationTime}; 19 | } 20 | else { 21 | //depends on business logic how to handle this case 22 | //one approach is we can overwrite the value 23 | } 24 | } 25 | 26 | //returns true if key existed and also alive 27 | bool Get(K key, V* out) { 28 | int currentTime = getCurrentTimeStamp(); 29 | if(_mep.find(key) == _mep.end()) { 30 | out = NULL; 31 | return 0; 32 | } 33 | else { 34 | pair cur = _mep[key]; 35 | if (cur.second < currentTime) { 36 | //expired 37 | out = NULL; 38 | return 0; 39 | } 40 | else { 41 | *out = cur.first; 42 | return 1; 43 | } 44 | } 45 | } 46 | }; 47 | 48 | int main() { 49 | CacheStore M; 50 | M.Add("rachit", 1, 10); 51 | M.Add("Uber", 2, 100); 52 | int* res = new int; 53 | if(M.Get("rachit", res)) cout << *res << endl; 54 | if(M.Get("Uber", res)) cout << *res << endl; 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Tricks/iterative-tree-traversal-1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node{ 5 | int val; 6 | node *left, *right; 7 | node(int x) { 8 | val = x; 9 | left = right = NULL; 10 | } 11 | }; 12 | 13 | unordered_map cnt; 14 | 15 | void traversal_trick(node *root) { 16 | //inorder 17 | stack S; 18 | 19 | S.push(root); 20 | while(!S.empty()){ 21 | node* cur = S.top(); 22 | if(cur == NULL) { S.pop(); continue; } 23 | if (cnt[cur] == 0) S.push(cur->left); 24 | else if (cnt[cur] == 1) cout << cur->val << " " ; 25 | else if (cnt[cur] == 2) S.push(cur->right); 26 | else S.pop(); 27 | cnt[cur]++; 28 | } 29 | } 30 | 31 | int main() 32 | { 33 | node *root = new node(7); 34 | node *t = root; 35 | root->left = new node(3); root->right = new node(10); 36 | root->left->left = new node(2); root->left->right = new node(5); 37 | root->left->left->left = new node(1); 38 | root->right->left = new node(8); 39 | root->right->right = new node(12); 40 | 41 | traversal_trick(root); 42 | } 43 | -------------------------------------------------------------------------------- /Tricks/iterative-tree-traversal-2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node{ 5 | int val; 6 | node *left, *right; 7 | node(int x) { 8 | val = x; 9 | left = right = NULL; 10 | } 11 | }; 12 | 13 | void traversal_trick(node *root) { 14 | //inorder 15 | stack> S; 16 | 17 | S.push({root, 0}); 18 | while(!S.empty()){ 19 | pair t = S.top(); 20 | node* cur = t.first; 21 | int state = t.second; 22 | 23 | S.pop(); 24 | 25 | if(cur == NULL or state == 3) continue; 26 | 27 | S.push({cur, state+1}); 28 | 29 | if (state == 0) S.push({cur->left, 0}); 30 | else if (state == 1) cout << cur->val << " " ; 31 | else if (state == 2) S.push({cur->right, 0}); 32 | } 33 | } 34 | 35 | int main() 36 | { 37 | node *root = new node(7); 38 | node *t = root; 39 | root->left = new node(3); root->right = new node(10); 40 | root->left->left = new node(2); root->left->right = new node(5); 41 | root->left->left->left = new node(1); 42 | root->right->left = new node(8); 43 | root->right->right = new node(12); 44 | 45 | traversal_trick(root); 46 | } 47 | -------------------------------------------------------------------------------- /Tricks/tricky-oops-problem.cpp: -------------------------------------------------------------------------------- 1 | //g++ 5.4.0 2 | //Are private functions really private? Well... 3 | //Checkout video at: https://youtu.be/TVKsaq7Bohs 4 | #include 5 | 6 | using namespace std; 7 | 8 | class SocialWebsite{ 9 | private: 10 | protected: 11 | public: 12 | virtual void secret() {} ; 13 | }; 14 | 15 | class Facebook: public SocialWebsite{ 16 | private: 17 | string fbPassword; 18 | 19 | void secret(){ 20 | cout << "The Facebook password is: " << fbPassword << endl; 21 | cout << "Its risky, but its fine to print here as it's a private function\n"; 22 | } 23 | public: 24 | Facebook(string pwd) { 25 | fbPassword = pwd; 26 | } 27 | }; 28 | 29 | int main() 30 | { 31 | Facebook f("Rachit95@fb"); 32 | 33 | SocialWebsite *ptr = &f; 34 | ptr->secret(); 35 | } 36 | --------------------------------------------------------------------------------