├── Dynamic_Programming ├── Atcoder_Educational_DP_contest │ ├── A_Frog1.cpp │ ├── B_Frog2.cpp │ ├── C_Vacation.cpp │ ├── D_Knapsack1.cpp │ ├── E_knapsack_2 │ ├── E_knapsack_2.cpp │ ├── F_LCS │ ├── F_LCS.cpp │ ├── G_longest_path │ ├── G_longest_path.cpp │ ├── H_Grid │ ├── H_Grid.cpp │ ├── I_coins │ ├── I_coins.cpp │ ├── J_sushi │ ├── J_sushi.cpp │ ├── K_stones │ ├── K_stones.cpp │ ├── L_deque │ ├── L_deque.cpp │ ├── M_candies │ ├── M_candies.cpp │ ├── N_slimes │ ├── N_slimes.cpp │ ├── O_matching.cpp │ └── P_Independent set.cpp ├── Cell_mitosis_Hackerblocks.cpp ├── CoinChange.cpp ├── Count_number_of_subarray_which_are_non_decreasing.cpp ├── Friend_Pairing_Problem.cpp ├── Ladders.cpp ├── LongestCommonSubsquence.cpp ├── LongestIncreasingSubsequence.cpp ├── Longest_Path_Atcoder_DP_Problems.cpp ├── MatrixChainMultiplication.cpp ├── Maximum_Sum_With_No_Two_Consecutive.cpp ├── Minimum_Cost_Path_Grid_Dp.cpp ├── MixturesSpoj.cpp ├── Nth_Catalan_Number.cpp ├── Optimal_Game_Strategy.cpp ├── Robot_Path_Codechef.cpp ├── Rod_Cutting_to_maximize_profit.cpp ├── Travellinf_Salesman_Problem_Graph_2_d_DP_with_Bitmasking.cpp ├── WinesProblem.cpp ├── a.out ├── fibonacci.cpp ├── longest_sum_subsequence.cpp ├── max_subarray_sum.cpp ├── minimum_steps_to_one.cpp ├── tiling_problem └── tiling_problem.cpp ├── Fenwicktree.cpp ├── Graph ├── Articulation_point_and_bridges.cpp ├── Bellmond_Ford_Algorithm.cpp ├── Bipartite_Check.cpp ├── Breadth_First_Search_BFS.cpp ├── Check_if_a_Undirected_Graph_is_a_Tree_or_Not_Using_BFS.cpp ├── Colorful_Array_Spoj.cpp ├── Connected_Component_Using_DFS_Graph.cpp ├── Cycle_Detection_in_Directed_Graph_using_DFS.cpp ├── Cycle_Detection_in_Undirected_Graph_Using_DSU.cpp ├── Cycle_Detection_in_Undirected_Graph_using_DFS.cpp ├── DP_on_Graph ├── DP_on_Graph.cpp ├── DP_on_tree__Smallest_node_in_a_subtree_of_x.cpp ├── Depth_First_Search_DFS.cpp ├── Dijkstras_Algorithm_Shortest_Path_on_Weighted_Graph.cpp ├── Disjoint_Set_DS_and_Union_Find_Algorithm.cpp ├── Euler_tour.cpp ├── Floyd_Warshall_Algorithm.cpp ├── Graph_Adjacency_List_Implementation_for_Generic_Data.cpp ├── Graph_Adjacency_list_Implementation.cpp ├── Holiday_Accomodation_ACM_ICPC_Regional_Contest.cpp ├── Kosaraju_Algorithm_Strongly_Connected_Components.cpp ├── Kruskals_Algorithm_for_minimum_spanning tree.cpp ├── LCA │ ├── Brute │ ├── distance_between_x_and_y │ ├── distance_between_x_and_y.cpp │ ├── lca_brute.cpp │ ├── lca_sparse_table │ ├── lca_sparse_table.cpp │ ├── lca_using_time │ └── lca_using_time.cpp ├── Network_flow │ ├── Edmund_karp_algorithm_to_find_the_max_flow_in_graph │ └── Edmund_karp_algorithm_to_find_the_max_flow_in_graph.cpp ├── Prims_Algorithm_for_finding_minimum_spanning_tree.cpp ├── Shortest_Cycle_in_undirected_graph.cpp ├── Single_Source_Shortest_Path_SSSP.cpp ├── Snakes_and_Ladder_BFS_SSSP_Problem.cpp ├── Sparse_Table │ ├── Range_min_queries.cpp │ └── Range_sum_queries.cpp ├── Splitwise_Algorithm_with_transaction_details.cpp ├── Topological_Sorting_for_Directed_Acyclic_Graph_DAG_using_BFS_Approach.cpp ├── Topological_Sorting_for_Directed_Acyclic_Graph_DAG_using_DFS_Approach.cpp ├── a.out └── apple.txt ├── Heaps ├── Build_Heap_from_Array.cpp ├── Heap_Priority_Queue.cpp ├── Heap_Sort.cpp ├── Join_the_ropes.cpp ├── Merge_K_Sorted_Array.cpp ├── Running_Median_of_a_stream_of_Integers.cpp ├── a.out └── kth_smallest_element_in_row_and_column_wise_sorted_matrix.cpp ├── Linked_List ├── CircularLinkedList.cpp ├── Floyd_Cycle_Algorithm.cpp ├── Kth_element_from_the_end_of_the_Linked_List.cpp ├── Linked_List.cpp ├── MergeSort.cpp ├── Merge_two_sorted_linked_list_into_one.cpp ├── Mid_Point_Runner_Technique.cpp └── Reverse_a_Linked_list.cpp ├── Queue ├── First_non_repeating_character_in_a_stream_of_characters.cpp ├── Implementation_of_Queue_using_Array.cpp ├── Implementation_of_Queue_using_two_stack.cpp ├── Implementation_of_stack_using_two_Queue.cpp └── LinkedList_Implementation_of_Queue.cpp ├── README.md ├── Stack ├── Max_Histogram_Area.cpp ├── StockSpan.cpp ├── Valid_Parenthesis.cpp └── nextGreaterElement.cpp ├── String_Matching_ALgorithm ├── KMP_Knuth_Morris_Pratt.cpp ├── Longest_Substring_with_distinct_character.cpp ├── Naive_Algorithm_Code.cpp ├── Rabin_Karp_Algorithm.cpp └── a.out ├── Top Interview Questions : Leetcode Link ├── Binary Tree and BST.pdf ├── Divide and Conquer.pdf ├── Top 50 Interview Question.pdf ├── Top Amazon Question.pdf ├── Top Facebook Question.pdf ├── Top Google Question.pdf └── Top Linkedin Question.pdf ├── Tree ├── Binary_Search_Tree.cpp ├── Binary_Tree.cpp ├── Maximum_Path_sum_between_two_leaf_nodes.cpp ├── Minimum_distance_between_two_node_of_a_binary_tree.cpp ├── a.out └── lca.cpp └── Trie ├── Longest_Common_Prefix.cpp ├── Maximum_Xor_Pair.cpp ├── Trie_Basics.cpp ├── Trie_Data_Structure.cpp ├── Unique_Prefix_Array.cpp └── a.out /Dynamic_Programming/Atcoder_Educational_DP_contest/A_Frog1.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_a 2 | 3 | //dp[i] : represents the minimum cost to reach stone number i from stone number 0. 4 | //Goal : to find dp[n] 5 | //dp[n] = min(|h(n)-h(n-1)| + dp[n-1] , |h(n)-h(n-2)| + dp[n-2]) 6 | 7 | #include 8 | using namespace std; 9 | 10 | //Bottom Up Approach 11 | int frog1(vectorh, int n) { 12 | vectordp(n + 1); 13 | dp[1] = 0; 14 | dp[2] = abs(h[2] - h[1]); 15 | for (int i = 3; i <= n; i++) { 16 | int option1 = abs(h[i] - h[i - 1]) + dp[i - 1]; 17 | int option2 = abs(h[i] - h[i - 2]) + dp[i - 2]; 18 | dp[i] = min(option1, option2); 19 | } 20 | return dp[n]; 21 | } 22 | 23 | int main() { 24 | ios_base::sync_with_stdio(false); 25 | cin.tie(NULL); 26 | cout.tie(NULL); 27 | int n; 28 | cin >> n; 29 | vectorh(n + 1); 30 | for (int i = 1; i <= n; i++) 31 | cin >> h[i]; 32 | cout << frog1(h, n) << endl; 33 | 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/B_Frog2.cpp: -------------------------------------------------------------------------------- 1 | https://atcoder.jp/contests/dp/tasks/dp_b 2 | 3 | dp[i] : Minimum Cost to reach stone i. 4 | Goal : to find dp[n]. 5 | dp[i] : min(|h(i)-h(j)| + dp[j]) over all valid values of j. j can be from i, i-1, i-2.....i-k. 6 | Base Case : dp[1] is zero as frog didnt need to jump to reach 1. 7 | 8 | #include 9 | using namespace std; 10 | 11 | //Bottom Up Approach 12 | int frog2(vectorh, int n, int k) { 13 | vectordp(n + 1); 14 | dp[1] = 0; 15 | for (int i = 2; i <= n; i++) { 16 | dp[i] = INT_MAX; 17 | // Condition (i-j<=k) ----> We can only jump from stone which is atmost k distance from the stone. 18 | for (int j = i - 1; j >= 1 && (i - j) <= k; j--) 19 | dp[i] = min(dp[i], abs(h[i] - h[j]) + dp[j]); 20 | } 21 | return dp[n]; 22 | } 23 | 24 | int main() { 25 | ios_base::sync_with_stdio(false); 26 | cin.tie(NULL); 27 | cout.tie(NULL); 28 | int n, k; 29 | cin >> n >> k; 30 | vectorh(n + 1); 31 | for (int i = 1; i <= n; i++) 32 | cin >> h[i]; 33 | cout << frog2(h, n, k) << endl; 34 | 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/C_Vacation.cpp: -------------------------------------------------------------------------------- 1 | // C : Vacation : Atcoder DP contest Problem 2 | 3 | // https://atcoder.jp/contests/dp/tasks/dp_c 4 | 5 | #include 6 | using namespace std; 7 | int mod = 1e9+7; 8 | 9 | 10 | class activity{ 11 | public: 12 | int A; 13 | int B; 14 | int C; 15 | }; 16 | 17 | //Bottom Up DP Approach 18 | //dp[n][0] : maximum possible happiness from 1...N ,if the boy does the activity A on day N. 19 | //dp[n][1] : maximum possible happiness from 1...N ,if the boy does the activity B on day N. 20 | //dp[n][2] : maximum possible happiness from 1...N ,if the boy does the activity C on day N. 21 | int vacation(vectorv,int n){ 22 | 23 | int dp[n+1][3]; 24 | dp[1][0]=v[1].A; 25 | dp[1][1]=v[1].B; 26 | dp[1][2]=v[1].C; 27 | 28 | for(int i=2;i<=n;i++){ 29 | dp[i][0]=(v[i].A + max(dp[i-1][1],dp[i-1][2]))%mod; 30 | dp[i][1]=(v[i].B + max(dp[i-1][0],dp[i-1][2]))%mod; 31 | dp[i][2]=(v[i].C + max(dp[i-1][0],dp[i-1][1]))%mod; 32 | } 33 | 34 | int ans = max(dp[n][0],max(dp[n][1],dp[n][2])); 35 | return ans % mod; 36 | } 37 | 38 | 39 | 40 | int main(){ 41 | 42 | int n; 43 | cin>>n; 44 | vectorv(n+1); 45 | for(int i=1;i<=n;i++){ 46 | cin>>v[i].A; 47 | cin>>v[i].B; 48 | cin>>v[i].C; 49 | } 50 | 51 | cout< 22 | using namespace std; 23 | #define ll long long int 24 | #define endl "\n" 25 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 26 | #define mod 1000000007 27 | #define gcd __gcd 28 | #define inf INT_MAX 29 | #define INF LLONG_MAX 30 | #define minf INT_MIN 31 | #define MINF LLONG_MIN 32 | #define pb push_back 33 | #define all(v) v.begin(),v.end() 34 | #define print(v) for(auto x:v) cout<wt, val; 42 | 43 | //Top Down DP 44 | ll knapsack_TD(int n, int w) { 45 | if (n == 0 || w == 0) return 0; 46 | 47 | if (dp[n][w] != -1) return dp[n][w]; 48 | 49 | if (wt[n] > w) return dp[n][w] = knapsack_TD(n - 1, w); 50 | else return dp[n][w] = max(val[n] + knapsack_TD(n - 1, w - wt[n]), knapsack_TD(n - 1, w)); 51 | } 52 | 53 | //Bottom up DP 54 | ll knapsack_BU(int n, int w) { 55 | for (int i = 1; i <= n; i++) { 56 | for (int j = 1; j <= w; j++) { 57 | if (wt[i] > j) dp[i][j] = dp[i - 1][j]; 58 | else dp[i][j] = max(val[i] + dp[i - 1][j - wt[i]], dp[i - 1][j]); 59 | } 60 | } 61 | return dp[n][w]; 62 | } 63 | 64 | int32_t main() { 65 | fastio; 66 | int n, w; 67 | cin >> n >> w; 68 | // memset(dp, -1, sizeof dp); 69 | wt.resize(n + 1, 0); 70 | val.resize(n + 1, 0); 71 | for (int i = 1; i < 72 | = n; i++) cin >> wt[i] >> val[i]; 73 | cout << knapsack_BU(n, w) << endl; 74 | } 75 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/E_knapsack_2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Dynamic_Programming/Atcoder_Educational_DP_contest/E_knapsack_2 -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/E_knapsack_2.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_e 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | // #define inf INT_MAX 11 | #define inf 1e9+1 12 | #define INF LLONG_MAX 13 | #define minf INT_MIN 14 | #define MINF LLONG_MIN 15 | #define pb push_back 16 | #define all(v) v.begin(),v.end() 17 | #define print(v) for(auto x:v) cout<wt; 25 | vectorval; 26 | int n, capacity; 27 | 28 | //dp[i][j] : minimum weight W, we have to carry to get the value j 29 | int knapsack_2(int max_profit) { 30 | for (int j = 0; j <= max_profit; j++) dp[0][j] = inf; 31 | for (int i = 0; i <= n; i++) dp[i][0] = 0; 32 | for (int i = 1; i <= n; i++) { 33 | for (int j = 0; j <= max_profit; j++) { 34 | if (val[i] <= j) dp[i][j] = min(wt[i] + dp[i - 1][j - val[i]], dp[i - 1][j]); 35 | else dp[i][j] = dp[i - 1][j]; 36 | } 37 | } 38 | int ans = 0; 39 | for (int j = 0; j <= max_profit; j++) 40 | if (dp[n][j] <= capacity) ans = j; 41 | return ans; 42 | } 43 | 44 | int32_t main() { 45 | fastio; 46 | cin >> n >> capacity; 47 | wt.resize(n + 1, 0); 48 | val.resize(n + 1, 0); 49 | int max_profit{}; 50 | for (int i = 1; i <= n; i++) { 51 | cin >> wt[i] >> val[i]; 52 | max_profit += val[i]; 53 | } 54 | cout << knapsack_2(max_profit) << endl; 55 | } 56 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/F_LCS: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Dynamic_Programming/Atcoder_Educational_DP_contest/F_LCS -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/F_LCS.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_f 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | #define inf INT_MAX 11 | #define minf INT_MIN 12 | #define pb push_back 13 | #define all(v) v.begin(),v.end() 14 | #define print(v) for(auto x:v) cout<= n || j >= m) return 0; 25 | if (dp[i][j] != -1) return dp[i][j]; 26 | 27 | if (s[i] == t[j]) return dp[i][j] = 1 + len_lcs(i + 1, j + 1, n, m); 28 | else return dp[i][j] = max(len_lcs(i + 1, j, n, m), len_lcs(i, j + 1, n, m)); 29 | } 30 | 31 | string get_lcs(int len) { 32 | int i = 0, j = 0; 33 | string lcs; 34 | while (len > 0) { 35 | if (s[i] == t[j]) { 36 | lcs.pb(s[i]); 37 | i++; 38 | j++; 39 | len--; 40 | } 41 | else if (dp[i + 1][j] > dp[i][j + 1]) i++; 42 | else j++; 43 | } 44 | return lcs; 45 | } 46 | 47 | int32_t main() { 48 | fastio; 49 | cin >> s >> t; 50 | int n = s.length(); 51 | int m = t.length(); 52 | memset(dp, -1, sizeof dp); 53 | int len = len_lcs(0, 0, n, m); 54 | cout << get_lcs(len) << endl; 55 | } 56 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/G_longest_path: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Dynamic_Programming/Atcoder_Educational_DP_contest/G_longest_path -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/G_longest_path.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_g 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | #define inf INT_MAX 11 | #define minf INT_MIN 12 | #define pb push_back 13 | #define all(v) v.begin(),v.end() 14 | #define print(v) for(auto x:v) cout<gr[N]; 22 | int dp[N]; //dp[i] = represents length of longest path starting at node i 23 | 24 | int longest_path(int src) { 25 | if (dp[src] != -1) return dp[src]; 26 | bool leaf_node = 1; 27 | int best_child = 0; 28 | for (auto child : gr[src]) { 29 | leaf_node = 0; 30 | best_child = max(best_child, longest_path(child)); 31 | } 32 | return dp[src] = (leaf_node ? 0 : 1 + best_child); 33 | } 34 | 35 | int32_t main() { 36 | fastio; 37 | int n, m; 38 | cin >> n >> m; 39 | for (int i = 1; i <= m; i++) { 40 | int u, v; 41 | cin >> u >> v; 42 | gr[u].pb(v); 43 | } 44 | memset(dp, -1, sizeof dp); 45 | int ans = 0; 46 | for (int i = 1; i <= n; i++) ans = max(ans, longest_path(i)); 47 | cout << ans << endl; 48 | } 49 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/H_Grid: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Dynamic_Programming/Atcoder_Educational_DP_contest/H_Grid -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/H_Grid.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_h 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | #define inf INT_MAX 11 | #define minf INT_MIN 12 | #define pb push_back 13 | #define all(v) v.begin(),v.end() 14 | #define print(v) for(auto x:v) cout<> h >> w; 46 | for (int i = 0; i < h; i++) { 47 | for (int j = 0; j < w; j++) { 48 | char ch; cin >> ch; 49 | if (ch == '.') dp[i][j] = 1; 50 | else dp[i][j] = 0; 51 | } 52 | } 53 | cout << grid_dp(h, w) << endl; 54 | } 55 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/I_coins: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Dynamic_Programming/Atcoder_Educational_DP_contest/I_coins -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/I_coins.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_i 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | #define inf INT_MAX 11 | #define minf INT_MIN 12 | #define pb push_back 13 | #define all(v) v.begin(),v.end() 14 | #define print(v) for(auto x:v) cout<&pr, int i, int x) { 24 | if (x == 0) return 1; 25 | if (i == 0) return 0; 26 | 27 | if (dp[i][x] > -1) return dp[i][x]; 28 | 29 | return dp[i][x] = pr[i] * coin(pr, i - 1, x - 1) + (1 - pr[i]) * coin(pr, i - 1, x); 30 | } 31 | 32 | int32_t main() { 33 | fastio; 34 | memset(dp, -1, sizeof dp); 35 | int n; cin >> n; 36 | vectorpr(n + 1); 37 | for (int i = 1; i <= n; i++) cin >> pr[i]; 38 | cout << fixed << setprecision(10); 39 | cout << coin(pr, n, (n + 1) / 2) << endl; 40 | } 41 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/J_sushi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Dynamic_Programming/Atcoder_Educational_DP_contest/J_sushi -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/J_sushi.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_j 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | #define inf INT_MAX 11 | #define INF LLONG_MAX 12 | #define minf INT_MIN 13 | #define MINF LLONG_MIN 14 | #define pb push_back 15 | #define all(v) v.begin(),v.end() 16 | #define print(v) for(auto x:v) cout< -0.9 ) return dp[x][y][z]; 31 | 32 | return dp[x][y][z] = (n + x * sushi(n, x - 1, y, z) + y * sushi(n, x + 1, y - 1, z) + z * sushi(n, x, y + 1, z - 1)) / (x + y + z); 33 | } 34 | 35 | int32_t main() { 36 | fastio; 37 | memset(dp, -1, sizeof dp); 38 | int n; cin >> n; 39 | int one{}, two{}, three{}; //No. of dishes having 1 sushies, two sushies and three sushies .NO. of zero sushies : N-(one + two + three) 40 | for (int i = 1; i <= n; i++) { 41 | int x; cin >> x; 42 | if (x == 1) one++; 43 | if (x == 2) two++; 44 | if (x == 3) three++; 45 | } 46 | cout << fixed << setprecision(10); 47 | cout << sushi(n, one, two, three) << endl; 48 | } 49 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/K_stones: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Dynamic_Programming/Atcoder_Educational_DP_contest/K_stones -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/K_stones.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_k 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | // #define inf INT_MAX 11 | #define inf 1e9+1 12 | #define INF LLONG_MAX 13 | #define minf INT_MIN 14 | #define MINF LLONG_MIN 15 | #define pb push_back 16 | #define all(v) v.begin(),v.end() 17 | #define print(v) for(auto x:v) cout<&v, int k) { 24 | int dp[k + 1] = {}; 25 | for (int i = 1; i <= k; i++) { 26 | for (int move : v) { 27 | if (i - move >= 0 && dp[i - move] == 0) dp[i] = 1; 28 | } 29 | } 30 | return dp[k] == 1 ? "First" : "Second"; 31 | } 32 | 33 | int32_t main() { 34 | fastio; 35 | int n, k; 36 | cin >> n >> k; 37 | vectorv(n); 38 | for (int i = 0; i < n; i++) cin >> v[i]; 39 | cout << k_stones(v, k) << endl; 40 | } 41 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/L_deque: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Dynamic_Programming/Atcoder_Educational_DP_contest/L_deque -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/L_deque.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_l 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | #define inf INT_MAX 11 | #define INF LLONG_MAX 12 | #define minf INT_MIN 13 | #define MINF LLONG_MIN 14 | #define pb push_back 15 | #define all(v) v.begin(),v.end() 16 | #define print(v) for(auto x:v) cout<v; 24 | 25 | ll L_deque(int i, int j, int turn) { 26 | if (i > j) return 0; 27 | 28 | if (dp[i][j] != -1) return dp[i][j]; 29 | 30 | if (turn == 1) return dp[i][j] = max(v[i] + L_deque(i + 1, j, 0), v[j] + L_deque(i, j - 1, 0)); 31 | else return dp[i][j] = min(L_deque(i + 1, j, 1), L_deque(i, j - 1, 1)); 32 | } 33 | 34 | int32_t main() { 35 | fastio; 36 | memset(dp, -1, sizeof dp); 37 | int n; cin >> n; 38 | v.resize(n + 1); 39 | ll sum{}; 40 | for (int i = 1; i <= n; i++) { 41 | cin >> v[i]; 42 | sum += v[i]; 43 | } 44 | ll x = L_deque(1, n, 1); 45 | ll y = sum - x; 46 | cout << x - y << endl; 47 | } 48 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/M_candies: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Dynamic_Programming/Atcoder_Educational_DP_contest/M_candies -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/M_candies.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_l 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | #define inf INT_MAX 11 | #define INF LLONG_MAX 12 | #define minf INT_MIN 13 | #define MINF LLONG_MIN 14 | #define pb push_back 15 | #define all(v) v.begin(),v.end() 16 | #define print(v) for(auto x:v) cout< A1 25 | ll dp[101][100001]; 26 | vectorv; 27 | 28 | ll candies(vector&v, int n, int k) { 29 | //Base Case 30 | for (int j = 0; j <= k; j++) dp[1][j] = (j > v[1] ? 0 : 1); 31 | for (int i = 2; i <= n; i++) { 32 | for (int j = 0; j <= k; j++) { 33 | if (j == 0) dp[i][j] = dp[i - 1][j]; 34 | else dp[i][j] = (dp[i][j - 1] + dp[i - 1][j] - ((j - v[i] - 1 >= 0) ? dp[i - 1][j - 1 - v[i]] : 0) + mod) % mod; 35 | } 36 | } 37 | return dp[n][k]; 38 | } 39 | 40 | int32_t main() { 41 | fastio; 42 | int n, k; 43 | cin >> n >> k; 44 | v.resize(n + 1); 45 | for (int i = 1; i <= n; i++) cin >> v[i]; 46 | cout << candies(v, n, k) << endl; 47 | } 48 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/N_slimes: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Dynamic_Programming/Atcoder_Educational_DP_contest/N_slimes -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/N_slimes.cpp: -------------------------------------------------------------------------------- 1 | // https://atcoder.jp/contests/dp/tasks/dp_n 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | #define inf INT_MAX 11 | #define INF LLONG_MAX 12 | #define minf INT_MIN 13 | #define MINF LLONG_MIN 14 | #define pb push_back 15 | #define all(v) v.begin(),v.end() 16 | #define print(v) for(auto x:v) cout<v; 28 | 29 | ll slime(int i, int j) { 30 | if (i == j) return 0; 31 | 32 | if (dp[i][j] != -1) return dp[i][j]; 33 | 34 | ll min_cost = INF; 35 | for (int k = i; k + 1 <= j; k++) 36 | min_cost = min(min_cost, sum[i][j] + slime(i, k) + slime(k + 1, j)); 37 | return dp[i][j] = min_cost; 38 | } 39 | 40 | void pre_processing(int n) { 41 | for (int i = 1; i <= n; i++) 42 | for (int j = i; j <= n; j++) 43 | sum[i][j] = v[j] + (j == i ? 0 : sum[i][j - 1]); 44 | } 45 | 46 | int32_t main() { 47 | fastio; 48 | memset(dp, -1, sizeof dp); 49 | int n; cin >> n; 50 | v.resize(n + 1); 51 | for (int i = 1; i <= n; i++) cin >> v[i]; 52 | pre_processing(n); 53 | cout << slime(1, n) << endl; 54 | } 55 | -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/O_matching.cpp: -------------------------------------------------------------------------------- 1 | //https://atcoder.jp/contests/dp/tasks/dp_o 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | #define inf INT_MAX 11 | #define INF LLONG_MAX 12 | #define minf INT_MIN 13 | #define MINF LLONG_MIN 14 | #define pb push_back 15 | #define all(v) v.begin(),v.end() 16 | #define print(v) for(auto x:v) cout<> n; 51 | for (int i = 1; i <= n; i++) { 52 | for (int j = 1; j <= n; j++) { 53 | cin >> compat[i][j]; 54 | } 55 | } 56 | memset(dp, -1, sizeof dp); 57 | cout << solve(1, n, ((1 << n) - 1)) << endl; 58 | 59 | } -------------------------------------------------------------------------------- /Dynamic_Programming/Atcoder_Educational_DP_contest/P_Independent set.cpp: -------------------------------------------------------------------------------- 1 | //https://atcoder.jp/contests/dp/tasks/dp_p 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | #define inf INT_MAX 11 | #define INF LLONG_MAX 12 | #define minf INT_MIN 13 | #define MINF LLONG_MIN 14 | #define pb push_back 15 | #define all(v) v.begin(),v.end() 16 | #define print(v) for(auto x:v) cout<tree[N]; 27 | int u, v; 28 | 29 | ll solve(int u, int constraint, int parent) { 30 | if (dp[u][constraint] != -1) return dp[u][constraint]; 31 | 32 | ll ans = 0; 33 | ll w = 1; 34 | for (int child : tree[u]) { 35 | if (child != parent) w = (w * solve(child, 0, u)) % mod; 36 | } 37 | ans = (ans + w); 38 | 39 | if (!constraint) { 40 | w = 1; 41 | for (int child : tree[u]) { 42 | if (child != parent) w = (w * solve(child, 1, u)) % mod; 43 | } 44 | ans = (ans + w) % mod; 45 | } 46 | return dp[u][constraint] = ans; 47 | } 48 | 49 | int32_t main() { 50 | fastio; 51 | int n; 52 | cin >> n; 53 | memset(dp, -1, sizeof dp); 54 | for (int i = 0; i < n - 1; i++) { 55 | cin >> u >> v; 56 | tree[u].pb(v); 57 | tree[v].pb(u); 58 | } 59 | cout << solve(1, 0, -1) << endl; 60 | } -------------------------------------------------------------------------------- /Dynamic_Programming/Cell_mitosis_Hackerblocks.cpp: -------------------------------------------------------------------------------- 1 | // There's a scientist named Brook who is interested in budding of cells. He has one container which initially contains only a single cell. Now Brook wants n number of cells in his container. So he can change the number of cells in container in 3 different ways -: 2 | // 3 | // Double the number of cells present in the container. 4 | // 5 | // Increase the number of cells in the container by 1. 6 | // 7 | // Decrease the number of cells in the container by 1. 8 | // 9 | // Now, all the above operations have different costs associated with them x,y,z respectively for above operations. Help brook in finding the minimum cost to generate n cells in the container starting from one cell . 10 | // 11 | // Input Format 12 | // Each test case contains 2 lines. First lines contains an integer n Second lines contains 3 space separated integers x, y, and z 13 | // 14 | // Constraints 15 | // 1<=n<=10^5 1<=x<=y<=z<=10^5 16 | // 17 | // Output Format 18 | // Output an integer denoting the minimum cost incurred to create n cells 19 | // 20 | // Sample Input 21 | // 5 22 | // 2 1 3 23 | // Sample Output 24 | // 4 25 | // Explanation 26 | // Initial number of cell is 1. Applying 2nd operations four times will give 5 cells in the container , and its total cost will be 1x4 = 4. One other way to do is - first adding a single cell with operation 2nd ,then doubling the cells , and then again adding one more cell , with cost = 1+2+1 =4. 27 | 28 | 29 | //https://hack.codingblocks.com/app/contests/1157/546/problem 30 | #include 31 | using namespace std; 32 | 33 | //Bottom Up DP Approach 34 | long long cellMitosis(int n,int x,int y,int z){ 35 | int dp[100001]; 36 | 37 | dp[0]=0; 38 | dp[1]=0; 39 | for(int i=2;i<=n;i++){ 40 | if(i%2==0) 41 | dp[i]=min(dp[i/2]+x , dp[i-1]+y); 42 | else 43 | dp[i]=min(dp[(i+1)/2]+x+z , dp[i-1]+y); 44 | } 45 | return dp[n]; 46 | } 47 | 48 | 49 | int main(){ 50 | int n,x,y,z; 51 | cin>>n>>x>>y>>z; 52 | cout< 2 | using namespace std; 3 | 4 | //Minimum coins needed to make a desired value 5 | 6 | //Top Down Approach 7 | int minCoinsTD(int n,int coins[],int t,int dp[]){ 8 | //Base Case 9 | if(n==0) 10 | return 0; 11 | 12 | //Lookup 13 | if(dp[n]!=0) 14 | return dp[n]; 15 | 16 | //Rec Case 17 | int ans=INT_MAX; 18 | for(int i=0;i=0){ 20 | int subproblem=minCoinsTD(n-coins[i],coins,t,dp); 21 | ans=min(ans,subproblem+1); 22 | } 23 | } 24 | return dp[n]=ans; 25 | } 26 | 27 | //Bottom Up Approach 28 | int minCoinsBU(int n,int coins[],int t){ 29 | int dp[100]={0}; 30 | 31 | //Iterate over all states 1...n 32 | for(int i=1;i<=n;i++){ 33 | //Initiliase our current ans to INT_MAX 34 | dp[i]=INT_MAX; 35 | //Iterating over the value of coins 36 | for(int j=0;j=0){ 38 | int subproblem=dp[i-coins[j]]; 39 | dp[i]=min(dp[i],subproblem+1); 40 | } 41 | } 42 | } 43 | return dp[n]; 44 | } 45 | 46 | 47 | 48 | 49 | int main(){ 50 | int n=15; 51 | int coins[]={1,7,10}; 52 | int dp[100]={0}; 53 | int t=sizeof(coins)/sizeof(int); 54 | cout< 2 | using namespace std; 3 | 4 | 5 | //Bottom up Approach 6 | //dp[i] : Number of non_decreasing subarray ending at index i. 7 | unsigned long long int countSubArray(int a[],int n){ 8 | unsigned long long int dp[n]; 9 | dp[0]=1; 10 | for(int i=1;i=a[i-1]) 12 | dp[i]=dp[i-1]+1; 13 | else 14 | dp[i]=1; 15 | } 16 | unsigned long long int count=0; 17 | for(int i=0;i>t; 28 | while(t--){ 29 | int n; 30 | cin>>n; 31 | int a[n]; 32 | for(int i=0;i>a[i]; 34 | cout << countSubArray(a, n)< 3 | using namespace std; 4 | #define mod 1000000007 5 | long int Friend_Pairing_Problem(int n){ 6 | long int dp[n+1]={0}; 7 | 8 | for(int i=1;i<=n;i++){ 9 | if(i<=2) 10 | dp[i]=i; 11 | else 12 | dp[i]=dp[i-1]+(i-1)*dp[i-2]; 13 | } 14 | return dp[n]%mod; 15 | } 16 | 17 | 18 | int main(){ 19 | 20 | int t; 21 | cin>>t; 22 | while(t--){ 23 | int n; 24 | cin>>n; 25 | cout< 2 | using namespace std; 3 | 4 | //Top Down Approach : O(n) sapace complexity and O(nk) time complexity 5 | int ladders_topdown(int n,int k,int dp[]){ 6 | 7 | //Base case 8 | if(n==0) 9 | return 1; 10 | 11 | //Lookup 12 | if(dp[n]!=0) 13 | return dp[n]; 14 | 15 | //Recursive case 16 | int ways=0; 17 | for(int i=1;i<=k;i++){ 18 | if(n-i>=0) 19 | ways+=ladders_topdown(n-i,k,dp); 20 | } 21 | return ways; 22 | } 23 | 24 | //Bottom Up Approach : O(n) sapace complexity and O(nk) time complexity 25 | int ladders_bottomup(int n,int k){ 26 | int dp[100]={0}; 27 | 28 | //Base Case 29 | dp[0]=1; 30 | 31 | for(int i=1;i<=n;i++){ 32 | for(int j=1;j<=k && i>=j;j++) 33 | dp[i]+=dp[i-j]; 34 | } 35 | 36 | return dp[n]; 37 | } 38 | 39 | //Optimised Bottom Up ladder DP Aprroach : O(n+k) time complexity and O(n) space complexity 40 | int ladders_Optimised(int n,int k){ 41 | int dp[100]={0}; 42 | 43 | dp[0]=dp[1]=1; 44 | for(int i=2;i<=k;i++) 45 | dp[i]=2*dp[i-1]; 46 | 47 | for(int i=k+1;i<=n;i++) 48 | dp[i]=2*dp[i-1]-dp[i-1-k]; 49 | 50 | return dp[n]; 51 | } 52 | 53 | 54 | int main(){ 55 | ios_base::sync_with_stdio(false); 56 | cin.tie(NULL); 57 | 58 | int n,k; 59 | cin>>n>>k; 60 | 61 | int dp[100]={0}; 62 | cout< 2 | using namespace std; 3 | #define size 100 4 | //Top Down Approach 5 | int lcsTD(string s1,int m,string s2,int n,int dp[][size]){ 6 | if(n==0 || m==0) 7 | return 0; 8 | 9 | if(dp[m-1][n-1]!=-1) 10 | return dp[m-1][n-1]; 11 | 12 | if(s1[m-1]==s2[n-1]) 13 | dp[m-1][n-1] = 1 + lcsTD(s1,m-1,s2,n-1,dp); 14 | else 15 | dp[m-1][n-1] = max(lcsTD(s1,m-1,s2,n,dp),lcsTD(s1,m,s2,n-1,dp)); 16 | 17 | return dp[m-1][n-1]; 18 | } 19 | //Bottom Up Approach 20 | int lcsBU(string s1,int m,string s2,int n){ 21 | int dp[m+1][n+1]; 22 | 23 | for(int i=0;i<=m;i++){ 24 | for(int j=0;j<=n;j++){ 25 | if(i==0 || j==0) 26 | dp[i][j]=0; 27 | else if(s1[i-1]==s2[j-1]) 28 | dp[i][j]=1+dp[i-1][j-1]; 29 | else 30 | dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 31 | } 32 | } 33 | return dp[m][n]; 34 | } 35 | int main(){ 36 | string s1="abcdef"; 37 | string s2="bcde"; 38 | 39 | int dp[100][100]; 40 | for(int i=0;i<100;i++) 41 | for(int j=0;j<100;j++) 42 | dp[i][j]=-1; 43 | cout< 2 | using namespace std; 3 | 4 | 5 | //Standard Solution : O(n2) time complexity and O(n) space complexity. 6 | //dp[i] represents the longest increasing subsequence ending at index i. 7 | int lis(int a[],int n){ 8 | int dp[n]={}; 9 | for(int i=0;idp[mid]) 65 | low=mid+1; 66 | else if(a[i] 7 | using namespace std; 8 | int mod = 1e9+7; 9 | 10 | 11 | 12 | int main(){ 13 | 14 | 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /Dynamic_Programming/MatrixChainMultiplication.cpp: -------------------------------------------------------------------------------- 1 | // Matrix Chain Multiplication 2 | // 3 | // 4 | // Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. There are many options to multiply a chain of matrices because matrix multiplication is associative i.e. no matter how one parenthesize the product, the result will be the same. 5 | // 6 | // Example: 7 | // if you had four matrices A, B, C, and D, you would have: 8 | // 9 | // (ABC)D = (AB)(CD) = A(BCD) = .... 10 | // However, the order in which one parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. 11 | // 12 | // For example: 13 | // 14 | // A: 10 × 30 matrix 15 | // B : 30 × 5 matrix 16 | // C : 5 × 60 matrix 17 | // Then, 18 | // (AB)C = (10×30×5) + (10×5×60) 19 | // = 1500 + 3000 20 | // = 4500 operations 21 | // A(BC) = (30×5×60) + (10×30×60) 22 | // = 9000 + 18000 23 | // = 27000 operations. 24 | // Given an array arr[] which represents the chain of matrices such that the ith matrix Ai is of dimension arr[i-1] x arr[i]. Your task is to write a function that should print the minimum number of multiplications needed to multiply the chain. 25 | // 26 | // Input: p[] = {40, 20, 30, 10, 30} 27 | // Output: 26000 28 | // There are 4 matrices of dimensions 40x20, 29 | // 20x30, 30x10 and 10x30. Let the input 4 30 | // matrices be A, B, C and D. The minimum 31 | // number of multiplications are obtained 32 | // by putting parenthesis in following way 33 | // (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30 34 | // 35 | // Input: p[] = {10, 20, 30, 40, 30} 36 | // Output: 30000 37 | // There are 4 matrices of dimensions 10x20, 38 | // 20x30, 30x40 and 40x30. Let the input 4 39 | // matrices be A, B, C and D. The minimum 40 | // number of multiplications are obtained by 41 | // putting parenthesis in following way 42 | // ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30 43 | // Input: 44 | // The first line of the input contains an integer T, denoting the number of test cases. Then T test case follows. The first line of each test case contains an integer N, denoting the number of elements in the array. 45 | // Then next line contains N space separated integers denoting the values of the element in the array. 46 | // 47 | // Output: 48 | // For each test case the print the minimum number of operations needed to multiply the chain. 49 | // 50 | // Constraints: 51 | // 1<=T<=100 52 | // 2<=N<=100 53 | // 1<=A[]<=500 54 | // 55 | // Example: 56 | // Input: 57 | // 2 58 | // 5 59 | // 1 2 3 4 5 60 | // 3 61 | // 3 3 3 62 | // Output: 63 | // 38 64 | // 27 65 | 66 | 67 | #include 68 | using namespace std; 69 | 70 | //Bottom Up Approach 71 | //Time Complexity: O(n^3) 72 | //Auxiliary Space: O(n^2) 73 | int matrixChainMultiplication(int a[],int n){ 74 | int dp[n][n]; 75 | int i,j,k,l,q; 76 | for(i=1;i>t; 97 | while(t--){ 98 | int n; 99 | cin>>n; 100 | int a[n]; 101 | for(int i=0;i>a[i]; 103 | 104 | cout< 2 | using namespace std; 3 | 4 | //Bottom Up DP Approach 5 | int kadaneIIBU(int a[],int n){ 6 | if(n==1) 7 | return a[0]; 8 | 9 | int dp[100]={0}; 10 | 11 | dp[0]=a[0]; 12 | dp[1]=max(a[0],a[1]); 13 | for(int i=2;i>n; 38 | int a[n]; 39 | for(int i=0;i>a[i]; 41 | 42 | cout< 6 | using namespace std; 7 | 8 | //Either you come from top or you come from left to any particular box 9 | int minCost(int cost[][3],int dp[][3]){ 10 | for(int i=0;i<3;i++){ 11 | for(int j=0;j<3;j++){ 12 | if(i==0 && j==0) 13 | dp[i][j]=cost[0][0]; 14 | else if(i==0) 15 | dp[i][j]=dp[i][j-1]+cost[0][j]; 16 | else if(j==0) 17 | dp[i][j]=dp[i-1][0]+cost[i][0]; 18 | else 19 | dp[i][j]=min(dp[i-1][j],dp[i][j-1])+cost[i][j]; 20 | } 21 | } 22 | return dp[2][2]; 23 | } 24 | 25 | int main(){ 26 | 27 | int cost[][3]={{1,5,2},{7,1,1},{8,1,3}}; 28 | int dp[3][3]={0}; 29 | cout< 38 | using namespace std; 39 | 40 | int a[1000]; 41 | long long dp[1000][1000]; 42 | 43 | long long sum(int s,int e){ 44 | long long ans=0; 45 | for(int i=s;i<=e;i++){ 46 | ans+=a[i]; 47 | ans%=100; 48 | } 49 | return ans; 50 | } 51 | 52 | 53 | long long solveMixtures(int i,int j){ 54 | if(i>=j) 55 | return 0; 56 | 57 | //If the ans is already computed 58 | if(dp[i][j]!=-1) 59 | return dp[i][j]; 60 | 61 | //we have to break the answer at every possible k. 62 | dp[i][j]=INT_MAX; 63 | for(int k=i;k<=j;k++){ 64 | dp[i][j]=min(dp[i][j],solveMixtures(i,k) + solveMixtures(k+1,j) + sum(i,k)*sum(k+1,j)); 65 | } 66 | return dp[i][j]; 67 | } 68 | 69 | int main(){ 70 | 71 | int n; 72 | while(scanf("%d",&n)!=EOF){ 73 | 74 | for(int i=0;i>a[i]; 76 | 77 | memset(dp,-1,sizeof(dp)); 78 | 79 | cout< 2 | using boost::multiprecision::cpp_int; // https://www.geeksforgeeks.org/factorial-large-number-using-boost-multiprecision-library/ 3 | using namespace std; 4 | 5 | //Sigma dp[i-1]*dp[n-i] from i=1 to n 6 | cpp_int Nth_Catalan_Number(int n) { 7 | cpp_int dp[n + 1] = {0}; 8 | dp[0] = 1; 9 | dp[1] = 1; 10 | for (int i = 2; i <= n; i++) { 11 | for (int j = 1; j <= i; j++) 12 | dp[i] += dp[j - 1] * dp[i - j]; 13 | } 14 | return dp[n]; 15 | } 16 | 17 | //Sigma dp[i]*dp[n-i-1] from i=0 to n-1 18 | cpp_int Nth_Catalan_Number(int n) { 19 | cpp_int dp[n + 1] = {0}; 20 | dp[0] = 1; 21 | dp[1] = 1; 22 | for (int i = 2; i <= n; i++) { 23 | for (int j = 0; j < i; j++) 24 | dp[i] += dp[j] * dp[i - j - 1]; 25 | } 26 | return dp[n]; 27 | } 28 | 29 | int main() { 30 | 31 | int t; 32 | cin >> t; 33 | 34 | while (t--) { 35 | int n; 36 | cin >> n; 37 | cout << Nth_Catalan_Number(n) << endl; 38 | } 39 | 40 | return 0; 41 | } 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Dynamic_Programming/Optimal_Game_Strategy.cpp: -------------------------------------------------------------------------------- 1 | //https://practice.geeksforgeeks.org/problems/optimal-strategy-for-a-game/0 2 | 3 | #include 4 | using namespace std; 5 | 6 | int dp[101][101]; 7 | 8 | //Top Bottom Approach 9 | int OptimalGameStrategy(int value[],int i,int j,int sum){ 10 | if(j==i+1) 11 | return max(value[i],value[j]); 12 | 13 | if(dp[i][j]!=-1) 14 | return dp[i][j]; 15 | 16 | dp[i][j]=max(sum-OptimalGameStrategy(value,i+1,j,sum-value[i]),sum-OptimalGameStrategy(value,i,j-1,sum-value[j])); 17 | 18 | return dp[i][j]; 19 | 20 | } 21 | 22 | 23 | int main(){ 24 | int t; 25 | cin>>t; 26 | 27 | while(t--){ 28 | int n; 29 | cin>>n; 30 | int value[n]; 31 | 32 | int sum=0; 33 | for(int i=0;i>value[i]; 35 | sum+=value[i]; 36 | } 37 | memset(dp,-1,sizeof(dp)); 38 | cout< (1, 2) -> (2, 2) -> (3, 2) -> (4, 2) -> (4, 3) and 36 | // (1, 1) -> (2, 1) -> (2, 2) -> (3, 2) -> (4, 2) -> (4, 3) 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | #include 46 | using namespace std; 47 | #define mod 1000000007 48 | 49 | int dp[1001][1001]; 50 | int numWays(int row,int col){ 51 | //Base Case 52 | if(dp[0][0]==-1) 53 | return 0; 54 | 55 | 56 | //Compute the number of rows for the first rows 57 | for(int j=0;j>m>>n>>number_of_cell_blocked; 99 | int x,y; 100 | for(int i=0;i>x>>y; 102 | dp[x-1][y-1]=-1; 103 | } 104 | cout< 2 | using namespace std; 3 | 4 | //Top Down Approach 5 | int maxProfitTD(int a[],int n,int dp[]){ 6 | if(n==0) 7 | return 0; 8 | 9 | if(dp[n]!=0) 10 | return dp[n]; 11 | 12 | int best=0; 13 | for(int i=1;i<=n;i++){ 14 | int profit=a[i]+maxProfitTD(a,n-i,dp); 15 | best=max(best,profit); 16 | } 17 | return dp[n]=best; 18 | } 19 | 20 | //Bottom Up Approach 21 | int maxProfitBU(int a[],int n){ 22 | int dp[100]={0}; 23 | 24 | 25 | for(int len=1;len<=n;len++){ 26 | for(int cut=1;cut<=len && len>=cut ;cut++){ 27 | dp[len]=max(a[cut]+dp[len-cut],dp[len]); 28 | } 29 | } 30 | return dp[n]; 31 | } 32 | 33 | 34 | int main(){ 35 | ios_base::sync_with_stdio(false); 36 | cin.tie(NULL); 37 | 38 | int priceOfEachLen[100]={0}; 39 | 40 | int length; 41 | cin>>length; 42 | 43 | for(int i=1;i<=length;i++) 44 | cin>>priceOfEachLen[i]; 45 | 46 | int dp[100]={0}; 47 | 48 | cout< 3 | using namespace std; 4 | #define ll long long int 5 | #define endl "\n" 6 | #define fast ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 7 | #define mod 1000000007 8 | 9 | 10 | 11 | int n = 4; 12 | //Adjacency matrix which defines our graph 13 | //dist[i][j] : distance between city i and city j. 14 | int dist[10][10] = { 15 | {0, 20, 42, 25}, 16 | {20, 0, 30, 34}, 17 | {42, 30, 0, 10}, 18 | {25, 34, 10, 0} 19 | }; 20 | //If all cities has been visited 21 | int visited_all = (1 << n) - 1; //(1111) 22 | 23 | int dp[1 << 4][4]; 24 | //mask denotes the set of city which has been visited so far 25 | int tsp(int mask, int pos) { 26 | //Base Case 27 | if (mask == visited_all) 28 | return dist[pos][0]; 29 | 30 | //Lookup Case 31 | if (dp[mask][pos] != -1) 32 | return dp[mask][pos]; 33 | 34 | int ans = INT_MAX; 35 | //Try to go to unvisited cities 36 | for (int city = 0; city < n; city++) { 37 | //It that set bit is off ,it means that city is not visited. 38 | if ((mask & (1 << city)) == 0) { 39 | int newAns = dist[pos][city] + tsp(mask | (1 << city), city); 40 | ans = min(ans, newAns); 41 | } 42 | } 43 | return dp[mask][pos] = ans; 44 | } 45 | 46 | int main() 47 | { 48 | fast; 49 | for (int i = 0; i < (1 << n); i++) 50 | for (int j = 0; j < n; j++) 51 | dp[i][j] = -1; 52 | cout << "Minimum Weight Hamiltonian path costs " << tsp(1, 0) << endl; 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Dynamic_Programming/WinesProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | //Top Down Approach 6 | int profit(int wines[],int i,int j,int y,int dp[][100]){ 7 | //Base case 8 | if(i>j) 9 | return 0; 10 | 11 | //Return if dp[i][j] is known 12 | if(dp[i][j]!=0) 13 | return dp[i][j]; 14 | 15 | //Recursive case 16 | int opt1=wines[i]*y + profit(wines,i+1,j,y+1,dp); 17 | int opt2=wines[j]*y + profit(wines,i,j-1,y+1,dp); 18 | 19 | return dp[i][j]=max(opt1,opt2); 20 | } 21 | 22 | //Bottom Up Approach 23 | 24 | 25 | int main(){ 26 | int wines[]={2,3,5,1,4}; 27 | int dp[100][100]={0}; 28 | int n=sizeof(wines)/sizeof(int); 29 | int year=1; 30 | cout< 2 | using namespace std; 3 | /* 4 | //Recursive Approach : (2^n) 5 | int fib(int n){ 6 | //base case 7 | if(n==0 || n==1) 8 | return n; 9 | int ans; 10 | ans=fib(n-1)+fib(n-2); 11 | return ans; 12 | } 13 | */ 14 | 15 | //Top Down DP Approach or Recursion + Memoization 16 | int fibTD(int n,int dp[]){ 17 | if(n==0 || n==1) 18 | return n; 19 | 20 | if(dp[n]!=0) 21 | return dp[n]; 22 | 23 | int ans; 24 | ans=fibTD(n-1,dp)+fibTD(n-2,dp); 25 | return dp[n]=ans; 26 | 27 | } 28 | //Down Top DP Approach 29 | int fibBT(int n){ 30 | int dp[100]={0}; 31 | dp[1]=1; 32 | 33 | for(int i=2;i<=n;i++) 34 | dp[i]=dp[i-1]+dp[i-2]; 35 | 36 | return dp[n]; 37 | } 38 | //Bottom Up Approach with Space Optimisation 39 | int fibSpaceOptimised(int n){ 40 | if(n==0 || n==1) 41 | return n; 42 | 43 | int a=0,b=1; 44 | for(int i=2;i<=n;i++){ 45 | b=a+b; 46 | a=b-a; 47 | } 48 | return b; 49 | } 50 | int main(){ 51 | int n; 52 | cin>>n; 53 | 54 | int dp[100]={0}; 55 | cout< 2 | using namespace std; 3 | #define fastio ios_base::sync_with_stdio(false), cin.tie(NULL), cin.tie(NULL) 4 | 5 | int maxSumIS(int a[], int n) 6 | { 7 | //longest sum subsequence ending at index i 8 | int dp[n]; 9 | for(int i = 0; i < n; ++i) { 10 | dp[i] = a[i]; 11 | } 12 | 13 | for(int i = 1; i < n; ++i) { 14 | for(int j = 0; j < i; ++j) { 15 | if (a[j] < a[i] && dp[i] < dp[j] + a[i]) { 16 | dp[i] = dp[j] + a[i]; 17 | } 18 | } 19 | } 20 | int msis = 0; 21 | for(int i = 0; i < n; ++i) { 22 | msis = max(msis, dp[i]); 23 | } 24 | return msis; 25 | } 26 | 27 | 28 | int main() { 29 | fastio; 30 | int a[] = {20, 8, 27, 37, 9, 12, 46}; 31 | int n = sizeof(a) / sizeof(int); 32 | cout << maxSumIS(a, n) << endl; 33 | } -------------------------------------------------------------------------------- /Dynamic_Programming/max_subarray_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //Kadane's Algorithm 5 | 6 | //Bottom Up Approach : O(n) time complexity and space complexity 7 | int maxSum(int a[],int n){ 8 | int dp[100]={0}; 9 | dp[0]=a[0]>0?a[0]:0; 10 | 11 | int max_so_far=dp[0]; 12 | for(int i=1;i 2 | using namespace std; 3 | 4 | //Minimum steps to one :- n->n/3, n/2, n-1 5 | //Top Down Approach 6 | int minStepsTD(int n,int dp[]){ 7 | //Base Case 8 | if(n==1) 9 | return 0; 10 | 11 | 12 | //Lookup if n is already computed 13 | if(dp[n]!=0) 14 | return dp[n]; 15 | 16 | //Compute if dp[n] is not known 17 | int opt1=INT_MAX,opt2=INT_MAX,opt3=INT_MAX; 18 | if(n%3==0) 19 | opt1 = minStepsTD(n/3,dp); 20 | if(n%2==0) 21 | opt2 = minStepsTD(n/2,dp); 22 | opt3 = minStepsTD(n-1,dp); 23 | 24 | int ans=min(min(opt1,opt2),opt3) + 1; 25 | 26 | return dp[n]=ans; 27 | } 28 | 29 | //Bottom Up Approach 30 | int minStepsBU(int n){ 31 | int dp[100]={0}; 32 | 33 | dp[1]=0; 34 | for(int i=2;i<=n;i++){ 35 | int opt1,opt2,opt3; 36 | opt1=INT_MAX,opt2=INT_MAX,opt3=INT_MAX; 37 | if(i%3==0) 38 | opt1=dp[i/3]; 39 | if(i%2==0) 40 | opt2=dp[i/2]; 41 | opt3=dp[i-1]; 42 | 43 | dp[i]=min(min(opt1,opt2),opt3)+1; 44 | } 45 | return dp[n]; 46 | } 47 | 48 | 49 | int main(){ 50 | int n; 51 | cin>>n; 52 | 53 | int dp[100]={0}; 54 | cout< 23 | using namespace std; 24 | #define ll long long int 25 | #define endl "\n" 26 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 27 | #define mod 1000000007 28 | #define gcd __gcd 29 | #define inf INT_MAX 30 | #define INF LLONG_MAX 31 | #define minf INT_MIN 32 | #define MINF LLONG_MIN 33 | #define pb push_back 34 | #define all(v) v.begin(),v.end() 35 | #define print(v) for(auto x:v) cout<> t; 57 | while (t--) { 58 | int n, m; 59 | cin >> n >> m; 60 | cout << tiling(n, m) << endl; 61 | } 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /Fenwicktree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<f; 20 | int n; 21 | void init(int n) { 22 | this->n = n + 1; 23 | f.resize(n + 1, 0); 24 | } 25 | //Returns sums of prefix from 1...x 26 | int sum(int x) { 27 | x++;//Due to one based indexing 28 | int ans = 0; 29 | while (x > 0) { 30 | ans += f[x]; 31 | x = x - (x & -x); 32 | } 33 | return ans; 34 | } 35 | //Add value to index idx 36 | void add(int idx, int val) { 37 | idx++;//Due to one based indexing 38 | while (idx < n) { 39 | f[idx] += val; 40 | idx = idx + (idx & -idx); 41 | } 42 | } 43 | int sum(int l, int r) { 44 | return sum(r) - sum(l - 1); 45 | } 46 | }; 47 | 48 | int32_t main() { 49 | fastio; 50 | int n; 51 | cin >> n; 52 | fenwick_tree tree; 53 | tree.init(n); 54 | int a[n]; 55 | for (int i = 0; i < n; i++) { 56 | cin >> a[i]; 57 | tree.add(i, a[i]); 58 | } 59 | cout << tree.sum(0) << endl; 60 | cout << tree.sum(2, 4) << endl; 61 | cout << tree.sum(4) << endl; 62 | cout << tree.sum(1, 3) << endl; 63 | } 64 | -------------------------------------------------------------------------------- /Graph/Articulation_point_and_bridges.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define FASTIO ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<gr[N]; 20 | int disc[N], low[N], timer; 21 | setart_point; 22 | vector>bridge; 23 | 24 | void dfs(int cur, int par = 0) { 25 | int no_of_child = 0; 26 | disc[cur] = low[cur] = timer++; 27 | for (auto child : gr[cur]) { 28 | if (!disc[child]) { 29 | dfs(child, cur); 30 | no_of_child++; 31 | low[cur] = min(low[cur], low[child]); 32 | //Articulation point 33 | if (par != 0 && low[child] >= disc[cur]) 34 | art_point.insert(cur); 35 | //Bridge 36 | if (low[child] > disc[cur]) 37 | bridge.pb({cur, child}); 38 | } 39 | else if (child != par) { 40 | //Backedge and cycle found 41 | low[cur] = min(low[cur], disc [child]); 42 | } 43 | } 44 | //Separate case for root to be Articulation Point 45 | if (par == 0 && no_of_child >= 2) 46 | art_point.insert(cur); 47 | } 48 | 49 | int32_t main() { 50 | int n, m; 51 | cin >> n >> m; 52 | for (int i = 0; i < m; i++) { 53 | int x, y; 54 | cin >> x >> y; 55 | gr[x].pb(y); 56 | gr[y].pb(x); 57 | } 58 | timer = 1; 59 | dfs(1); 60 | for (auto x : art_point) 61 | cout << x << " "; 62 | cout << endl; 63 | for (auto x : bridge) 64 | cout << x.first << " --- " << x.second << endl; 65 | } 66 | -------------------------------------------------------------------------------- /Graph/Bellmond_Ford_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | // //Bellman Ford Algorithm 2 | // ----> Single source shortest path Algorithm. 3 | // ----> Also handle negative weight edges. 4 | // ----> Negative Weight cycle : If there is a path from source to destination 5 | // where i encounters a cycle whose total weight of all the edges is Negative 6 | // ,then the minimum distance from source to destination will be minus infinity. 7 | // ----> Why not Dijsktra ? It works only for non negative edges. 8 | // ----> Bellman Ford Algorithm also works for positive edges but we use Dijsktra 9 | // because it has a time complexity of O(VlogE). 10 | // ----> Bellman Ford Algorithm works in time complexity of O(V * E). 11 | // ----> Why directed , not undirected ? If in a undirected graph , there is a 12 | // negative weight edges, then we cannot apply Bellman Ford Algorithm 13 | // because it will make a negative weight cycles. 14 | // ----> It works like a dynamic programming way. 15 | // ----> Worst Path Length from source to destination (1-->2-->3-->4-->5) can be (N(nodes)-1) edges. 16 | // It means that (n-1) iteration or we have to apply Bellman Ford Algorithm 17 | // (n-1) times to find shortest path from source to destination. 18 | // ----> We will not consider cycle in positive weight cycles. 19 | // ----> If there is a negative weight cycle , then Relaxation of edges will be 20 | // done infinity times. 21 | // 22 | // <----------------------------Methods-----------------------------------------> 23 | // 1---> distance of source will be zero and distance of other vertex will be INT_MAX. 24 | // 2---> Relax all edges (n-1) times. 25 | // 3---> If I can perform further Relaxation on any edge, then that edge is in negative 26 | // weight cycles because atmost (n-1) Relaxation is required for Bellman Ford 27 | // Algorithm. 28 | // 29 | // Example 1. 30 | // Input : 31 | // 3 3 32 | // 2 1 -4 33 | // 1 3 5 34 | // 3 2 -7 35 | // Output : 36 | // There is a negative weight cycle in our Graph 37 | // 38 | // Example 2. 39 | // Input : 40 | // 3 3 41 | // 1 2 4 42 | // 1 3 5 43 | // 3 2 -7 44 | // Output : 45 | // Distance from source to 1 : 0 46 | // Distance from source to 2 : -2 47 | // Distance from source to 3 : 5 48 | 49 | 50 | 51 | #include 52 | using namespace std; 53 | #define ll long long int 54 | #define endl "\n" 55 | #define fast ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 56 | #define mod 1000000007 57 | 58 | //Code for Bellman Ford Algorithm 59 | 60 | vectorbellman_ford(int n, int src, vector>edges) { 61 | //Minimum distance from source to i. 62 | //dist(src,i). 63 | vector dist(n + 1, INT_MAX); 64 | dist[src] = 0; 65 | 66 | //Relax all the edges (n-1) times. 67 | for (int i = 0; i < n - 1; i++) { 68 | for (auto x : edges) { 69 | int from = x[0], to = x[1], weight = x[2]; 70 | if (dist[from] != INT_MAX && dist[to] > dist[from] + weight) 71 | //Relaxed the edges (n-1) times. 72 | dist[to] = dist[from] + weight; 73 | } 74 | } 75 | //Let's check for negative weight cycle. 76 | for (auto x : edges) { 77 | int from = x[0], to = x[1], weight = x[2]; 78 | if (dist[from] != INT_MAX && dist[to] > dist[from] + weight) { 79 | cout << "There is a negative weight cycle in our Graph" << endl; 80 | exit(0);//It will successfully terminate the program. 81 | } 82 | } 83 | return dist; 84 | } 85 | 86 | int main() { 87 | fast; 88 | int n, m; 89 | cin >> n >> m; 90 | vector>edges; 91 | for (int i = 0; i < m; i++) { 92 | int from, to, weight; 93 | cin >> from >> to >> weight; 94 | edges.push_back({from, to, weight}); 95 | } 96 | int src = 1; 97 | vectordistance = bellman_ford(n, src, edges); 98 | for (int i = 1; i <= n; i++) 99 | cout << "Distance from source to " << i << " : " << distance[i] << endl; 100 | cout << endl; 101 | 102 | return 0; 103 | } 104 | -------------------------------------------------------------------------------- /Graph/Bipartite_Check.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int N = 100005, M = 23; 5 | vectorgr[N]; 6 | int visited[N]; 7 | bool odd_cycle = 0; 8 | 9 | void dfs(int cur, int parent, int color) { 10 | visited[cur] = color; 11 | for (auto child : gr[cur]) { 12 | if (visited[child] == 0) { 13 | dfs(child, cur, 3 - color); 14 | } 15 | else if (child != parent && color == visited[child]) { 16 | // backedge and odd length cycle 17 | odd_cycle = 1; 18 | } 19 | } 20 | return; 21 | } 22 | 23 | void solve() { 24 | int n, m; 25 | cin >> n >> m; 26 | for (int i = 0; i < m; i++) { 27 | int x, y; 28 | cin >> x >> y; 29 | gr[x].push_back(y); 30 | gr[y].push_back(x); 31 | } 32 | dfs(1, 0, 1); 33 | if (odd_cycle) 34 | cout << "Not Bipartite graph" << endl; 35 | else 36 | cout << "Bipartite graph" << endl; 37 | } 38 | 39 | int main() { 40 | solve(); 41 | } 42 | -------------------------------------------------------------------------------- /Graph/Breadth_First_Search_BFS.cpp: -------------------------------------------------------------------------------- 1 | //Breadth First Search 2 | //Traversing all the nodes of the graph. 3 | //Recursive way 4 | //It is like a level order traversal of all the node i.e same level means same distance from the source node. 5 | #include 6 | using namespace std; 7 | 8 | template 9 | class Graph{ 10 | map>l; 11 | public: 12 | void addEdge(int x,int y){ 13 | l[x].push_back(y); 14 | l[y].push_back(x); 15 | } 16 | void bfs(T sourceNode){ 17 | mapvisited; 18 | queueq; 19 | q.push(sourceNode); 20 | visited[sourceNode]=true; 21 | while(!q.empty()){ 22 | T node=q.front(); 23 | q.pop(); 24 | cout<g; 41 | g.addEdge(0,1); 42 | g.addEdge(1,2); 43 | g.addEdge(2,3); 44 | g.addEdge(3,4); 45 | g.addEdge(4,5); 46 | 47 | g.bfs(0); 48 | 49 | 50 | return 0; 51 | } 52 | 53 | /* 54 | #include 55 | using namespace std; 56 | 57 | vector bfs(vector g[], int N) { 58 | vector vis (N, false); 59 | int s = 0; 60 | vis[s] = true; // Initially mark source vertex as visited(true) 61 | vector res; 62 | queue q; 63 | q.push(s); // Push the source vertex to queue 64 | 65 | while (!q.empty()) // Till queue is not empty 66 | { 67 | int t = q.front(); 68 | res.push_back (t); 69 | 70 | q.pop(); // Pop the queue front 71 | 72 | for (int v : 73 | g[t]) // Traverse through all the connected components of front 74 | { 75 | if (!vis[v]) { // If they are not visited, mark them visited and add 76 | // to queue 77 | vis[v] = true; 78 | q.push(v); 79 | } 80 | } 81 | } 82 | return res; 83 | } 84 | 85 | 86 | int main(){ 87 | int t; 88 | cin>>t; 89 | while(t--){ 90 | int n,e; 91 | cin>>n>>e; 92 | vectoradj[n]; 93 | for(int i=0;i>u>>v; 96 | adj[u].push_back(v); 97 | adj[v].push_back(u); 98 | } 99 | vectorres=bfs(adj,n); 100 | for(int i=0;i 4 | using namespace std; 5 | 6 | //Check if a Undirected Graph is a Tree or Not. 7 | //If a Graph contains a cycle , then it is tree ,else it is a tree. 8 | //If a node is visited by more than one path, then it contains a cycle. 9 | class Graph{ 10 | 11 | list*l; 12 | int V; 13 | public: 14 | Graph(int V){ 15 | this->V=V; 16 | l=new list[V]; 17 | } 18 | void addEdge(int x,int y){ 19 | //Undirected Graph 20 | l[x].push_back(y); 21 | l[y].push_back(x); 22 | } 23 | bool is_tree(){ 24 | bool *visited=new bool[V]; 25 | int *parent=new int[V]; 26 | 27 | queueq; 28 | 29 | for(int i=0;i 3 | // You have been given an array of n unpainted elements. 4 | // By unpainted, we mean that each element initially has a value of 0. 5 | // You have to process q queries of the form l r c, in which you paint all the elements of the 6 | // array from index l to index r with color c. Assume that, each new color currently being applied 7 | // to an element overrides its previous color. Output the color of each element after all the queries 8 | // have been processed. 9 | 10 | // Note: The problem is guaranteed to be solved using C or C++ programming language. 11 | 12 | // Input 13 | // The first line of input consists of two integers n and q. Next q lines consists of 3 integers l, r and c denoting the starting index, ending index and the color respectively. 14 | 15 | // 1 <= n <= 200000 16 | // 1 <= q <= 200000 17 | // 1 <= l <= r <= n 18 | // 1 <= c <= 1 000 000 000 19 | // Output 20 | // Output the final color of each element starting from index 1 on a new line. 21 | 22 | // Example 23 | // Input 24 | // 4 3 25 | // 1 3 2 26 | // 2 4 6 27 | // 2 3 7 28 | // Output: 29 | // 2 30 | // 7 31 | // 7 32 | // 6 33 | // Input 34 | // 10 5 35 | // 3 9 13 36 | // 1 4 9 37 | // 2 10 14 38 | // 2 7 10 39 | // 6 9 44 40 | // Output 41 | // 9 42 | // 10 43 | // 10 44 | // 10 45 | // 10 46 | // 44 47 | // 44 48 | // 44 49 | // 44 50 | // 14 51 | 52 | //Soln : Using Disjoint Set union 53 | #include 54 | using namespace std; 55 | #define ll long long int 56 | #define endl "\n" 57 | #define FASTIO ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 58 | #define mod 1000000007 59 | #define gcd __gcd 60 | 61 | class dsu { 62 | vectorparent; 63 | public: 64 | void init(int n) { 65 | parent.resize(n); 66 | iota(parent.begin(), parent.end(), 0); 67 | } 68 | int get(int x) { 69 | return (x == parent[x] ? x : parent[x] = get(parent[x])); 70 | } 71 | void unite(int x, int y) { 72 | x = get(x); 73 | y = get(y); 74 | if (x != y) { 75 | parent[x] = max(parent[x], parent[y]); 76 | parent[y] = max(parent[x], parent[y]); 77 | } 78 | } 79 | }; 80 | 81 | int32_t main() { 82 | int n, q; 83 | cin >> n >> q; 84 | int l[q], r[q], c[q]; 85 | for (int i = 0; i < q; i++) 86 | cin >> l[i] >> r[i] >> c[i]; 87 | dsu G; 88 | G.init(n + 2); 89 | int color[n + 2] = {}; 90 | for (int i = q - 1; i >= 0; i--) { 91 | //rightmost non-coloured index 92 | int index = G.get(l[i]); 93 | while (index <= r[i]) { 94 | color[index] = c[i]; 95 | G.unite(index, index + 1); 96 | index = G.get(index); 97 | } 98 | } 99 | for (int i = 1; i <= n; i++) 100 | cout << color[i] << endl; 101 | } 102 | -------------------------------------------------------------------------------- /Graph/Connected_Component_Using_DFS_Graph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | class Graph{ 6 | map>l; 7 | public: 8 | void addEdge(int x,int y){ 9 | l[x].push_back(y); 10 | l[y].push_back(x); 11 | } 12 | 13 | void dfs_helper(T source,map&visited){ 14 | //Recursive function that will traverse the Graph 15 | cout<visited; 26 | //Mark all the node that is not visited in the beginning. 27 | for(auto p:l){ 28 | T node=p.first; 29 | visited[node]=false; 30 | } 31 | //Iterate over all the vertices and initiate a dfs Call 32 | int count=1; 33 | for(auto p:l){ 34 | T node=p.first; 35 | if(!visited[node]){ 36 | cout<<"Component "<"; 37 | dfs_helper(node,visited); 38 | count++; 39 | cout<g; 49 | g.addEdge(0,1); 50 | g.addEdge(1,2); 51 | g.addEdge(2,3); 52 | g.addEdge(0,3); 53 | g.addEdge(0,4); 54 | g.addEdge(5,6); 55 | g.addEdge(6,7); 56 | g.addEdge(8,8); 57 | 58 | g.dfs(); 59 | 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /Graph/Cycle_Detection_in_Directed_Graph_using_DFS.cpp: -------------------------------------------------------------------------------- 1 | //Cycle Detection in a Directed Graph using DFS Approach 2 | //If a graph has a back edge, then it contains a cycle. Back edge is a node to its ancestor from the same path. 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | class Graph{ 9 | 10 | list*l; 11 | int V; 12 | public: 13 | Graph(int V){ 14 | this->V=V; 15 | l=new list[V]; 16 | } 17 | void addEdge(int x,int y){ 18 | //Directed Graph 19 | l[x].push_back(y); 20 | } 21 | 22 | bool cycle_Helper(int node,bool *visited,bool *stack){ 23 | //When you visit a node 24 | visited[node]=true; 25 | stack[node]=true; 26 | 27 | for(int neighbour:l[node]){ 28 | //Two Cases 29 | if(stack[neighbour]==true) 30 | return true; 31 | 32 | else if(visited[neighbour]==false){ 33 | bool cycle_mila=cycle_Helper(neighbour,visited,stack); 34 | if(cycle_mila==true) 35 | return true; 36 | } 37 | } 38 | 39 | //Leave a node 40 | stack[node]=false; 41 | return false; 42 | } 43 | 44 | 45 | //Checks for cycle in Directed Graph 46 | bool contains_Cycle(){ 47 | bool *visited=new bool[V]; 48 | bool *stack=new bool[V]; 49 | 50 | for(int i=0;i 12 | using namespace std; 13 | 14 | class disjointSetUnion{ 15 | public: 16 | vectorparent; 17 | void Initialize(int n){ 18 | parent.clear(); 19 | parent.resize(n); 20 | iota(parent.begin(),parent.end(),0); 21 | } 22 | int get_SuperParent(int x){ 23 | return (x==parent[x]?x:(parent[x]=get_SuperParent(parent[x]))); 24 | } 25 | void unite(int x,int y){ 26 | x=get_SuperParent(x); 27 | y=get_SuperParent(y); 28 | if(x!=y) 29 | parent[x]=y; 30 | } 31 | }; 32 | 33 | 34 | void detectCycle(){ 35 | bool cycle=false; 36 | int n,m; 37 | cin>>n>>m;// n number of nodes and m pairs 38 | disjointSetUnion G; 39 | G.Initialize(n);//0 --> n-1 40 | for(int i=0;i>x>>y; 43 | x--;//0 based indexing 44 | y--;//0 based indexing 45 | if(G.get_SuperParent(x)!=G.get_SuperParent(y)){ 46 | //Different connected components 47 | G.unite(x,y); 48 | } 49 | else{ 50 | // Same components 51 | //There was a path from x to y, so there is a cycle. 52 | cycle=true; 53 | } 54 | } 55 | if(cycle) 56 | cout<<"Graph contains a cycle"< 6 | using namespace std; 7 | 8 | 9 | class Graph{ 10 | 11 | list*l; 12 | int V; 13 | public: 14 | Graph(int V){ 15 | this->V=V; 16 | l=new list[V]; 17 | } 18 | void addEdge(int x,int y){ 19 | //Undirected Graph 20 | l[x].push_back(y); 21 | l[y].push_back(x); 22 | } 23 | 24 | bool cycle_Helper(int node,bool *visited,int parent){ 25 | visited[node]=true; 26 | for(auto neighbour:l[node]){ 27 | //Two cases 28 | if(!visited[neighbour]){ 29 | //Go and recursively visits its neighbour 30 | bool cycle_mila=cycle_Helper(neighbour,visited,node); 31 | if(cycle_mila) 32 | return true; 33 | } 34 | //This is the case when neighbour is visited but neighbour should not be equal to parent. 35 | else if(neighbour!=parent) 36 | return true; 37 | } 38 | return false; 39 | } 40 | 41 | 42 | //Checks for cycle in Undirected Graph 43 | bool contains_Cycle(){ 44 | bool *visited=new bool[V]; 45 | 46 | for(int i=0;i 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<gr[N]; 56 | int dp[N], vis[N], depth[N]; 57 | //dp[i] --> min(min(dp[child]),min(backedge)) 58 | 59 | void dfs(int cur, int p = 0, int dep = 0) { 60 | vis[cur] = 1; 61 | dp[cur] = dep; 62 | depth[cur] = dep; 63 | for (auto x : gr[cur]) { 64 | if (vis[x] == 0) { 65 | dfs(x, cur, dep + 1); 66 | dp[cur] = min(dp[cur], dp[x]); 67 | } 68 | else if (x != p) { 69 | //Backedge or cycle 70 | dp[cur] = min(dp[cur], depth[x]); 71 | } 72 | } 73 | } 74 | 75 | int32_t main() { 76 | fastio; 77 | int n, m; 78 | cin >> n >> m; 79 | for (int i = 0; i < m; i++) { 80 | int x, y; 81 | cin >> x >> y; 82 | gr[x].pb(y); 83 | gr[y].pb(x); 84 | } 85 | //root is 1 86 | dfs(1); 87 | for (int i = 1; i <= n; i++) cout << i << " " << dp[i] << endl; 88 | } 89 | -------------------------------------------------------------------------------- /Graph/DP_on_tree__Smallest_node_in_a_subtree_of_x.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<gr[N]; 21 | int dp[N];//dp[i] is min(i and min(all the child of i)) 22 | 23 | void dfs(int cur, int p = 0) { 24 | dp[cur] = cur; 25 | for (auto x : gr[cur]) { 26 | if (x != p) { 27 | dfs(x, cur); 28 | dp[cur] = min(dp[cur], dp[x]); 29 | } 30 | } 31 | } 32 | 33 | int32_t main() { 34 | fastio; 35 | int n; 36 | cin >> n; 37 | for (int i = 1; i < n; i++) { 38 | int x, y; 39 | cin >> x >> y; 40 | gr[x].pb(y); 41 | gr[y].pb(x); 42 | } 43 | //root is 1 44 | dfs(1); 45 | for (int i = 1; i <= n; i++) cout << i << " " << dp[i] << endl; 46 | } 47 | -------------------------------------------------------------------------------- /Graph/Depth_First_Search_DFS.cpp: -------------------------------------------------------------------------------- 1 | //Depth First Search 2 | 3 | #include 4 | using namespace std; 5 | 6 | template 7 | class Graph{ 8 | map>l; 9 | public: 10 | void addEdge(int x,int y){ 11 | l[x].push_back(y); 12 | l[y].push_back(x); 13 | } 14 | 15 | void dfs_helper(T source,map&visited){ 16 | //Recursive function that will traverse the Graph 17 | cout<visited; 28 | //Mark all the node that is not visited in the beginning. 29 | for(auto p:l){ 30 | T node=p.first; 31 | visited[node]=false; 32 | } 33 | //Call the dfs dfs_helper function 34 | dfs_helper(source,visited); 35 | cout<g; 43 | g.addEdge(0,1); 44 | g.addEdge(1,2); 45 | g.addEdge(2,3); 46 | g.addEdge(3,4); 47 | g.addEdge(4,5); 48 | g.addEdge(3,0); 49 | 50 | g.dfs(0); 51 | 52 | 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Graph/Dijkstras_Algorithm_Shortest_Path_on_Weighted_Graph.cpp: -------------------------------------------------------------------------------- 1 | //Dijkstra's Algorithm : It is also known as the single source shortest path Algorithm. 2 | //It is an algorithm for the weighted graph with no negative weight cycle. 3 | 4 | #include 5 | using namespace std; 6 | 7 | template 8 | class Graph{ 9 | unordered_map> > m; // (Source , (Destination,Distance) ) 10 | 11 | public: 12 | void addEdge(T u,T v,int distance,bool bidirectional=true){ 13 | m[u].push_back(make_pair(v,distance)); 14 | //If the edge is bidirectional 15 | if(bidirectional) 16 | m[v].push_back(make_pair(u,distance)); 17 | } 18 | 19 | void printAdj(){ 20 | //Iterate over all the key value value pairs in the map 21 | // j refers to key and the value as well 22 | for(auto j:m){ 23 | cout<"; 24 | //Iterate over the list of cities 25 | for(auto l:j.second) 26 | cout<<"("<distance; 32 | //Set all distance to infinity 33 | for(auto j:m) 34 | distance[j.first]=INT_MAX; 35 | 36 | //Make a set to find out the node with minimum distance 37 | set>s; //Set sorts the element according to the first element , thats why i have kept int as the first parameter 38 | distance[sourceNode]=0; 39 | s.insert(make_pair(0,sourceNode)); 40 | while(!s.empty()){ 41 | //Find the pair at the front 42 | auto p=*(s.begin()); 43 | T node=p.second; 44 | int nodeDistance=p.first; 45 | s.erase(s.begin()); 46 | 47 | //Iterate over the neighbour/children of current node 48 | for(auto neighbour:m[node]){ 49 | if(nodeDistance+neighbour.second < distance[neighbour.first]){ 50 | //In the set , Updation of a particle node is not possible 51 | //So, we have to remove the old pair , and insert the new pair to stimulate Updation 52 | auto f=s.find(make_pair(distance[neighbour.first],neighbour.first)); 53 | if(f!=s.end()) 54 | s.erase(f); 55 | //Insert the new pair 56 | distance[neighbour.first]=nodeDistance+neighbour.second; 57 | s.insert(make_pair(distance[neighbour.first],neighbour.first)); 58 | } 59 | } 60 | } 61 | //Print Distances to all other nodes 62 | for(auto d:distance) 63 | cout<g; 71 | g.addEdge(1,2,1); 72 | g.addEdge(1,3,4); 73 | g.addEdge(2,3,1); 74 | g.addEdge(3,4,2); 75 | g.addEdge(1,4,7); 76 | 77 | g.printAdj(); 78 | g.DijkstraSSSP(1); 79 | 80 | GraphIndia; 81 | India.addEdge("Amritsar","Delhi",1); 82 | India.addEdge("Amritsar","Jaipur",4); 83 | India.addEdge("Jaipur","Delhi",2); 84 | India.addEdge("Jaipur","Mumbai",8); 85 | India.addEdge("Bhopal","Agra",2); 86 | India.addEdge("Mumbai","Bhopal",3); 87 | India.addEdge("Agra","Delhi",1); 88 | 89 | India.DijkstraSSSP("Amritsar"); 90 | } 91 | 92 | // https://practice.geeksforgeeks.org/problems/implementing-dijkstra-set-1-adjacency-matrix/1/?track=SPC-Graph&batchId=155 93 | 94 | // vector dijkstra(vector> g, int src, int V) 95 | // { 96 | // vectordistance(V,INT_MAX);//(node,distance) 97 | // distance[src]=0; 98 | // 99 | // set>s;//(distance,node) 100 | // s.insert({0,src}); 101 | // 102 | // while(!s.empty()){ 103 | // auto p=*(s.begin()); 104 | // int nodeDistance=p.first; 105 | // int node=p.second; 106 | // s.erase(p); 107 | // for(int i=0;i 36 | using namespace std; 37 | 38 | class disjointSetUnion{ 39 | public: 40 | vectorparent,sizeOfSuperParent; 41 | int total_Unconnected_Component; 42 | //Initialize 43 | void Initialize(int n){ 44 | parent.resize(n); 45 | sizeOfSuperParent.resize(n); 46 | for(int i=0;i>n>>m; 78 | G.Initialize(n); 79 | for(int i=0;i>x>>y; 82 | G.unite(x,y); 83 | } 84 | int ans=0; 85 | //All elements are in there connected components 86 | for(int i=0;i 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define FASTIO ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<gr[N]; 20 | int tin[N], tout[N], timer; 21 | 22 | void euler_tour_1(int cur, int par) { 23 | cout << cur << " "; 24 | for (auto x : gr[cur]) { 25 | if (x != par) { 26 | euler_tour_1(x, cur); 27 | cout << cur << " "; 28 | } 29 | } 30 | } 31 | 32 | void euler_tour_2(int cur, int par) { 33 | cout << cur << " "; 34 | //tin[cur]=timer++; 35 | for (auto x : gr[cur]) { 36 | if (x != par) 37 | euler_tour_2(x, cur); 38 | } 39 | //tout[cur]=timer++; 40 | cout << cur << " "; 41 | } 42 | 43 | void euler_tour_3(int cur, int par) { 44 | //cout << cur << " "; 45 | //Enter a node 46 | tin[cur] = ++timer; 47 | for (auto x : gr[cur]) { 48 | if (x != par) 49 | euler_tour_3(x, cur); 50 | } 51 | //Leave a node 52 | tout[cur] = timer; 53 | } 54 | 55 | //Whether x is ancestor of y or not 56 | bool is_ancestor(int x, int y) { 57 | return tin[x] <= tin[y] && tout[y] <= tout[x]; 58 | } 59 | 60 | int32_t main() { 61 | FASTIO; 62 | int n; 63 | cin >> n; 64 | for (int i = 0; i < n - 1; i++) { 65 | int x, y; 66 | cin >> x >> y; 67 | gr[x].pb(y); 68 | gr[y].pb(x); 69 | } 70 | timer = 0; 71 | // euler_tour_1(1, 0); 72 | // cout << endl; 73 | // euler_tour_2(1, 0); 74 | // cout << endl; 75 | euler_tour_3(1, 0); 76 | for (int i = 1; i <= n; i++) 77 | cout << i << " " << tin[i] << " " << tout[i] << endl; 78 | if (is_ancestor(2, 6)) 79 | cout << "2 is a ancestor of 6"; 80 | else 81 | cout << "2 is not a ancestor of 6"; 82 | cout << endl; 83 | } 84 | -------------------------------------------------------------------------------- /Graph/Floyd_Warshall_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | Floyd Warshall Algorithm 2 | <------------------------------------------------------------------------------> 3 | --> Used to find shortest path between all pairs of vertices.(in directed as well 4 | as undirected graphs). 5 | --> Will work even if negative edges are present. 6 | --> Will also be able to detect negative cycles. 7 | --> Time Compleity :- O(V^3). 8 | --> Space Compleity :- O(V^2). 9 | 10 | 11 | vector> floyd_warshall(int n, vector>> &adj) { 12 | //Matrix of order (n+1)*(n+1) 13 | vector> dist(n + 1, vector(n + 1, 2e9)); 14 | for (int i = 1; i <= n; i++) { 15 | dist[i][i] = 0; 16 | for (pair x : adj[i]) { 17 | int nbr = x.first; 18 | int wt = x.second; 19 | dist[i][nb] = w; 20 | } 21 | } 22 | for (int k = 1; k <= n; k++) { 23 | //kth phase 24 | for (int i = 1; i <= n; i++) 25 | for (int j = 1; j <= n; j++) 26 | dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); 27 | } 28 | return dist; 29 | } 30 | -------------------------------------------------------------------------------- /Graph/Graph_Adjacency_List_Implementation_for_Generic_Data.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //Weighted Graph 5 | class Graph{ 6 | //Adjacency List 7 | unordered_map> >l; 8 | public: 9 | void addEdge(string x,string y,bool bidirectional,int weight){ 10 | l[x].push_back(make_pair(y,weight)); 11 | 12 | if(bidirectional) 13 | l[y].push_back(make_pair(x,weight)); 14 | } 15 | 16 | void printAdjList(){ 17 | //Iterate over all the key in the map 18 | for(auto x:l){ 19 | string city=x.first; 20 | list>neighbours=x.second; 21 | //y.first is the destination and y.second is the distance from the city 22 | for(auto y:neighbours) 23 | cout<"< 2 | using namespace std; 3 | 4 | class Graph{ 5 | int V; 6 | //Array of List 7 | list *l; 8 | public: 9 | Graph(int V){ 10 | this->V=V; 11 | l=new list[V]; 12 | } 13 | void addEdge(int x,int y){ 14 | l[x].push_back(y); 15 | l[y].push_back(x); 16 | } 17 | void printAdjList(){ 18 | //Iterate over all the vertices 19 | for(int i=0;i 3 | // Nowadays, people have many ways to save money on accommodation when they are on vacation. One of these ways is exchanging houses with other people. 4 | // 5 | // Here is a group of N people who want to travel around the world. They live in different cities, so they can travel to some other people's city and use someone's house temporary. Now they want to make a plan that choose a destination for each person. There are two rules should be satisfied: 6 | // 7 | // All the people should go to one of the other people's city. 8 | // Two of them never go to the same city, because they are not willing to share a house. 9 | // They want to maximize the sum of all people's travel distance. The travel distance of a person is the distance between the city he lives in and the city he travels to. These N cities have N-1 highways connecting them. The travelers always choose the shortest path when traveling. 10 | // 11 | // Given the highways' information, it is your job to find the best plan, that maximum the total travel distance of all people. 12 | // 13 | // Input 14 | // The first line of input contains one integer T (1 ≤ T ≤ 10), indicating the number of test cases. 15 | // 16 | // Each test case contains several lines. The first line contains an integer N (2 ≤ N ≤ 105), representing the number of cities. Then the following N-1 lines each contains three integers X, Y, Z (1 ≤ X, Y ≤ N, 1 ≤ Z ≤ 106), means that there is a highway between city X and city Y, and length of that highway. 17 | // 18 | // You can assume all the cities are connected and the highways are bi-directional. 19 | // 20 | // Output 21 | // For each test case in the input, print one line: "Case #X: Y", where X is the test case number (starting with 1) and Y represents the largest total travel distance of all people. 22 | // 23 | // Example 24 | // Input: 25 | // 2 26 | // 4 27 | // 1 2 3 28 | // 2 3 2 29 | // 4 3 2 30 | // 6 31 | // 1 2 3 32 | // 2 3 4 33 | // 2 4 1 34 | // 4 5 8 35 | // 5 6 5 36 | // 37 | // Output: 38 | // Case #1: 18 39 | // Case #2: 62 40 | #include 41 | using namespace std; 42 | #define int long long int 43 | #define endl "\n" 44 | #define fast ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 45 | #define mod 1000000007 46 | 47 | 48 | class Graph { 49 | int V; 50 | list>*l; 51 | public: 52 | Graph(int v) { 53 | V = v; 54 | l = new list>[V]; 55 | } 56 | void addEdge(int u, int v, int cost) { 57 | l[u].push_back({v, cost}); 58 | l[v].push_back({u, cost}); 59 | } 60 | 61 | int dfsHelper(int node, bool *visited, int *count, int &ans) { 62 | //mark the node as visited 63 | visited[node] = 1; 64 | count[node] = 1; 65 | for (auto nbr_cost_pair : l[node]) { 66 | int nbr = nbr_cost_pair.first; 67 | int cost = nbr_cost_pair.second; 68 | if (!visited[nbr]) { 69 | count[node] += dfsHelper(nbr, visited, count, ans); 70 | int nx = count[nbr]; 71 | int ny = V - nx; 72 | ans += 2 * min(nx, ny) * cost; 73 | } 74 | } 75 | //Just before leaving the node parent 76 | return count[node]; 77 | } 78 | 79 | int dfs() { 80 | bool *visited = new bool[V] {}; 81 | int *count = new int [V] {}; 82 | int ans{}; 83 | dfsHelper(0, visited, count, ans); 84 | 85 | return ans; 86 | } 87 | }; 88 | 89 | int32_t main() { 90 | int t; 91 | cin >> t; 92 | for(int x=1;x<=t;x++) { 93 | int V; 94 | cin >> V; 95 | Graph g(V); 96 | for (int i = 0; i < V-1; i++) { 97 | int u, v, cost; 98 | cin >> u >> v >> cost; 99 | u--; 100 | v--; 101 | g.addEdge(u, v, cost); 102 | } 103 | cout <<"Case #"< 3 | // Strongly Connectd Graph : This term is strictly used for directed Graph. 4 | 5 | // Input : 6 | // 6 7 7 | // 1 2 8 | // 2 3 9 | // 3 1 10 | // 3 4 11 | // 4 5 12 | // 5 6 13 | // 6 4 14 | // 15 | // Output : 16 | // 1 ---> 2 17 | // 2 ---> 2 18 | // 3 ---> 2 19 | // 4 ---> 3 20 | // 5 ---> 3 21 | // 6 ---> 3 22 | 23 | 24 | #include 25 | using namespace std; 26 | #define ll long long int 27 | #define endl "\n" 28 | #define fast ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 29 | #define mod 1000000007 30 | 31 | 32 | //Kosaraju's Algorithm : O(n) time complexity 33 | const int N = 100005, M = 22; 34 | vectorGraph[N], reverseGraph[N]; 35 | vectororder;//If there is a path from x to y, then y should come before x in the order vector 36 | int visited[N], component[N]; 37 | 38 | void dfs(int current) { 39 | visited[current] = 1; 40 | for (auto x : Graph[current]) { 41 | if (!visited[x]) dfs(x); 42 | } 43 | order.push_back(current); 44 | } 45 | 46 | void dfs_reverse(int current, int color) { 47 | visited[current] = 1; 48 | component[current] = color; 49 | for (auto x : reverseGraph[current]) { 50 | if (!visited[x]) 51 | dfs_reverse(x, color); 52 | } 53 | } 54 | 55 | void solve() { 56 | int n, m; 57 | cin >> n >> m; 58 | for (int i = 0; i < m; i++) { 59 | int x, y; 60 | cin >> x >> y; 61 | Graph[x].push_back(y); 62 | reverseGraph[y].push_back(x); 63 | } 64 | // memset(visited, 0, sizeof(visited)); 65 | for (int i = 1; i <= n; i++) { 66 | if (!visited[i]) dfs(i); 67 | } 68 | memset(visited, 0, sizeof(visited)); 69 | int color = 1; 70 | for (int i = n; i >= 1; i--) { 71 | if (!visited[order[i]]) { 72 | dfs_reverse(order[i], color); 73 | color++; 74 | } 75 | } 76 | for (int i = 1; i <= n; i++) 77 | cout << i << " ---> " << component[i] << endl; 78 | } 79 | 80 | int32_t main() { 81 | fast; 82 | solve(); 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /Graph/Kruskals_Algorithm_for_minimum_spanning tree.cpp: -------------------------------------------------------------------------------- 1 | //Kruskal's Algorithm for finding the minimum spanning tree. 2 | //A minimum spanning tree (MST) or minimum weight spanning tree is a subset of 3 | //the edges of a connected, edge-weighted undirected graph that connects all 4 | //the vertices together, without any cycles and with the minimum possible total 5 | //edge weight. 6 | //Pre-requisite :- Disjoint set Union 7 | 8 | //Step 1.Sort all the edges according to the increasing order of weight. 9 | //Step 2.If I add that esges in the graph and resulting graph has no cycle.Then that edge is a worthy edge. 10 | 11 | // Input 12 | // 9 15 13 | // 1 2 10 14 | // 2 3 9 15 | // 1 3 12 16 | // 3 5 3 17 | // 5 4 7 18 | // 2 4 8 19 | // 3 6 1 20 | // 4 6 10 21 | // 5 6 3 22 | // 7 4 8 23 | // 7 8 9 24 | // 7 9 2 25 | // 8 6 6 26 | // 9 7 2 27 | // 9 8 11 28 | 29 | // Output : 43 30 | 31 | #include 32 | using namespace std; 33 | 34 | class disjointSetUnion { 35 | public: 36 | vectorparent; 37 | void Initialize(int n) { 38 | parent.clear(); 39 | parent.resize(n); 40 | iota(parent.begin(), parent.end(), 0); 41 | } 42 | int get_SuperParent(int x) { 43 | return (x == parent[x] ? x : (parent[x] = get_SuperParent(parent[x]))); 44 | } 45 | void unite(int x, int y) { 46 | x = get_SuperParent(x); 47 | y = get_SuperParent(y); 48 | if (x != y) 49 | parent[x] = y; 50 | } 51 | }; 52 | 53 | 54 | void KrushkalsAlgorithm() { 55 | bool cycle = false; 56 | int n, m; 57 | cin >> n >> m; // n number of nodes and m pairs 58 | vector>edges(m); 59 | for (int i = 0; i < m; i++) { 60 | int x, y, w; //Edges x-->y having weight w 61 | cin >> x >> y >> w;//1 based Indexing. 62 | edges[i] = {w, x, y}; 63 | } 64 | sort(edges.begin(), edges.end()); 65 | disjointSetUnion G; 66 | G.Initialize(n + 1); // Nodes from 1--->n. 67 | int total_weight_of_the_minimum_spanning_tree = 0; 68 | for (int i = 0; i < m; i++) { 69 | int x = edges[i][1]; 70 | int y = edges[i][2]; 71 | int w = edges[i][0]; 72 | //cout << w << " " << x << " " << y << endl; 73 | if (G.get_SuperParent(x) != G.get_SuperParent(y)) { 74 | //Can take this edge because it is not creating a cycle 75 | G.unite(x, y); 76 | cout << w << " " << x << " " << y << endl; 77 | //If you want to make a unidirected graph of minimum spanning tree 78 | //ad[x].push_back(y); ad[y],push_back(x); 79 | //Include all the edge which doesnot result in a cycle. 80 | total_weight_of_the_minimum_spanning_tree += w; 81 | } 82 | } 83 | cout << "Total weight of the minimum spanning tree is " << total_weight_of_the_minimum_spanning_tree << endl; 84 | } 85 | 86 | int main() { 87 | ios_base::sync_with_stdio(false); 88 | cin.tie(NULL); 89 | cout.tie(NULL); 90 | 91 | KrushkalsAlgorithm(); 92 | } 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | // #include 126 | // using namespace std; 127 | // class disjointSetUnion { 128 | // public: 129 | // int parent[100001]; 130 | // void Initialize(int n) { 131 | // 132 | // for (int i = 0; i < n; i++) 133 | // parent[i] = i; 134 | // } 135 | // 136 | // int get_SuperParent(int x) { 137 | // return (x == parent[x] ? x : (parent[x] = get_SuperParent(parent[x]))); 138 | // } 139 | // 140 | // void unite(int x, int y) { 141 | // x = get_SuperParent(x); 142 | // y = get_SuperParent(y); 143 | // if (x != y) 144 | // parent[x] = y; 145 | // } 146 | // }; 147 | // 148 | // long long int kruskalDSU(vector> adj[], int n, int m) { 149 | // pair > v[2 * m]; 150 | // int t = 0; 151 | // 152 | // for (int i = 1; i <= n; i++) { 153 | // for (int j = 0; j < adj[i].size(); j++) { 154 | // v[t++] = make_pair(adj[i][j].second, make_pair(i, adj[i][j].first)); 155 | // } 156 | // } 157 | // 158 | // sort(v, v + t); 159 | // disjointSetUnion G; 160 | // G.Initialize(n + 1); 161 | // ll ans = 0; 162 | // for (int i = 0; i < 2 * m; i++) { 163 | // int x = v[i].second.first; 164 | // int y = v[i].second.second; 165 | // long long w = v[i].first; 166 | // if (G.get_SuperParent(x) != G.get_SuperParent(y)) { 167 | // G.unite(x, y); 168 | // ans += w; 169 | // } 170 | // } 171 | // return ans; 172 | // } 173 | // int main() { 174 | // ios_base::sync_with_stdio(false); 175 | // cin.tie(NULL); 176 | // cout.tie(NULL); 177 | // int t; 178 | // cin >> t; 179 | // vector>adj[100009]; 180 | // while (t--) { 181 | // int n, m; 182 | // cin >> n >> m; 183 | // int u, v; 184 | // ll w; 185 | // for (int i = 0; i < m; i++) { 186 | // cin >> u >> v >> w; 187 | // adj[u].push_back(make_pair(v, w)); 188 | // adj[v].push_back(make_pair(u, w)); 189 | // } 190 | // cout << kruskalDSU(adj, n, m) << endl; 191 | // for (int i = 0; i < m; i++) 192 | // adj[i].clear(); 193 | // } 194 | // return 0; 195 | // } 196 | -------------------------------------------------------------------------------- /Graph/LCA/Brute: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Graph/LCA/Brute -------------------------------------------------------------------------------- /Graph/LCA/distance_between_x_and_y: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Graph/LCA/distance_between_x_and_y -------------------------------------------------------------------------------- /Graph/LCA/distance_between_x_and_y.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<>gr[N]; 20 | int p[N][M];//Parent 21 | int d[N];//depth 22 | int dis[N];//Sum of weight of the path from root to i 23 | 24 | //O(n) 25 | void dfs(int cur, int par = 0) { 26 | for (auto x : gr[cur]) { 27 | if (x.F != par) { 28 | d[x.F] = d[cur] + 1; 29 | dis[x.F] = dis[cur] + x.S; 30 | dfs(x.F, cur); 31 | } 32 | } 33 | } 34 | 35 | //It is just like a dfs 36 | void cal_sparse_table(int cur, int par = 0) { 37 | p[cur][0] = par; 38 | for (int j = 1; j < M; j++) 39 | p[cur][j] = p[p[cur][j - 1]][j - 1]; 40 | 41 | for (auto x : gr[cur]) { 42 | if (x.F != par) 43 | cal_sparse_table(x.F, cur); 44 | } 45 | } 46 | 47 | //Lets find LCA using depth using Binary lifting 48 | //Time complexity : O(logn)==O(m) 49 | int lca_sparse(int u, int v) { 50 | if (u == v) return u; 51 | 52 | if (d[u] < d[v]) swap(u, v); 53 | int diff = d[u] - d[v]; 54 | for (int i = M - 1; i >= 0; i--) { 55 | if ((diff >> i) & 1) u = p[u][i]; 56 | } 57 | //After this u and v are on the same depth 58 | //If v was ancestor of u 59 | if (u == v) return u; 60 | for (int i = M - 1; i >= 0; i--) { 61 | if (p[u][i] != p[v][i]) { 62 | u = p[u][i]; 63 | v = p[v][i]; 64 | } 65 | } 66 | 67 | //I am standing on different nodes and both these u and v are child of lca 68 | return p[u][0]; 69 | } 70 | 71 | //Distnace between two nodes : O(M) 72 | int distance(int x, int y) { 73 | //dis(x,y)=dis(x)+dis(y)-2*dis(lca) 74 | int lca = lca_sparse(x, y); 75 | return dis[x] + dis[y] - 2 * dis[lca]; 76 | } 77 | 78 | int32_t main() { 79 | fastio; 80 | int n; 81 | cin >> n; 82 | for (int i = 1; i < n; i++) { 83 | int x, y, w; 84 | cin >> x >> y >> w; 85 | gr[x].pb({y, w}); 86 | gr[y].pb({x, w}); 87 | } 88 | //Root as 1 89 | dfs(1); 90 | cal_sparse_table(1); 91 | cout << distance(4, 6) << endl; 92 | cout << distance(1, 7) << endl; 93 | } 94 | -------------------------------------------------------------------------------- /Graph/LCA/lca_brute.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<gr[N]; 20 | int p[N];//Parent 21 | int d[N];//depth 22 | 23 | 24 | void dfs(int cur, int par = 0) { 25 | p[cur] = par; 26 | for (auto x : gr[cur]) { 27 | if (x != par) { 28 | d[x] = d[cur] + 1; 29 | dfs(x, cur); 30 | } 31 | } 32 | 33 | } 34 | 35 | //Time Complexity : O(n) 36 | int lca_brute(int u, int v) { 37 | if (u == v) return u; 38 | 39 | //Lets take u to be at more depth 40 | if (d[u] < d[v]) swap(u, v); 41 | 42 | while (d[u] > d[v]) u = p[u]; 43 | //Now they are at the same level 44 | while (u != v) { 45 | u = p[u]; 46 | v = p[v]; 47 | } 48 | return u; 49 | } 50 | 51 | 52 | 53 | int32_t main() { 54 | fastio; 55 | int n; 56 | cin >> n; 57 | for (int i = 1; i < n; i++) { 58 | int x, y; 59 | cin >> x >> y; 60 | gr[x].pb(y); 61 | gr[y].pb(x); 62 | } 63 | //Root as 1 64 | dfs(1); 65 | for (int i = 1; i < n; i++) cout << i << " " << d[i] << " " << p[i] << endl; 66 | cout << lca_brute(18, 16) << endl; 67 | cout << lca_brute(9, 2) << endl; 68 | 69 | } 70 | -------------------------------------------------------------------------------- /Graph/LCA/lca_sparse_table: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Graph/LCA/lca_sparse_table -------------------------------------------------------------------------------- /Graph/LCA/lca_sparse_table.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<gr[N]; 20 | int p[N][M];//Parent 21 | int d[N];//depth 22 | 23 | //O(n) 24 | void dfs(int cur, int par = 0) { 25 | for (auto x : gr[cur]) { 26 | if (x != par) { 27 | d[x] = d[cur] + 1; 28 | dfs(x, cur); 29 | } 30 | } 31 | } 32 | 33 | //It is just like a dfs 34 | void cal_sparse_table(int cur, int par = 0) { 35 | p[cur][0] = par; 36 | for (int j = 1; j < M; j++) 37 | p[cur][j] = p[p[cur][j - 1]][j - 1]; 38 | 39 | for (auto x : gr[cur]) { 40 | if (x != par) 41 | cal_sparse_table(x, cur); 42 | } 43 | } 44 | 45 | //Lets find LCA using depth using Binary lifting 46 | //Time complexity : O(logn)==O(m) 47 | int lca_sparse(int u, int v) { 48 | if (u == v) return u; 49 | 50 | if (d[u] < d[v]) swap(u, v); 51 | int diff = d[u] - d[v]; 52 | for (int i = M - 1; i >= 0; i--) { 53 | if ((diff >> i) & 1) u = p[u][i]; 54 | } 55 | //After this u and v are on the same depth 56 | //If v was ancestor of u 57 | if (u == v) return u; 58 | for (int i = M - 1; i >= 0; i--) { 59 | if (p[u][i] != p[v][i]) { 60 | u = p[u][i]; 61 | v = p[v][i]; 62 | } 63 | } 64 | 65 | //I am standing on different nodes and both these u and v are child of lca 66 | return p[u][0]; 67 | } 68 | 69 | int32_t main() { 70 | fastio; 71 | int n; 72 | cin >> n; 73 | for (int i = 1; i < n; i++) { 74 | int x, y; 75 | cin >> x >> y; 76 | gr[x].pb(y); 77 | gr[y].pb(x); 78 | } 79 | //Root as 1 80 | dfs(1); 81 | cal_sparse_table(1); 82 | cout << lca_sparse(9, 15) << endl; 83 | cout << lca_sparse(18, 15) << endl; 84 | } 85 | -------------------------------------------------------------------------------- /Graph/LCA/lca_using_time: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Graph/LCA/lca_using_time -------------------------------------------------------------------------------- /Graph/LCA/lca_using_time.cpp: -------------------------------------------------------------------------------- 1 | // 19 2 | // 1 2 3 | // 2 4 4 | // 2 5 5 | // 5 6 6 | // 6 7 7 | // 6 8 8 | // 6 9 9 | // 1 3 10 | // 3 10 11 | // 10 17 12 | // 17 18 13 | // 17 19 14 | // 3 11 15 | // 11 12 16 | // 12 13 17 | // 12 14 18 | // 12 15 19 | // 15 16 20 | 21 | 22 | #include 23 | using namespace std; 24 | #define ll long long int 25 | #define endl "\n" 26 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 27 | #define mod 1000000007 28 | #define gcd __gcd 29 | #define inf INT_MAX 30 | #define minf INT_MIN 31 | #define pb push_back 32 | #define all(v) v.begin(),v.end() 33 | #define print(v) for(auto x:v) cout<gr[N]; 41 | int p[N][M];//Parent 42 | int d[N];//depth 43 | int tin[N], tout[N]; 44 | int timer; 45 | 46 | //O(n) 47 | void dfs(int cur, int par = 0) { 48 | tin[cur] = ++timer; 49 | for (auto x : gr[cur]) { 50 | if (x != par) { 51 | d[x] = d[cur] + 1; 52 | dfs(x, cur); 53 | } 54 | } 55 | tout[cur] = timer; 56 | } 57 | 58 | //It is just like a dfs 59 | void cal_sparse_table(int cur, int par = 0) { 60 | p[cur][0] = par; 61 | for (int j = 1; j < M; j++) 62 | p[cur][j] = p[p[cur][j - 1]][j - 1]; 63 | 64 | for (auto x : gr[cur]) { 65 | if (x != par) 66 | cal_sparse_table(x, cur); 67 | } 68 | } 69 | 70 | //Whether u is a ancestor of v or not 71 | bool is_ancestor(int u, int v) { 72 | return (tin[u] <= tin[v] && tout[u] >= tout[v]); 73 | } 74 | 75 | //LCA using time in and time out 76 | int lca_using_time(int u, int v) { 77 | if (is_ancestor(u, v)) return u; 78 | if (is_ancestor(v, u)) return v; 79 | for (int i = M - 1; i >= 0; i--) { 80 | //If p[u][i] is not a ancestor of v , then move to it 81 | if (!is_ancestor(p[u][i], v)) u = p[u][i]; 82 | } 83 | return p[u][0]; 84 | } 85 | 86 | int32_t main() { 87 | fastio; 88 | int n; 89 | cin >> n; 90 | for (int i = 1; i < n; i++) { 91 | int x, y; 92 | cin >> x >> y; 93 | gr[x].pb(y); 94 | gr[y].pb(x); 95 | } 96 | timer = 0; 97 | tin[0] = 0; tout[0] = n + 1;//Universal Parent 98 | //Root as 1 99 | dfs(1); 100 | cal_sparse_table(1); 101 | cout << lca_using_time(9, 15) << endl; 102 | cout << lca_using_time(18, 15) << endl; 103 | cout << lca_using_time(15, 15) << endl; 104 | cout << lca_using_time(11, 16) << endl; 105 | } 106 | -------------------------------------------------------------------------------- /Graph/Network_flow/Edmund_karp_algorithm_to_find_the_max_flow_in_graph: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Graph/Network_flow/Edmund_karp_algorithm_to_find_the_max_flow_in_graph -------------------------------------------------------------------------------- /Graph/Network_flow/Edmund_karp_algorithm_to_find_the_max_flow_in_graph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<q; 22 | visited[src] = 1; 23 | q.push(src); 24 | bool found_augmented_path = false; 25 | while (!q.empty()) { 26 | int u = q.front(); 27 | q.pop(); 28 | for (int v = 0; v < n; v++) { 29 | if (!visited[v] && res_capacity[u][v] > 0) { 30 | parent[v] = u; 31 | visited[v] = 1; 32 | q.push(v); 33 | if (v == sink) { 34 | found_augmented_path = true; 35 | break; 36 | } 37 | } 38 | } 39 | } 40 | 41 | return found_augmented_path; 42 | } 43 | 44 | void print_augmented_path(vector>augmented_path) { 45 | for (int i = 0; i < augmented_path.size(); i++) { 46 | for (int j = 0; j < augmented_path[i].size(); j++) cout << augmented_path[i][j] << " "; 47 | cout << endl; 48 | } 49 | } 50 | 51 | int max_flow(int **capacity, int src, int sink, int v) { 52 | int **residual_capacity = new int*[v]; 53 | for (int i = 0; i < v; i++) residual_capacity[i] = new int[v]; 54 | for (int i = 0; i < v; i++) { 55 | for (int j = 0; j < v; j++) 56 | residual_capacity[i][j] = capacity[i][j]; 57 | } 58 | int *parent = new int[1000]; 59 | vector>augmented_path; 60 | int maxflow = 0; 61 | while (bfs(residual_capacity, src, sink, v, parent)) { 62 | vectorcur_augmented_path; 63 | int flow = inf; 64 | int v = sink; 65 | while (v != src) { 66 | cur_augmented_path.pb(v); 67 | int u = parent[v]; 68 | if (flow > residual_capacity[u][v]) 69 | flow = residual_capacity[u][v]; 70 | v = u; 71 | } 72 | cur_augmented_path.pb(src); 73 | reverse(all(cur_augmented_path)); 74 | augmented_path.pb(cur_augmented_path); 75 | maxflow += flow; 76 | v = sink; 77 | while (v != src) { 78 | int u = parent[v]; 79 | residual_capacity[u][v] -= flow; 80 | residual_capacity[v][u] += flow; 81 | v = u; 82 | } 83 | } 84 | print_augmented_path(augmented_path); 85 | return maxflow; 86 | } 87 | 88 | int32_t main() { 89 | fastio; 90 | int v, e; 91 | cin >> v >> e; 92 | int **capacity = new int*[v]; 93 | for (int i = 0; i < v; i++) capacity[i] = new int[v]; 94 | for (int i = 0; i < e; i++) { 95 | int u, v, c; 96 | cin >> u >> v >> c; 97 | capacity[u][v] = c; 98 | } 99 | cout << max_flow(capacity, 0, 1, v); 100 | } 101 | -------------------------------------------------------------------------------- /Graph/Prims_Algorithm_for_finding_minimum_spanning_tree.cpp: -------------------------------------------------------------------------------- 1 | //Prim's Algorithm for finding the minimum spanning tree. 2 | //MST Vertex : Vertex is included in my MST. 3 | //MST Edge or Active Edge : It points from the MST vertex to the non MST Vertex. 4 | //MST Edge : Edge that is included in the MST. 5 | //It is an greedy Algorithm. 6 | 7 | // 1. Choose a Source Vertex(Any Vertex in Graph) 8 | // 2. Out of all the active edges, choose the one with smallest weight. 9 | // 3. Update the adjacency list. 10 | // 11 | // https://www.spoj.com/problems/MST/ 12 | // Find the minimum spanning tree of the graph. 13 | // 14 | // Input 15 | // On the first line there will be two integers N - the number of nodes and M - the number of edges. (1 <= N <= 10000), (1 <= M <= 100000) 16 | // M lines follow with three integers i j k on each line representing an edge between node i and j with weight k. The IDs of the nodes are between 1 and n inclusive. The weight of each edge will be <= 1000000. 17 | // 18 | // Output 19 | // Single number representing the total weight of the minimum spanning tree on this graph. There will be only one possible MST. 20 | // 21 | // Example 22 | // Input: 23 | // 4 5 24 | // 1 2 10 25 | // 2 3 15 26 | // 1 3 5 27 | // 4 2 2 28 | // 4 3 40 29 | // 30 | // Output: 31 | // 17 32 | 33 | #include 34 | using namespace std; 35 | #define ll long long int 36 | #define endl "\n" 37 | 38 | 39 | int main() { 40 | ios_base::sync_with_stdio(false); 41 | cin.tie(NULL); 42 | cout.tie(NULL); 43 | 44 | int n, m; 45 | cin >> n >> m; 46 | vector>graph[n + 1]; //1 based indexing 47 | //Visited means it is not an active edge and we will not consider it in MST. 48 | int visited[n + 1] = {0}; 49 | for (int i = 0; i < m; i++) { 50 | int x, y, w; 51 | cin >> x >> y >> w; 52 | graph[x].push_back({y, w}); 53 | graph[y].push_back({x, w}); 54 | } 55 | ll mst = 0; 56 | priority_queue, vector>, greater>>Q; 57 | Q.push({0, 1}); //(weight,vertex/node) 58 | while (!Q.empty()) { 59 | pairbest = Q.top(); 60 | Q.pop(); 61 | 62 | int weight = best.first; 63 | int to = best.second; 64 | 65 | if (visited[to]) continue; //If it not an active edge ,then we wont be considering it in our MST. 66 | mst += weight; 67 | visited[to] = 1; 68 | 69 | //"to" vertex is visited , so we will push all the active edge which is going through this "to" vertex. 70 | for (auto x : graph[to]) { 71 | //x.first is not visited 72 | if (visited[x.first] == 0) 73 | Q.push({x.second, x.first}); 74 | } 75 | } 76 | cout << mst << endl; 77 | 78 | 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /Graph/Shortest_Cycle_in_undirected_graph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int N = 100005, M = 22; 5 | vectorgraph[N]; 6 | 7 | void bfs(int src, int n, int &ans) { 8 | vectordist(n + 1, INT_MAX); 9 | queueQ; 10 | Q.push(src); 11 | dist[src] = 0; 12 | while (!Q.empty()) { 13 | int cur = Q.front(); 14 | Q.pop(); 15 | for (auto nbr : graph[cur]) { 16 | if (dist[nbr] == INT_MAX) { 17 | //Neighbour not visited. 18 | dist[nbr] = dist[cur] + 1; 19 | Q.push(nbr); 20 | } 21 | //Condition for backedge 22 | else if (dist[nbr] >= dist[cur]) { 23 | //Backedge is encountered 24 | ans = min(ans, dist[nbr] + dist[cur] + 1); 25 | } 26 | } 27 | } 28 | } 29 | 30 | void solve() { 31 | int n, m; 32 | cin >> n >> m; 33 | for (int i = 0; i < m; i++) { 34 | int x, y; 35 | cin >> x >> y; 36 | graph[x].push_back(y); 37 | graph[y].push_back(x); 38 | } 39 | int ans = n + 1; 40 | for (int i = 1; i <= n; i++) { 41 | bfs(i, n, ans); 42 | } 43 | if (ans == n + 1) { 44 | cout << "No cycle" << endl; 45 | } 46 | else { 47 | cout << "Shortest cycle is of length " << ans << endl; 48 | } 49 | } 50 | 51 | 52 | 53 | int main() { 54 | solve(); 55 | } 56 | -------------------------------------------------------------------------------- /Graph/Single_Source_Shortest_Path_SSSP.cpp: -------------------------------------------------------------------------------- 1 | //Distance calculated by bfs or level order traversal is the shortest 2 | //Unweighted Graph 3 | 4 | #include 5 | using namespace std; 6 | 7 | template 8 | class Graph{ 9 | map>l; 10 | public: 11 | void addEdge(int x,int y){ 12 | l[x].push_back(y); 13 | l[y].push_back(x); 14 | } 15 | void singleSourceShortestPath(T sourceNode){ 16 | mapdistance; 17 | queueq; 18 | // All other nodes will have INT_MAX distance 19 | for(auto node_pair:l){ 20 | T node=node_pair.first; 21 | distance[node]=INT_MAX; 22 | } 23 | q.push(sourceNode); 24 | distance[sourceNode]=0; 25 | while(!q.empty()){ 26 | T node=q.front(); 27 | q.pop(); 28 | for(int neighbour:l[node]){ 29 | if(distance[neighbour]==INT_MAX){ 30 | q.push(neighbour); 31 | //Mark that node as visited 32 | distance[neighbour]=distance[node]+1; 33 | } 34 | } 35 | } 36 | //Print the distance to every node 37 | for(auto node_pair:l){ 38 | T node=node_pair.first; 39 | int d=distance[node]; 40 | cout<<"Node "<g; 49 | g.addEdge(0,1); 50 | g.addEdge(1,2); 51 | g.addEdge(2,3); 52 | g.addEdge(3,0); 53 | g.addEdge(3,4); 54 | g.addEdge(4,5); 55 | 56 | g.singleSourceShortestPath(0); 57 | 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /Graph/Snakes_and_Ladder_BFS_SSSP_Problem.cpp: -------------------------------------------------------------------------------- 1 | //Distance calculated by bfs or level order traversal is the shortest 2 | //Unweighted Graph 3 | 4 | #include 5 | using namespace std; 6 | 7 | template 8 | class Graph{ 9 | map>l; 10 | public: 11 | //Directed Edges 12 | void addEdge(int x,int y){ 13 | l[x].push_back(y); 14 | } 15 | int singleSourceShortestPath(T sourceNode,T destination){ 16 | mapdistance; 17 | mapparent; 18 | queueq; 19 | // All other nodes will have INT_MAX distance 20 | for(auto node_pair:l){ 21 | T node=node_pair.first; 22 | distance[node]=INT_MAX; 23 | } 24 | q.push(sourceNode); 25 | distance[sourceNode]=0; 26 | parent[sourceNode]=sourceNode; 27 | while(!q.empty()){ 28 | T node=q.front(); 29 | q.pop(); 30 | for(int neighbour:l[node]){ 31 | if(distance[neighbour]==INT_MAX){ 32 | q.push(neighbour); 33 | parent[neighbour]=node; 34 | //Mark that node as visited 35 | distance[neighbour]=distance[node]+1; 36 | } 37 | } 38 | } 39 | //Destination to source 40 | T temp=destination; 41 | while(temp!=sourceNode){ 42 | cout<g; 73 | for(int i=0;i<=36;i++){ 74 | for(int dice=1;dice<=6;dice++){ 75 | int location=i+dice; 76 | location+=board[location]; 77 | if(location<=36) 78 | g.addEdge(i,location);//Directed Edges 79 | } 80 | } 81 | g.addEdge(36,36); 82 | 83 | int distance = g.singleSourceShortestPath(0,36); 84 | cout< 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<> n; 23 | int a[n]; 24 | for (int i = 0; i < n; i++) cin >> a[i]; 25 | int log[n + 1]; 26 | log[1] = 0; 27 | for (int i = 2; i <= n; i++) log[i] = log[i / 2] + 1; 28 | int k = log2(n); 29 | int st[n][k + 1]; 30 | for (int i = 0; i < n; i++) st[i][0] = a[i]; 31 | for (int j = 1; j <= k; j++) { 32 | for (int i = 0; i + (1 << j) <= n; i++) 33 | st[i][j] = min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]); 34 | } 35 | int q; 36 | cin >> q; 37 | while (q--) { 38 | int L, R; 39 | cin >> L >> R; 40 | int j = log[R - L + 1]; 41 | int minimum = min(st[L][j], st[R - (1 << j) + 1][j]); 42 | cout << minimum << endl; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Graph/Sparse_Table/Range_sum_queries.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<> n; 23 | int a[n]; 24 | for (int i = 0; i < n; i++) cin >> a[i]; 25 | int log[n + 1]; 26 | log[1] = 0; 27 | for (int i = 2; i <= n; i++) log[i] = log[i / 2] + 1; 28 | int k = log2(n); 29 | int st[n][k + 1]; 30 | for (int i = 0; i < n; i++) st[i][0] = a[i]; 31 | for (int j = 1; j <= k; j++) { 32 | for (int i = 0; i + (1 << j) <= n; i++) 33 | st[i][j] = st[i][j - 1] + st[i + (1 << (j - 1))][j - 1]; 34 | } 35 | int q; 36 | cin >> q; 37 | while (q--) { 38 | int L, R; 39 | cin >> L >> R; 40 | int sum = 0; 41 | for (int j = k; j >= 0; j--) { 42 | if ((1 << j) <= R - L + 1) { 43 | sum += st[L][j]; 44 | L += 1 << j; 45 | } 46 | } 47 | cout << sum << endl; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Graph/Splitwise_Algorithm_with_transaction_details.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define inf INT_MAX 9 | #define minf INT_MIN 10 | #define pb push_back 11 | #define all(v) v.begin(),v.end() 12 | #define print(v) for(auto x:v) cout<> no_of_transaction >> no_of_friend; 24 | // int x, y, amount; 25 | // int net[100000] = {}; 26 | // while (no_of_transaction--) { 27 | // cin >> x >> y >> amount; 28 | // net[x] -= amount; 29 | // net[y] += amount; 30 | // } 31 | // multisetm; 32 | // for (int i = 0; i < no_of_friend; i++) 33 | // if (net[i] != 0) m.insert(net[i]); 34 | // int cnt = 0;//Minimum number of transaction needed for settlement 35 | // //Pop out two persosn from left and right and settle them 36 | // while (!m.empty()) { 37 | // auto low = m.begin(); 38 | // auto high = prev(m.end()); 39 | // int debit = *low; 40 | // int credit = *high; 41 | // m.erase(low); 42 | // m.erase(high); 43 | // //Settlement 44 | // int settlement_amount = min(-debit, credit); 45 | // cnt++; 46 | // //Settlement amount from donor to acceptor 47 | // debit += settlement_amount; 48 | // credit -= settlement_amount; 49 | // if (debit != 0) m.insert(debit); 50 | // if (credit != 0) m.insert(credit); 51 | // } 52 | // cout << cnt << endl; 53 | // } 54 | 55 | class person_compare { 56 | public: 57 | bool operator()(pairp1, pairp2) { 58 | return p1.second < p2.second; 59 | } 60 | }; 61 | 62 | //Splitwise Algorithm in Cash transaction 63 | //Distribution of money among friends for settlement 64 | int32_t main() { 65 | fastio; 66 | int no_of_transaction, no_of_friend; 67 | cin >> no_of_transaction >> no_of_friend; 68 | mapnet; 69 | string x, y; int amount; 70 | while (no_of_transaction--) { 71 | cin >> x >> y >> amount; 72 | if (net.count(x) == 0) net[x] = 0; 73 | if (net.count(y) == 0) net[y] = 0; 74 | net[x] -= amount; 75 | net[y] += amount; 76 | } 77 | multiset, person_compare>m; 78 | for (auto p : net) { 79 | string person = p.first; 80 | int amount = p.second; 81 | if (net[person] != 0) m.insert({person, amount}); 82 | } 83 | //Settlement from start and end 84 | int cnt = 0; //Minimum number of transaction needed for settlement 85 | while (!m.empty()) { 86 | auto low = m.begin(); 87 | auto high = prev(m.end()); 88 | int debit = low->second; 89 | string debit_person = low->first; 90 | 91 | int credit = high->second; 92 | string credit_person = high->first; 93 | 94 | //Erase them out 95 | m.erase(low); 96 | m.erase(high); 97 | 98 | int settlement_amount = min(-debit, credit); 99 | debit += settlement_amount; 100 | credit -= settlement_amount; 101 | cnt++; 102 | //Print the transaction between friends 103 | cout << credit_person << " will pay " << settlement_amount << " to " << debit_person << endl; 104 | if (debit != 0) m.insert({debit_person, debit}); 105 | if (credit != 0) m.insert({credit_person, credit}); 106 | } 107 | cout << "Total transaction made between friends is " << cnt << endl; 108 | } 109 | -------------------------------------------------------------------------------- /Graph/Topological_Sorting_for_Directed_Acyclic_Graph_DAG_using_BFS_Approach.cpp: -------------------------------------------------------------------------------- 1 | //TopologicalSort Using BFS Approach 2 | 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | 8 | list*l; 9 | int V; 10 | public: 11 | Graph(int V){ 12 | this->V=V; 13 | l=new list[V]; 14 | } 15 | void addEdge(int x,int y){ 16 | //Directed Graph 17 | l[x].push_back(y); 18 | } 19 | 20 | void topologicalSort(){ 21 | //indegree : incoming nodes 22 | int *indegree=new int[V]; 23 | //Initialize all the indegree with 0. 24 | for(int i=0;iy 28 | //indegree[y]++; 29 | for(int i=0;iq; 35 | //Step 1. Find nodes with 0 indegree 36 | for(int i=0;i 4 | using namespace std; 5 | 6 | template 7 | class Graph{ 8 | map>l; 9 | public: 10 | //Directed Graph 11 | void addEdge(T x,T y){ 12 | l[x].push_back(y); 13 | } 14 | 15 | void dfs_helper(T source,map&visited,list&ordering){ 16 | //Recursive function that will traverse the Graph 17 | 18 | 19 | //Mark this node is visited 20 | visited[source]=true; 21 | //Go to all neighbour of that node that is not visited 22 | for(T neighbour:l[source]){ 23 | if(!visited[neighbour]) 24 | dfs_helper(neighbour,visited,ordering); 25 | } 26 | ordering.push_front(source); 27 | } 28 | 29 | void dfs(){ 30 | mapvisited; 31 | listordering; 32 | //Mark all the node that is not visited in the beginning. 33 | for(auto p:l){ 34 | T node=p.first; 35 | visited[node]=false; 36 | } 37 | //Iterate over all the vertices and initiate a dfs Call 38 | for(auto p:l){ 39 | T node=p.first; 40 | if(!visited[node]){ 41 | dfs_helper(node,visited,ordering); 42 | } 43 | } 44 | //Finally return the list or print the list 45 | for(auto node:ordering) 46 | cout<g; 55 | g.addEdge("Python","DataPreProcessing"); 56 | g.addEdge("Python","PyTorch"); 57 | g.addEdge("Python","ML"); 58 | g.addEdge("DataPreProcessing","ML"); 59 | g.addEdge("PyTorch","DL"); 60 | g.addEdge("ML","DL"); 61 | g.addEdge("DL","FaceRecognition"); 62 | g.addEdge("DataSet","FaceRecognition"); 63 | 64 | g.dfs(); 65 | 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Graph/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Graph/a.out -------------------------------------------------------------------------------- /Graph/apple.txt: -------------------------------------------------------------------------------- 1 | 15 30 2 | *************************** 3 | ************#####********** 4 | ************#***#********** 5 | *****########***######***** 6 | ****##*****######***###**** 7 | ***##******************##** 8 | -------------------------------------------------------------------------------- /Heaps/Build_Heap_from_Array.cpp: -------------------------------------------------------------------------------- 1 | //Build Heap from Array in: 2 | //Method 1 : Time Complexity : O(NlogN) 3 | //Method 2 : Time Complexity : O(N) 4 | 5 | 6 | #include 7 | using namespace std; 8 | 9 | 10 | void print(vectorv){ 11 | for(int x:v) 12 | cout<&v){ 18 | for(int i=2;i1 && v[index]>v[parent]){ 22 | swap(v[index],v[parent]); 23 | index=parent; 24 | parent=parent/2; 25 | } 26 | } 27 | } 28 | 29 | bool compare(int a,int b){ 30 | return a>b; 31 | } 32 | void heapify(vector&v,int index){ 33 | int left=2*index; 34 | int right=left+1; 35 | int min_index=index; 36 | int last_index=v.size()-1; 37 | 38 | if(left<=last_index && compare(v[left],v[index])) 39 | min_index=left; 40 | if(right<=last_index && compare(v[right],v[min_index])) 41 | min_index=right; 42 | 43 | //It means there is a smaller element 44 | //Also a Base Case if node comes at its correct position 45 | if(min_index!=index){ 46 | swap(v[index],v[min_index]); 47 | heapify(v,min_index); 48 | } 49 | } 50 | 51 | //Time Complexity : O(N) 52 | void buildHeapOptimised(vector&v){ 53 | //We have to start from the first non leaf node 54 | for(int i=(v.size()-1)/2;i>=1;i--){ 55 | heapify(v,i); 56 | } 57 | } 58 | 59 | int main(){ 60 | 61 | //Zero index is blocked.We are building heap from index 1. 62 | vectorv{-1,10,20,5,6,1,8,9,4}; //Heap 63 | buildHeapOptimised(v); 64 | print(v); 65 | 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Heaps/Heap_Priority_Queue.cpp: -------------------------------------------------------------------------------- 1 | // Heap or Priority Queue 2 | // A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Generally, Heaps can be of two types: 3 | // Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree. 4 | // Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree. 5 | 6 | 7 | #include 8 | using namespace std; 9 | 10 | class Heap{ 11 | vectorv; 12 | bool minHeap; 13 | bool compare(int a,int b){ 14 | if(minHeap) 15 | return ab; 18 | } 19 | void heapify(int index){ 20 | int left=2*index; 21 | int right=left+1; 22 | int min_index=index; 23 | int last_index=v.size()-1; 24 | 25 | if(left<=last_index && compare(v[left],v[index])) 26 | min_index=left; 27 | if(right<=last_index && compare(v[right],v[min_index])) 28 | min_index=right; 29 | 30 | //It means there is a smaller element 31 | //Also a Base Case if node comes at its correct position 32 | if(min_index!=index){ 33 | swap(v[index],v[min_index]); 34 | heapify(min_index); 35 | } 36 | } 37 | public: 38 | Heap(int default_size = 10, bool type = true){ 39 | v.reserve(default_size); 40 | v.push_back(-1); 41 | minHeap = type; 42 | } 43 | 44 | //Implementing MinHeap as well as MaxHeap 45 | //Keep pushing to the top till you reach a root node or stop midway because current element is already greater than its parent node. 46 | void push(int d){ 47 | v.push_back(d); 48 | int index=v.size()-1; 49 | int parent=index/2; 50 | while(index>1 && compare(v[index],v[parent])){ 51 | swap(v[index],v[parent]); 52 | index=parent; 53 | parent=parent/2; 54 | } 55 | } 56 | //Return the topmost element of the Heap 57 | int top(){ 58 | return v[1]; 59 | } 60 | //Remove the min or max element from heap or we can say it removes the root node of the heap. 61 | void pop(){ 62 | int last_index=v.size()-1; 63 | swap(v[1],v[last_index]); 64 | v.pop_back(); 65 | //Heapify Operation 66 | heapify(1);//index/we want to heapify the index 1 or we can say that we can find the correct position of the index 1 in the heap 67 | } 68 | 69 | bool empty(){ 70 | return v.size()==1; 71 | } 72 | }; 73 | 74 | int main(){ 75 | 76 | //Give some initial size of heap. 77 | //if the arguement is true ,then it will act as minHeap and if it is true, it behaves as MaxHeap 78 | Heap h(10,false); 79 | int n; 80 | cin>>n; 81 | for(int i=0;i>element; 84 | h.push(element); 85 | } 86 | while(!h.empty()){ 87 | cout< 2 | using namespace std; 3 | 4 | void downHeapify(vector&heap,int idx){ 5 | int leftIdx = 2*idx+1; 6 | int rightIdx = 2*idx+2; 7 | if(leftIdx>=heap.size() && rightIdx>=heap.size()) 8 | return; 9 | 10 | int largestIdx=idx; 11 | if(leftIdxheap[largestIdx]) 12 | largestIdx=leftIdx; 13 | 14 | if(rightIdxheap[largestIdx]) 15 | largestIdx=rightIdx; 16 | 17 | if(largestIdx==idx) 18 | return; 19 | swap(heap[idx],heap[largestIdx]); 20 | downHeapify(heap,largestIdx); 21 | } 22 | 23 | void deletePeak(vector&heap){ 24 | swap(heap[0],heap[heap.size()-1]); 25 | heap.pop_back(); 26 | downHeapify(heap,0); 27 | } 28 | 29 | // void insert(vector&heap,int key){ 30 | // heap.push_back(key); 31 | // upheapify(heap,heap.size()-1); 32 | // } 33 | 34 | // void buildheap(vector&heap){ 35 | // for(int i=0;i&heap){ 40 | for(int i=heap.size()-1;i>=0;i--) 41 | downHeapify(heap,i); 42 | } 43 | 44 | void display(vector&heap){ 45 | for(int i=0;i&heap,int idx,int heapSize){ 52 | int leftIdx = 2*idx+1; 53 | int rightIdx = 2*idx+2; 54 | if(leftIdx>=heapSize && rightIdx>=heapSize) 55 | return; 56 | 57 | int largestIdx=idx; 58 | if(leftIdxheap[largestIdx]) 59 | largestIdx=leftIdx; 60 | 61 | if(rightIdxheap[largestIdx]) 62 | largestIdx=rightIdx; 63 | 64 | if(largestIdx==idx) 65 | return; 66 | swap(heap[idx],heap[largestIdx]); 67 | downHeapifyHelper(heap,largestIdx,heapSize); 68 | } 69 | 70 | void heapSort(vector&arr){ 71 | int heapSize=arr.size(); 72 | buildHeapOptimised(arr); 73 | for(int i=arr.size()-1;i>=0;i--){ 74 | swap(arr[0],arr[i]); 75 | heapSize--; 76 | downHeapifyHelper(arr,0,heapSize); 77 | } 78 | } 79 | int main(){ 80 | 81 | int n; 82 | cin>>n; 83 | vectorheap(n); 84 | for(int i=0;i>heap[i]; 86 | 87 | heapSort(heap); 88 | display(heap); 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /Heaps/Join_the_ropes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //By default of the priority_queue is max heap.. 5 | int connectTheRopesWithMinimumCost(vector &ropes){ 6 | priority_queue,greater> pq(ropes.begin(),ropes.end()); 7 | int cost=0; 8 | while(pq.size()>1){ 9 | int first=pq.top(); 10 | pq.pop(); 11 | int second=pq.top(); 12 | pq.pop(); 13 | cost+=first+second; 14 | pq.push(first+second); 15 | } 16 | return cost; 17 | } 18 | 19 | 20 | 21 | int main(){ 22 | 23 | int t; 24 | cin>>t; 25 | while(t--){ 26 | int n; 27 | cin>>n; 28 | vector ropes(n); 29 | for(int i=0;i>ropes[i]; 31 | cout< 2 | using namespace std; 3 | 4 | //Time complexity :- O(nklogk) 5 | typedef pair> customPair; //In this pair, first int represents the element, next two int represents its position in 2d vector ie. i,j 6 | vector mergeKSortedArrays(vector>v) 7 | { 8 | vectorresult; 9 | priority_queue,greater>pq; 10 | for(int i=0;i>t; 31 | while(t--){ 32 | int k; 33 | cin>>k; 34 | int n=0; 35 | vector>v(k); 36 | for(int i=0;i>n; 39 | v[i].push_back(n); 40 | } 41 | } 42 | vectorsorted=mergeKSortedArrays(v); 43 | for(auto x:sorted) 44 | cout< 5 | using namespace std; 6 | 7 | void Median_of_a_stream(vector&v,int n){ 8 | //max heap to store the smaller half element 9 | priority_queues; 10 | //min heap to store the greater half element 11 | priority_queue,greater>g; 12 | s.push(v[0]); 13 | double median=v[0]; 14 | cout<g.size()){ 19 | if(x>n; 60 | 61 | vectorv(n); 62 | for(int i=0;i>v[i]; 64 | Median_of_a_stream(v,n); 65 | } 66 | -------------------------------------------------------------------------------- /Heaps/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Heaps/a.out -------------------------------------------------------------------------------- /Heaps/kth_smallest_element_in_row_and_column_wise_sorted_matrix.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.codingblocks.com/s/263748 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | typedef pair>customPair; 8 | int kthSmallest(vector>v,int row,int column,int k){ 9 | priority_queue,greater>pq; 10 | map,bool>visited; 11 | for(int i=0;i>row>>column; 51 | vector>v; 52 | for(int i=0;itemp; 54 | for(int j=0;j>x; 56 | temp.push_back(x); 57 | } 58 | v.push_back(temp); 59 | } 60 | 61 | cin>>k; 62 | cout< 2 | using namespace std; 3 | #define ll long long int 4 | #define endl '\n' 5 | #define fastio ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | #define setbit __builtin_popcount 9 | #define setbitll __builtin_popcount 10 | 11 | class Node { 12 | public: 13 | int data; 14 | Node* next; 15 | //constructor 16 | Node(int data) { 17 | this->data = data; 18 | next = nullptr; 19 | } 20 | }; 21 | 22 | void insert(Node* &head, int data) { 23 | Node* n = new Node(data); 24 | if (head == nullptr) { 25 | head = n; 26 | n->next = n; 27 | } 28 | else { 29 | n->next = head; 30 | Node*temp = head; 31 | while (temp->next != head) 32 | temp = temp->next; 33 | temp->next = n; 34 | } 35 | } 36 | 37 | //Floyd's Cycle : Cycle Detection & Removal 38 | bool detectCycle(Node* head) { 39 | Node* slow = head; 40 | Node*fast = head; 41 | while (fast && fast->next) { 42 | fast = fast->next->next; 43 | slow = slow->next; 44 | if (slow == fast) 45 | return true; 46 | } 47 | return false; 48 | } 49 | 50 | //The point where slow and fast meet ..from that point ,the distance 51 | //from head to start of the loop is same as the distance from that 52 | //point to the start of the loop. 53 | void removeLoop(Node* head) { 54 | Node* slow = head; 55 | Node* fast = head; 56 | while (fast && fast->next) { 57 | fast = fast->next->next; 58 | slow = slow->next; 59 | if (slow == fast) 60 | break; 61 | } 62 | //when cycle starts from the head of the loop 63 | if (slow == head) { 64 | while (fast->next != slow) 65 | fast = fast->next; 66 | fast->next = nullptr; 67 | } 68 | else { 69 | slow = head; 70 | while (slow->next != fast->next) { 71 | slow = slow->next; 72 | fast = fast->next; 73 | } 74 | fast->next = nullptr; 75 | } 76 | } 77 | 78 | //Search any node and return that node if present 79 | Node* getNode(Node* head, int data) { 80 | Node* temp = head; 81 | //All nodes except last node 82 | while (temp->next != head) { 83 | if (temp->data == data) 84 | return temp; 85 | temp = temp->next; 86 | } 87 | if (temp->data == data) 88 | return temp; 89 | return nullptr; 90 | } 91 | //Deletion in a Circular Linked List 92 | void deleteNode(Node* &head, int data) { 93 | Node* del = getNode(head, data); 94 | if (del == nullptr) 95 | return; 96 | if (head == del) 97 | head = head->next; 98 | Node* temp = head; 99 | //stop one step behind the node to be deleted 100 | while (temp->next != del) 101 | temp = temp->next; 102 | temp->next = del->next; 103 | delete del; 104 | } 105 | 106 | void print(Node* head) { 107 | Node* temp = head; 108 | while (temp->next != head) { 109 | cout << temp->data << " "; 110 | temp = temp->next; 111 | } 112 | cout << temp->data << endl; 113 | } 114 | 115 | int32_t main() { 116 | Node *head = nullptr; 117 | insert(head, 10); 118 | insert(head, 20); 119 | insert(head, 30); 120 | insert(head, 40); 121 | insert(head, 50); 122 | print(head); 123 | deleteNode(head, 10); 124 | print(head); 125 | } 126 | -------------------------------------------------------------------------------- /Linked_List/Floyd_Cycle_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define FASTIO ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | class Node { 10 | public: 11 | int data; 12 | Node* next; 13 | //constructor 14 | Node(int data) { 15 | this->data = data; 16 | next = nullptr; 17 | } 18 | }; 19 | 20 | void insert(Node* &head, int data) { 21 | Node* n = new Node(data); 22 | if (head == nullptr) { 23 | head = n; 24 | n->next = n; 25 | } 26 | else { 27 | n->next = head; 28 | Node*temp = head; 29 | while (temp->next != head) 30 | temp = temp->next; 31 | temp->next = n; 32 | } 33 | } 34 | 35 | //Floyd's Cycle : Cycle Detection & Removal 36 | bool detectCycle(Node* head) { 37 | Node* slow = head; 38 | Node*fast = head; 39 | while (fast && fast->next) { 40 | fast = fast->next->next; 41 | slow = slow->next; 42 | if (slow == fast) 43 | return true; 44 | } 45 | return false; 46 | } 47 | 48 | //The point where slow and fast meet ..from that point ,the distance 49 | //from head to start of the loop is same as the distance from that 50 | //point to the start of the loop. 51 | void removeLoop(Node* head) { 52 | Node* slow = head; 53 | Node* fast = head; 54 | while (fast && fast->next) { 55 | fast = fast->next->next; 56 | slow = slow->next; 57 | if (slow == fast) 58 | break; 59 | } 60 | if (slow == head) { 61 | while (fast->next != slow) 62 | fast = fast->next; 63 | fast->next = nullptr; 64 | } 65 | else { 66 | slow = head; 67 | while (slow->next != fast->next) { 68 | slow = slow->next; 69 | fast = fast->next; 70 | } 71 | fast->next = nullptr; 72 | } 73 | } 74 | 75 | 76 | void print(Node* head) { 77 | Node* temp = head; 78 | while (temp->next != head) { 79 | cout << temp->data << " "; 80 | temp = temp->next; 81 | } 82 | cout << temp->data << endl; 83 | } 84 | 85 | int32_t main() { 86 | Node *head = nullptr; 87 | insert(head, 10); 88 | insert(head, 20); 89 | insert(head, 30); 90 | insert(head, 40); 91 | insert(head, 50); 92 | print(head); 93 | if (detectCycle(head)) 94 | cout << "Cycle is present" << endl; 95 | removeLoop(head); 96 | if (detectCycle(head)) 97 | cout << "Cycle is present" << endl; 98 | else 99 | cout << "Cycle is not present" << endl; 100 | 101 | } 102 | -------------------------------------------------------------------------------- /Linked_List/Kth_element_from_the_end_of_the_Linked_List.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fastIO ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | class Node { 10 | public: 11 | int data; 12 | Node* next; 13 | //constructor 14 | Node(int data) { 15 | this->data = data; 16 | next = nullptr; 17 | } 18 | }; 19 | 20 | //Passing a pointer via pass by reference 21 | void insertAtHead(Node* &head, int data) { 22 | if (head == nullptr) { 23 | head = new Node(data); 24 | return; 25 | } 26 | Node* n = new Node(data); 27 | n->next = head; 28 | head = n; 29 | } 30 | 31 | //Passing this head value via pass by value .So original head will remains same in the main. 32 | void print(Node* head) { 33 | while (head) { 34 | cout << head->data << " "; 35 | head = head->next; 36 | } 37 | cout << endl; 38 | } 39 | 40 | Node* take_input() { 41 | int data; 42 | cin >> data; 43 | Node* head = nullptr; 44 | while (data != -1) { 45 | insertAtHead(head, data); 46 | cin >> data; 47 | } 48 | return head; 49 | } 50 | //Kth Node from the end of the Linked List 51 | void printKthNode(Node* head, int k) { 52 | Node* slow = head; 53 | Node* fast = head; 54 | int cnt = 1; 55 | while (cnt <= k) { 56 | cnt++; 57 | fast = fast->next; 58 | } 59 | while (fast) { 60 | slow = slow->next; 61 | fast = fast->next; 62 | } 63 | cout << slow-> data << endl; 64 | } 65 | 66 | int32_t main() { 67 | Node* head = nullptr; 68 | head = take_input(); 69 | print(head); 70 | int k; 71 | cin >> k; 72 | printKthNode(head, k); 73 | } 74 | -------------------------------------------------------------------------------- /Linked_List/Linked_List.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | 10 | class Node { 11 | public: 12 | int data; 13 | Node* next; 14 | //constructor 15 | Node(int data) { 16 | this->data = data; 17 | next = nullptr; 18 | } 19 | }; 20 | 21 | //Linked List class (object oriented) 22 | // class LinkedList{ 23 | // Node* head; 24 | // Node* tail; 25 | // public: 26 | // LinkedList(){ 27 | 28 | // } 29 | // void insert(int data){ 30 | 31 | // } 32 | // }; 33 | 34 | //Functions (Procedural Programming) 35 | void build() { 36 | 37 | } 38 | //Passing a pointer via pass by reference 39 | void insertAtHead(Node* &head, int data) { 40 | if (head == nullptr) { 41 | head = new Node(data); 42 | return; 43 | } 44 | Node* n = new Node(data); 45 | n->next = head; 46 | head = n; 47 | } 48 | 49 | //Passing this head value via pass by value .So original head will remains same in the main. 50 | void print(Node* head) { 51 | while (head) { 52 | cout << head->data << " "; 53 | head = head->next; 54 | } 55 | cout << endl; 56 | } 57 | 58 | //Return length of the Linked List 59 | int length(Node* head) { 60 | int cnt = 0; 61 | while (head) { 62 | cnt++; 63 | head = head->next; 64 | } 65 | return cnt; 66 | } 67 | 68 | void insertAtTail(Node* &head, int data) { 69 | if (head == nullptr) { 70 | head = new Node(data); 71 | return; 72 | } 73 | Node*tail = head; 74 | while (tail->next) 75 | tail = tail->next; 76 | tail->next = new Node(data); 77 | } 78 | 79 | void insertAtMiddle(Node* head, int data, int pos) { 80 | //Corner Case 81 | if (head == nullptr || pos == 0) { 82 | insertAtHead(head, data); 83 | return; 84 | } 85 | else if (pos > length(head)) { 86 | insertAtTail(head, data); 87 | return; 88 | } 89 | else { 90 | //take pos-1 jump to reach the position 91 | int jump = 1; 92 | Node* temp = head; 93 | while (jump <= pos - 1) { 94 | temp = temp->next; 95 | jump++; 96 | } 97 | //Create a new node 98 | Node* n = new Node(data); 99 | n->next = temp->next; 100 | temp->next = n; 101 | } 102 | } 103 | 104 | void deleteHead(Node* &head) { 105 | if (head == nullptr) 106 | return; 107 | Node* temp = head->next; 108 | delete head; 109 | head = temp; 110 | } 111 | 112 | //Search Operation : Linear Search 113 | bool search(Node* head, int key) { 114 | if (head == nullptr) 115 | return false; 116 | while (head) { 117 | if (key == head->data) 118 | return true; 119 | head = head->next; 120 | } 121 | return false; 122 | } 123 | 124 | //Recursively 125 | bool RecursivelySearch(Node* head, int key) { 126 | if (head == nullptr) 127 | return false; 128 | if (key == head->data) 129 | return true; 130 | return RecursivelySearch(head->next, key); 131 | } 132 | 133 | Node* take_input() { 134 | int data; 135 | cin >> data; 136 | Node* head = nullptr; 137 | while (data != -1) { 138 | insertAtHead(head, data); 139 | cin >> data; 140 | } 141 | return head; 142 | } 143 | 144 | //Operator Overloading : cout<>head - input the entire linked list 150 | istream& operator>>(istream &is, Node* &head) { 151 | head = take_input(); 152 | return is; 153 | } 154 | 155 | int32_t main() { 156 | 157 | /* 158 | Node* head = nullptr; 159 | insertAtHead(head, 3); 160 | insertAtHead(head, 2); 161 | insertAtHead(head, 1); 162 | insertAtHead(head, 0); 163 | 164 | print(head); 165 | print(head); 166 | 167 | insertAtMiddle(head, 4, 3); 168 | insertAtTail(head, 7); 169 | print(head); 170 | 171 | deleteHead(head); 172 | print(head); 173 | 174 | cout << search(head, 4) << endl; 175 | cout << search(head, 5) << endl; 176 | cout << RecursivelySearch(head, 4) << endl; 177 | cout << RecursivelySearch(head, 5) << endl; 178 | */ 179 | Node* head = take_input(); 180 | Node* head2 = take_input(); 181 | print(head); 182 | print(head2); 183 | //cout << head; //print entire linked list..for this , we will do operator overloading 184 | //cout << head2; 185 | //cout << head << head2; 186 | // Node* head = nullptr; 187 | // Node* head2 = nullptr; 188 | // cin >> head >> head2; 189 | // cout << head << head2; 190 | } 191 | -------------------------------------------------------------------------------- /Linked_List/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define FASTIO ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | class Node { 10 | public: 11 | int data; 12 | Node* next; 13 | //constructor 14 | Node(int data) { 15 | this->data = data; 16 | next = nullptr; 17 | } 18 | }; 19 | 20 | //Passing a pointer via pass by reference 21 | void insertAtHead(Node* &head, int data) { 22 | if (head == nullptr) { 23 | head = new Node(data); 24 | return; 25 | } 26 | Node* n = new Node(data); 27 | n->next = head; 28 | head = n; 29 | } 30 | 31 | //Passing this head value via pass by value .So original head will remains same in the main. 32 | void print(Node* head) { 33 | while (head) { 34 | cout << head->data << " "; 35 | head = head->next; 36 | } 37 | cout << endl; 38 | } 39 | 40 | Node* take_input() { 41 | int data; 42 | cin >> data; 43 | Node* head = nullptr; 44 | while (data != -1) { 45 | insertAtHead(head, data); 46 | cin >> data; 47 | } 48 | return head; 49 | } 50 | 51 | //Mid Point Runner Technique 52 | Node* midpoint(Node* head) { 53 | if (head == nullptr || head->next == nullptr) 54 | return head; 55 | Node* slow = head; 56 | Node* fast = head->next; 57 | while (fast != nullptr && fast->next != nullptr) { 58 | fast = fast->next->next; 59 | slow = slow->next; 60 | } 61 | return slow; 62 | } 63 | 64 | //Merge two Sorted Linked List into One Recursively 65 | Node* merge(Node* head1, Node* head2) { 66 | //Base Case 67 | if (head1 == nullptr) 68 | return head2; 69 | if (head2 == nullptr) 70 | return head1; 71 | Node* head = nullptr; 72 | if (head1->data < head2->data) { 73 | head = head1; 74 | head->next = merge(head1->next, head2); 75 | } 76 | else { 77 | head = head2; 78 | head->next = merge(head1, head2->next); 79 | } 80 | return head; 81 | } 82 | 83 | //Sort an unsorted Linked List : Merge Sort 84 | //time complexity : O(nlogn) 85 | Node* mergeSort(Node* head) { 86 | if (head == nullptr or head->next == nullptr) 87 | return head; 88 | //1)Divide about mid point 89 | Node* mid = midpoint(head); 90 | Node* a = head; 91 | Node* b = mid->next; 92 | mid->next = nullptr; 93 | //2)Recursively sort the two parts 94 | a = mergeSort(a); 95 | b = mergeSort(b); 96 | //3)Merge them 97 | Node* c = merge(a, b); 98 | return c; 99 | } 100 | 101 | int32_t main() { 102 | Node *head = nullptr; 103 | head = take_input(); 104 | head = mergeSort(head); 105 | print(head); 106 | } 107 | -------------------------------------------------------------------------------- /Linked_List/Merge_two_sorted_linked_list_into_one.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define FASTIO ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | class Node { 10 | public: 11 | int data; 12 | Node* next; 13 | //constructor 14 | Node(int data) { 15 | this->data = data; 16 | next = nullptr; 17 | } 18 | }; 19 | 20 | //Passing a pointer via pass by reference 21 | void insertAtHead(Node* &head, int data) { 22 | if (head == nullptr) { 23 | head = new Node(data); 24 | return; 25 | } 26 | Node* n = new Node(data); 27 | n->next = head; 28 | head = n; 29 | } 30 | 31 | //Passing this head value via pass by value .So original head will remains same in the main. 32 | void print(Node* head) { 33 | while (head) { 34 | cout << head->data << " "; 35 | head = head->next; 36 | } 37 | cout << endl; 38 | } 39 | 40 | Node* take_input() { 41 | int data; 42 | cin >> data; 43 | Node* head = nullptr; 44 | while (data != -1) { 45 | insertAtHead(head, data); 46 | cin >> data; 47 | } 48 | return head; 49 | } 50 | 51 | //Merge two Sorted Linked List into One Recursively 52 | Node* merge(Node* head1, Node* head2) { 53 | //Base Case 54 | if (head1 == nullptr) 55 | return head2; 56 | if (head2 == nullptr) 57 | return head1; 58 | Node* head = nullptr; 59 | if (head1->data < head2->data) { 60 | head = head1; 61 | head->next = merge(head1->next, head2); 62 | } 63 | else { 64 | head = head2; 65 | head->next = merge(head1, head2->next); 66 | } 67 | return head; 68 | } 69 | 70 | int32_t main() { 71 | Node *head1 = nullptr, *head2 = nullptr; 72 | head1 = take_input(); 73 | head2 = take_input(); 74 | Node* head = merge(head1, head2); 75 | print(head); 76 | } 77 | -------------------------------------------------------------------------------- /Linked_List/Mid_Point_Runner_Technique.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define FASTIO ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | 10 | class Node { 11 | public: 12 | int data; 13 | Node* next; 14 | //constructor 15 | Node(int data) { 16 | this->data = data; 17 | next = nullptr; 18 | } 19 | }; 20 | 21 | //Passing a pointer via pass by reference 22 | void insertAtHead(Node* &head, int data) { 23 | if (head == nullptr) { 24 | head = new Node(data); 25 | return; 26 | } 27 | Node* n = new Node(data); 28 | n->next = head; 29 | head = n; 30 | } 31 | 32 | //Passing this head value via pass by value .So original head will remains same in the main. 33 | void print(Node* head) { 34 | while (head) { 35 | cout << head->data << " "; 36 | head = head->next; 37 | } 38 | cout << endl; 39 | } 40 | 41 | //Return length of the Linked List 42 | int length(Node* head) { 43 | int cnt = 0; 44 | while (head) { 45 | cnt++; 46 | head = head->next; 47 | } 48 | return cnt; 49 | } 50 | 51 | void insertAtTail(Node* &head, int data) { 52 | if (head == nullptr) { 53 | head = new Node(data); 54 | return; 55 | } 56 | Node*tail = head; 57 | while (tail->next) 58 | tail = tail->next; 59 | tail->next = new Node(data); 60 | } 61 | 62 | void insertAtMiddle(Node* head, int data, int pos) { 63 | //Corner Case 64 | if (head == nullptr || pos == 0) { 65 | insertAtHead(head, data); 66 | return; 67 | } 68 | else if (pos > length(head)) { 69 | insertAtTail(head, data); 70 | return; 71 | } 72 | else { 73 | //take pos-1 jump to reach the position 74 | int jump = 1; 75 | Node* temp = head; 76 | while (jump <= pos - 1) { 77 | temp = temp->next; 78 | jump++; 79 | } 80 | //Create a new node 81 | Node* n = new Node(data); 82 | n->next = temp->next; 83 | temp->next = n; 84 | } 85 | } 86 | 87 | void deleteHead(Node* &head) { 88 | if (head == nullptr) 89 | return; 90 | Node* temp = head->next; 91 | delete head; 92 | head = temp; 93 | } 94 | 95 | Node* take_input() { 96 | int data; 97 | cin >> data; 98 | Node* head = nullptr; 99 | while (data != -1) { 100 | insertAtHead(head, data); 101 | cin >> data; 102 | } 103 | return head; 104 | } 105 | 106 | //Mid Point Runner Technique 107 | Node* midpoint(Node* head) { 108 | if (head == nullptr || head->next == nullptr) 109 | return head; 110 | Node* slow = head; 111 | Node* fast = head->next; 112 | while (fast != nullptr && fast->next != nullptr) { 113 | fast = fast->next->next; 114 | slow = slow->next; 115 | } 116 | return slow; 117 | } 118 | 119 | int32_t main() { 120 | Node*head = nullptr; 121 | head = take_input(); 122 | Node* mid = midpoint(head); 123 | print(head); 124 | cout << mid->data << endl; 125 | } 126 | -------------------------------------------------------------------------------- /Linked_List/Reverse_a_Linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | 10 | class Node { 11 | public: 12 | int data; 13 | Node* next; 14 | //constructor 15 | Node(int data) { 16 | this->data = data; 17 | next = nullptr; 18 | } 19 | }; 20 | 21 | //Passing a pointer via pass by reference 22 | void insertAtHead(Node* &head, int data) { 23 | if (head == nullptr) { 24 | head = new Node(data); 25 | return; 26 | } 27 | Node* n = new Node(data); 28 | n->next = head; 29 | head = n; 30 | } 31 | //Passing this head value via pass by value .So original head will remains same in the main. 32 | void print(Node* head) { 33 | while (head) { 34 | cout << head->data << " "; 35 | head = head->next; 36 | } 37 | cout << endl; 38 | } 39 | 40 | Node* take_input() { 41 | int data; 42 | cin >> data; 43 | Node* head = nullptr; 44 | while (data != -1) { 45 | insertAtHead(head, data); 46 | cin >> data; 47 | } 48 | return head; 49 | } 50 | 51 | Node* reverse(Node* head) { 52 | Node* prev = nullptr; 53 | Node* current = head; 54 | while (current) { 55 | //Save the next node 56 | Node* next = current->next; 57 | //make the current node point to prev 58 | current->next = prev; 59 | //update the prev and current one step forward 60 | prev = current; 61 | current = next; 62 | } 63 | return prev; 64 | } 65 | 66 | //Recursively reverse a Linked List 67 | Node* recursiveReverse(Node* head) { 68 | //smallest linked list 69 | if (head->next == nullptr || head == nullptr) 70 | return head; 71 | //Recursive Case 72 | Node* shead = recursiveReverse(head->next); 73 | Node* temp = head->next; 74 | head->next = nullptr; 75 | temp->next = head; 76 | return shead; 77 | } 78 | 79 | int32_t main() { 80 | Node*head = nullptr; 81 | head = take_input(); 82 | print(head); 83 | //head = reverse(head); 84 | head = recursiveReverse(head); 85 | print(head); 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /Queue/First_non_repeating_character_in_a_stream_of_characters.cpp: -------------------------------------------------------------------------------- 1 | //https://practice.geeksforgeeks.org/problems/first-non-repeating-character-in-a-stream/0 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define endl "\n" 7 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 8 | #define mod 1000000007 9 | #define gcd __gcd 10 | 11 | class Queue { 12 | int cs; 13 | listl; 14 | public: 15 | Queue() { 16 | cs = 0; 17 | } 18 | bool empty() { 19 | return cs == 0; 20 | } 21 | void push(int data) { 22 | l.push_back(data); 23 | cs++; 24 | } 25 | void pop() { 26 | if (!empty()) { 27 | cs--; 28 | l.pop_front(); 29 | } 30 | } 31 | int front() { 32 | return l.front(); 33 | } 34 | }; 35 | 36 | int32_t main() { 37 | int t; 38 | cin >> t; 39 | while (t--) { 40 | int n; 41 | cin >> n; 42 | int freq[27] = {}; 43 | queueq; 44 | for (int i = 1; i <= n; i++) { 45 | char ch; 46 | cin >> ch; 47 | //Insert in the queue and update the frequency table 48 | q.push(ch); 49 | freq[ch - 'a']++; 50 | //Query 51 | while (!q.empty()) { 52 | int idx = q.front() - 'a'; 53 | if (freq[idx] > 1) 54 | q.pop(); 55 | else { 56 | cout << q.front() << " "; 57 | break; 58 | } 59 | } 60 | //q is empty 61 | if (q.empty()) 62 | cout << "-1 "; 63 | } 64 | cout << endl; 65 | } 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /Queue/Implementation_of_Queue_using_Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | class Queue { 10 | int *arr; 11 | int f, r, cs, ms; 12 | public: 13 | Queue(int ds = 5) { 14 | arr = new int[ds]; 15 | cs = 0; 16 | ms = ds; 17 | f = 0; 18 | r = ms - 1; 19 | } 20 | bool full() { 21 | return cs == ms; 22 | } 23 | bool empty() { 24 | return cs == 0; 25 | } 26 | void push(int data) { 27 | if (!full()) { 28 | r = (r + 1) % ms; 29 | arr[r] = data; 30 | cs++; 31 | } 32 | } 33 | void pop() { 34 | if (!empty()) { 35 | f = (f + 1) % ms; 36 | cs--; 37 | } 38 | } 39 | int front() { 40 | return arr[f]; 41 | } 42 | ~Queue() { 43 | if (arr != NULL) { 44 | delete [] arr; 45 | arr = NULL; 46 | } 47 | } 48 | }; 49 | 50 | int32_t main() { 51 | Queue q(7); 52 | for (int i = 0; i <= 6; i++) 53 | q.push(i); 54 | q.pop(); 55 | q.pop(); 56 | while (!q.empty()) { 57 | cout << q.front() << " "; 58 | q.pop(); 59 | } 60 | cout << endl; 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /Queue/Implementation_of_Queue_using_two_stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | //Implement Queue using two Stack 10 | template 11 | class Queue { 12 | stacks1, s2; 13 | public: 14 | bool empty() { 15 | return s1.empty(); 16 | } 17 | void push(T data) { 18 | s1.push(data); 19 | } 20 | void pop() { 21 | while (!s1.empty()) { 22 | s2.push(s1.top()); 23 | s1.pop(); 24 | } 25 | s2.pop(); 26 | while (!s2.empty()) { 27 | s1.push(s2.top()); 28 | s2.pop(); 29 | } 30 | } 31 | T front() { 32 | while (!s1.empty()) { 33 | s2.push(s1.top()); 34 | s1.pop(); 35 | } 36 | T x = s2.top(); 37 | while (!s2.empty()) { 38 | s1.push(s2.top()); 39 | s2.pop(); 40 | } 41 | return x; 42 | } 43 | }; 44 | 45 | int32_t main() { 46 | Queueq; 47 | for (int i = 1; i <= 5; i++) 48 | q.push(i); 49 | while (!q.empty()) { 50 | cout << q.front() << " "; 51 | q.pop(); 52 | } 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Queue/Implementation_of_stack_using_two_Queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | //Implement stack using two Queue 10 | template 11 | class Stack { 12 | queueq1; 13 | queueq2; 14 | public: 15 | bool empty() { 16 | return q1.empty(); 17 | } 18 | void push(T x) { 19 | q2.push(x); 20 | while (!q1.empty()) { 21 | q2.push(q1.front()); 22 | q1.pop(); 23 | } 24 | swap(q1, q2); 25 | } 26 | void pop() { 27 | q1.pop(); 28 | } 29 | T top() { 30 | return q1.front(); 31 | } 32 | }; 33 | 34 | int32_t main() { 35 | Stacks; 36 | for (int i = 1; i <= 5; i++) 37 | s.push(i); 38 | while (!s.empty()) { 39 | cout << s.top() << " "; 40 | s.pop(); 41 | } 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Queue/LinkedList_Implementation_of_Queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | #define gcd __gcd 8 | 9 | class Queue { 10 | int cs; 11 | listl; 12 | public: 13 | Queue() { 14 | cs = 0; 15 | } 16 | bool empty() { 17 | return cs == 0; 18 | } 19 | void push(int data) { 20 | l.push_back(data); 21 | cs++; 22 | } 23 | void pop() { 24 | if (!empty()) { 25 | cs--; 26 | l.pop_front(); 27 | } 28 | } 29 | int front() { 30 | return l.front(); 31 | } 32 | }; 33 | 34 | int32_t main() { 35 | Queue q; 36 | for (int i = 1; i <= 10; i++) 37 | q.push(i); 38 | while (!q.empty()) { 39 | cout << q.front() << " "; 40 | q.pop(); 41 | } 42 | cout << endl; 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-Structure-and-Algorithm 2 | It includes all the important algorithms in Data structures and algorithms that is very important for competitive proogramming as well as for company perspective. 3 | It includes topic like linked list, stack, queues, heaps, tree, graph and trie. 4 | It also includes some important string matching algorithms. 5 | Also some interview questions to practice ! 6 | Stay connected ! I will add dynamic programming soon! 7 | -------------------------------------------------------------------------------- /Stack/Max_Histogram_Area.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | 8 | ll max_hist_area(ll hist[], ll n) { 9 | stacks; 10 | ll max_area = 0; 11 | ll i = 0; 12 | while (i < n) { 13 | if (s.empty() || hist[s.top()] <= hist[i]) 14 | s.push(i++); 15 | else { 16 | ll tp = s.top(); 17 | s.pop(); 18 | ll current_area = hist[tp] * (s.empty() ? i : i - s.top() - 1); 19 | max_area = max(max_area, current_area); 20 | } 21 | } 22 | while (!s.empty()) { 23 | ll tp = s.top(); 24 | s.pop(); 25 | ll current_area = hist[tp] * (s.empty() ? i : i - s.top() - 1); 26 | max_area = max(current_area, max_area); 27 | } 28 | return max_area; 29 | } 30 | 31 | 32 | int32_t main() { 33 | int t; 34 | cin >> t; 35 | while (t--) { 36 | ll n; 37 | cin >> n; 38 | ll hist[n]; 39 | for (int i = 0; i < n; i++) 40 | cin >> hist[i]; 41 | cout << max_hist_area(hist, n) << endl; 42 | } 43 | <<<<<<< HEAD 44 | return 0; 45 | ======= 46 | >>>>>>> be5ae3c27cc7b99f8724beaf23e361f216ff1541 47 | } 48 | -------------------------------------------------------------------------------- /Stack/StockSpan.cpp: -------------------------------------------------------------------------------- 1 | //https://practice.geeksforgeeks.org/problems/stock-span-problem/0 2 | #include 3 | using namespace std; 4 | #define ll long long int 5 | #define endl "\n" 6 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 7 | #define mod 1000000007 8 | 9 | //Time Complexity : O(n) 10 | void stockSpan(vector&price, int n, vector&span) { 11 | stacks;//indices of the day 12 | s.push(0); 13 | span.push_back(1); 14 | for (int i = 1; i < n; i++) { 15 | int currentPrices = price[i]; 16 | //topmost element that is higher than the current price 17 | while (!s.empty() && price[s.top()] <= currentPrices) 18 | s.pop(); 19 | int x = (s.empty() ? (i + 1) : (i - s.top())); 20 | span.push_back(x); 21 | //Push this element into this stack 22 | s.push(i); 23 | } 24 | } 25 | 26 | 27 | int32_t main() { 28 | int t; 29 | cin >> t; 30 | while (t--) { 31 | int n; 32 | cin >> n; 33 | vectorprice(n); 34 | for (int i = 0; i < n; i++) 35 | cin >> price[i]; 36 | vectorspan; 37 | stockSpan(price, n, span); 38 | for (auto x : span) 39 | cout << x << " "; 40 | cout << endl; 41 | } 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Stack/Valid_Parenthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | 8 | 9 | bool isValidParenthesis(char *s) { 10 | stackst; 11 | for (int i = 0; s[i] != '\0'; i++) { 12 | char ch = s[i]; 13 | if (ch == '(') 14 | st.push(ch); 15 | else if (ch == ')') { 16 | if (st.empty() || st.top() != '(') 17 | return false; 18 | st.pop(); 19 | } 20 | } 21 | return st.empty(); 22 | } 23 | 24 | int32_t main() { 25 | char s[100] = "((a+b)+(c-d+f))"; 26 | if (isValidParenthesis(s)) 27 | cout << "Valid Parenthesis" << endl; 28 | else 29 | cout << "Not a Valid Parenthesis" << endl; 30 | return 0; 31 | } 32 | 33 | #include 34 | using namespace std; 35 | #define ll long long int 36 | #define endl "\n" 37 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 38 | #define mod 1000000007 39 | 40 | bool validParenthesis(string s) { 41 | stackst; 42 | for (int i = 0; i < s.length(); i++) { 43 | if (s[i] == '(' || s[i] == '{' || s[i] == '[') 44 | st.push(s[i]); 45 | else { 46 | if (st.empty() && (s[i] == ')' || s[i] == '}' || s[i] == ']')) 47 | return false; 48 | else if (st.top() == '(' && s[i] == ')') 49 | st.pop(); 50 | else if (st.top() == '{' && s[i] == '}') 51 | st.pop(); 52 | else if (st.top() == '[' && s[i] == ']') 53 | st.pop(); 54 | else 55 | return false; 56 | } 57 | } 58 | return st.empty(); 59 | } 60 | 61 | int32_t main() { 62 | int t; 63 | cin >> t; 64 | while (t--) { 65 | string s; 66 | cin >> s; 67 | cout << validParenthesis(s) << endl; 68 | } 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /Stack/nextGreaterElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define endl "\n" 5 | #define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) 6 | #define mod 1000000007 7 | 8 | 9 | void nextGreaterElement(vector&a, ll n, vector&ans) { 10 | stacks; 11 | ans.push_back(-1); 12 | s.push(a[n - 1]); 13 | for (ll i = n - 2; i >= 0; i--) { 14 | while (!s.empty() && s.top() <= a[i]) 15 | s.pop(); 16 | ll x = (s.empty() ? -1 : s.top()); 17 | ans.push_back(x); 18 | s.push(a[i]); 19 | } 20 | reverse(ans.begin(), ans.end()); 21 | } 22 | 23 | int32_t main() { 24 | fast; 25 | int t; 26 | cin >> t; 27 | while (t--) { 28 | ll n; 29 | cin >> n; 30 | vectora(n); 31 | for (ll i = 0; i < n; i++) 32 | cin >> a[i]; 33 | vectorans; 34 | nextGreaterElement(a, n, ans); 35 | for (auto x : ans) 36 | cout << x << " "; 37 | cout << endl; 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /String_Matching_ALgorithm/KMP_Knuth_Morris_Pratt.cpp: -------------------------------------------------------------------------------- 1 | // Example: 2 | // Input: 3 | // 2 4 | // aabaacaadaabaaba 5 | // aaaab 6 | // aabaacaadaabaaba 7 | // caada 8 | // Output: 9 | // No 10 | // Yes 11 | 12 | 13 | #include 14 | using namespace std; 15 | 16 | 17 | //Preprocessing the length of longest prefix suffix array i.e lps Array 18 | void computeLPSArray(string pat, int m, int* lps){ 19 | 20 | lps[0]=0; 21 | int len=0; 22 | int i=1; 23 | while(i>t; 75 | while(t--){ 76 | string txt,pat; 77 | cin>>txt>>pat; 78 | if(KMPSearch(pat,txt)) 79 | cout<<"Yes"< 2 | using namespace std; 3 | 4 | int longestSubstringLength(string s,int m){ 5 | 6 | vectorprev(256,-1); 7 | int i=0,j,res; 8 | for(j=0;j>t; 22 | while(t--){ 23 | string s; 24 | cin>>s; 25 | int m=s.length(); 26 | cout< 2 | using namespace std; 3 | 4 | void Naive_Search(string str,string pattern){ 5 | for(int i=0;i<=str.size()-pattern.size();i++){ 6 | int j; 7 | for(j=0;jleft && !root->right) return root->data; 5 | 6 | int ls = maxPathSumUtil(root->left, res); 7 | int rs = maxPathSumUtil(root->right, res); 8 | 9 | if (root->left && root->right) { 10 | res = max(res, ls + rs + root->data); 11 | return max(ls, rs) + root->data; 12 | } 13 | return (!root->left) ? rs + root->data : ls + root->data; 14 | } 15 | 16 | int maxPathSum(Node *root) { 17 | int res = INT_MIN; 18 | maxPathSumUtil(root, res); 19 | return res; 20 | } 21 | -------------------------------------------------------------------------------- /Tree/Minimum_distance_between_two_node_of_a_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | Node* lca(Node* root , int n1 , int n2 ) { 2 | if (root == nullptr) return nullptr; 3 | 4 | if (root->data == n1 || root->data == n2) return root; 5 | 6 | Node* leftans = lca(root->left, n1, n2); 7 | Node* rightans = lca(root->right, n1, n2); 8 | if (leftans != nullptr && rightans != nullptr) 9 | return root; 10 | else if (leftans != nullptr) 11 | return leftans; 12 | else 13 | return rightans; 14 | } 15 | 16 | //Finding the level of a given node from the root node 17 | int search(Node* root, int key, int level = 0) { 18 | if (!root) return -1; 19 | if (root->data == key) return level; 20 | int left = search(root->left, key, level + 1); 21 | if (left != -1) return left; 22 | search(root->right, key, level + 1); 23 | } 24 | int findDist(Node* root, int a, int b) { 25 | Node* lca_node = lca(root, a, b); 26 | int l1 = search(lca_node, a); 27 | int l2 = search(lca_node, b); 28 | return l1 + l2; 29 | } 30 | -------------------------------------------------------------------------------- /Tree/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trojancode95/Data-Structure-and-Algorithm/56aa20a5aa1a52a866f7759fb0c97702e67a9428/Tree/a.out -------------------------------------------------------------------------------- /Tree/lca.cpp: -------------------------------------------------------------------------------- 1 | 2 | Node* lca(Node* root , int n1 , int n2 ) { 3 | if (root == nullptr) return nullptr; 4 | 5 | if (root->data == n1 || root->data == n2) return root; 6 | 7 | Node* leftans = lca(root->left, n1, n2); 8 | Node* rightans = lca(root->right, n1, n2); 9 | if (leftans != nullptr && rightans != nullptr) 10 | return root; 11 | else if (leftans != nullptr) 12 | return leftans; 13 | else 14 | return rightans; 15 | } 16 | -------------------------------------------------------------------------------- /Trie/Longest_Common_Prefix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node{ 5 | public: 6 | char data; 7 | unordered_mapchildren; 8 | bool terminal; 9 | int cnt; 10 | Node(char d){ 11 | data=d; 12 | terminal=false; 13 | cnt=0; 14 | } 15 | }; 16 | 17 | class Trie{ 18 | public: 19 | Node*root; 20 | Trie(){ 21 | root=new Node('\0'); 22 | } 23 | 24 | void insert(string s){ 25 | Node*temp=root; 26 | for(int i=0;s[i]!='\0';i++){ 27 | char ch=s[i]; 28 | if(temp->children.count(ch)){ 29 | temp=temp->children[ch]; 30 | (temp->cnt)++; 31 | } 32 | else{ 33 | Node*n=new Node(ch); 34 | temp->children[ch]=n; 35 | temp=n; 36 | (temp->cnt)++; 37 | } 38 | } 39 | temp->terminal=true; 40 | } 41 | bool find(string s){ 42 | Node*temp=root; 43 | for(int i=0;s[i]!='\0';i++){ 44 | char ch=s[i]; 45 | if(temp->children.count(ch)==0) 46 | return false; 47 | else 48 | temp=temp->children[ch]; 49 | } 50 | return temp->terminal; 51 | } 52 | }; 53 | 54 | string longestPrefix(Trie t,string s,int n){ 55 | Node*temp=t.root; 56 | int length=s.length(); 57 | string ans=""; 58 | 59 | for(int i=0;s[i]!='\0';i++){ 60 | if(temp->children[s[i]]->cnt==n){ 61 | ans+=s[i]; 62 | temp=temp->children[s[i]]; 63 | } 64 | else 65 | break; 66 | } 67 | 68 | return ans; 69 | } 70 | int main(){ 71 | 72 | 73 | Trie t; 74 | int n; 75 | cin>>n; 76 | string s[n]; 77 | // cin.get(); 78 | for(int i=0;i>s[i]; 80 | t.insert(s[i]); 81 | } 82 | 83 | cout< 12 | using namespace std; 13 | 14 | class trieNode{ 15 | public: 16 | trieNode* left; //Represents 0 17 | trieNode* right;//Represents 1 18 | }; 19 | 20 | void insert(int n,trieNode* head){ 21 | trieNode *curr=head; 22 | for(int i=31;i>=0;i--){ 23 | int bit=(n>>i)&1; 24 | if(bit==0){ 25 | if(curr->left==nullptr) 26 | curr->left=new trieNode(); 27 | 28 | curr=curr->left; 29 | } 30 | else{ 31 | if(curr->right==nullptr) 32 | curr->right=new trieNode(); 33 | 34 | curr=curr->right; 35 | } 36 | } 37 | } 38 | 39 | int findMaxXorPair(trieNode* head,int ele){ 40 | int max_xor=INT_MIN; 41 | trieNode *curr=head; 42 | int value=ele; 43 | int current_xor=0; 44 | for(int i=31;i>=0;i--){ 45 | int bit=(value>>i)&1; 46 | if(bit==0){ 47 | if(curr->right!=nullptr){ 48 | curr=curr->right; 49 | current_xor+=(int)pow(2,i); 50 | } 51 | else 52 | curr=curr->left; 53 | } 54 | else{ 55 | if(curr->left!=nullptr){ 56 | curr=curr->left; 57 | current_xor+=(int)pow(2,i); 58 | } 59 | else 60 | curr=curr->right; 61 | } 62 | } 63 | max_xor=max(max_xor,current_xor); 64 | return max_xor; 65 | } 66 | int main(){ 67 | int n; 68 | cin>>n; 69 | int *arr=new int[n](); 70 | for(int i=0;i>arr[i]; 72 | trieNode *head = new trieNode(); 73 | 74 | int max_xor=INT_MIN; 75 | for(int i=0;i 2 | using namespace std; 3 | 4 | class node{ 5 | public: 6 | char data; 7 | node*children[26]; 8 | bool terminal; 9 | int count; 10 | node(char d){ 11 | data=d; 12 | terminal=false; 13 | count=0; 14 | for(int i=0;i<26;i++) 15 | children[i]=nullptr; 16 | } 17 | }; 18 | 19 | class Trie{ 20 | public: 21 | node* root; 22 | Trie(){ 23 | root=new node('\0'); 24 | } 25 | void insert(string s){ 26 | node* temp=root; 27 | for(int i=0;s[i]!='\0';i++){ 28 | if(temp->children[s[i]-'a']!=nullptr){ 29 | temp=temp->children[s[i]-'a']; 30 | temp->count++; 31 | } 32 | else{ 33 | temp->children[s[i]-'a']=new node(s[i]); 34 | temp=temp->children[s[i]-'a']; 35 | temp->count++; 36 | } 37 | } 38 | temp->terminal=true; 39 | } 40 | bool search(string s){ 41 | node*temp=root; 42 | for(int i=0;s[i]!='\0';i++){ 43 | if(temp->children[s[i]-'a']==nullptr) 44 | return false; 45 | else 46 | temp=temp->children[s[i]-'a']; 47 | } 48 | return temp->terminal; 49 | } 50 | 51 | }; 52 | 53 | string uniquePrefix(Trie t,string s){ 54 | Node*temp=t.root; 55 | int i=0; 56 | int length=s.length(); 57 | string ans=""; 58 | while(i!=length){ 59 | if(temp->children[s[i]]->cnt==1){ 60 | ans=ans+s[i]; 61 | return ans; 62 | } 63 | else{ 64 | ans=ans+s[i]; 65 | temp=temp->children[s[i]]; 66 | } 67 | i++; 68 | } 69 | return "-1"; 70 | } 71 | 72 | string longestPrefix(Trie t,string s,int n){ 73 | node*temp=t.root; 74 | int length=s.length(); 75 | string ans=""; 76 | for(int i=0;s[i]!='\0';i++){ 77 | if(temp->children[s[i]-'a']->count==n){ 78 | ans+=s[i]; 79 | temp=temp->children[s[i]-'a']; 80 | } 81 | else 82 | break; 83 | } 84 | 85 | return (ans=="")?"-1":ans; 86 | } 87 | 88 | int main(){ 89 | 90 | 91 | Trie t; 92 | char words[][10]={"a","hello","not","news","apple"}; 93 | char w[10]; 94 | cin>>w; 95 | for(int i=0;i<5;i++) 96 | t.insert(words[i]); 97 | 98 | if(t.search(w)) 99 | cout< 2 | using namespace std; 3 | 4 | 5 | 6 | class Node{ 7 | public: 8 | char data; 9 | unordered_mapchildren; 10 | bool terminal; 11 | Node(char d){ 12 | data=d; 13 | terminal=false; 14 | } 15 | }; 16 | 17 | class Trie{ 18 | 19 | Node* root; 20 | int cnt; 21 | 22 | public: 23 | 24 | Trie(){ 25 | root=new Node('\0'); 26 | cnt=0; 27 | } 28 | 29 | void insert(char *w){ 30 | Node* temp=root; 31 | for(int i=0;w[i]!='\0';i++){ 32 | char ch=w[i]; 33 | if(temp->children.count(ch))//count check whether the character is present in the hashmap or not 34 | temp=temp->children[ch]; 35 | else{ 36 | Node* n=new Node(ch); 37 | temp->children[ch]=n; 38 | temp=n; 39 | } 40 | } 41 | temp->terminal=true; //last character will always be terminal node 42 | } 43 | 44 | bool find(char* w){ 45 | Node* temp=root; 46 | for(int i=0;w[i]!='\0';i++){ 47 | char ch=w[i]; 48 | if(temp->children.count(ch)==0) 49 | return false; 50 | else 51 | temp=temp->children[ch]; 52 | } 53 | return temp->terminal; // if the last character of any word which we r finding is terminal ,then that word is present, else it is only a prefix of any word. 54 | } 55 | }; 56 | 57 | int main(){ 58 | 59 | 60 | Trie t; 61 | char words[][10]={"a","hello","not","news","apple"}; 62 | char w[10]; 63 | cin>>w; 64 | for(int i=0;i<5;i++) 65 | t.insert(words[i]); 66 | 67 | if(t.find(w)) 68 | cout< 2 | using namespace std; 3 | 4 | class Node{ 5 | public: 6 | char data; 7 | unordered_mapchildren; 8 | bool terminal; 9 | int cnt; 10 | Node(char d){ 11 | data=d; 12 | terminal=false; 13 | cnt=0; 14 | } 15 | }; 16 | 17 | class Trie{ 18 | public: 19 | Node*root; 20 | Trie(){ 21 | root=new Node('\0'); 22 | } 23 | 24 | void insert(string s){ 25 | Node*temp=root; 26 | for(int i=0;s[i]!='\0';i++){ 27 | char ch=s[i]; 28 | if(temp->children.count(ch)){ 29 | temp=temp->children[ch]; 30 | (temp->cnt)++; 31 | } 32 | else{ 33 | Node*n=new Node(ch); 34 | temp->children[ch]=n; 35 | temp=n; 36 | (temp->cnt)++; 37 | } 38 | } 39 | temp->terminal=true; 40 | } 41 | bool find(string s){ 42 | Node*temp=root; 43 | for(int i=0;s[i]!='\0';i++){ 44 | char ch=s[i]; 45 | if(temp->children.count(ch)==0) 46 | return false; 47 | else 48 | temp=temp->children[ch]; 49 | } 50 | return temp->terminal; 51 | } 52 | }; 53 | 54 | string prefix(Trie t,string s){ 55 | Node*temp=t.root; 56 | int i=0; 57 | int length=s.length(); 58 | string ans=""; 59 | while(i!=length){ 60 | if(temp->children[s[i]]->cnt==1){ 61 | ans=ans+s[i]; 62 | return ans; 63 | } 64 | else{ 65 | ans=ans+s[i]; 66 | temp=temp->children[s[i]]; 67 | } 68 | i++; 69 | } 70 | return "-1"; 71 | } 72 | int main(){ 73 | 74 | Trie t; 75 | int n; 76 | cin>>n; 77 | string s[n]; 78 | cin.get(); 79 | for(int i=0;i>s[i]; 81 | t.insert(s[i]); 82 | } 83 | 84 | for(int i=0;i