├── Advanced Algorithms and Complexity ├── Week1 │ ├── 15_flows_1_transporting_goods.pdf │ ├── 15_flows_2_network_flows.pdf │ ├── 15_flows_3_residual_networks.pdf │ ├── 15_flows_4_maxflow_mincut.pdf │ ├── 15_flows_5_ford_fulkerson.pdf │ ├── 15_flows_6_example.pdf │ ├── 15_flows_7_edmonds_karp.pdf │ ├── 15_flows_8_bipartite_matching.pdf │ ├── 15_flows_9_image_segmentation.pdf │ ├── Programming Assignment: Programming Assignment 1 │ │ ├── Program1.cpp │ │ ├── Program2.cpp │ │ └── Programming Assignment: Programming Assignment 1.pdf │ └── Quiz: Flow Algorithms.png ├── Week2 │ ├── 16_LP_1_1_introduction.pdf │ ├── 16_LP_1_2_LP.pdf │ ├── 16_LP_2_1_Substitution.pdf │ ├── 16_LP_2_2_GaussianElimination.pdf │ ├── 16_LP_2_GaussianElimination.pdf │ ├── 16_LP_3_Convexity.pdf │ ├── 16_LP_4_1_Duality.pdf │ ├── 16_LP_4_2_DualityProofs.pdf │ ├── 16_LP_5_Formulations.pdf │ ├── 16_LP_6_simplex.pdf │ ├── 16_LP_7_ellipsoid.pdf │ └── Programming Assignment: Programming Assignment 2 │ │ ├── Program1.py │ │ ├── Program2.py │ │ └── Programming Assignment: Programming Assignment 2.pdf ├── Week3 │ ├── 17_np_complete_problems_1_search_problems.pdf │ ├── 17_np_complete_problems_2_reductions.pdf │ ├── Programming Assignment: Programming Assignment 3 │ │ └── Programming Assignment: Programming Assignment 3.pdf │ └── sudokusolver.py ├── Week4 │ ├── 18_coping_with_np_completeness_1_introduction.pdf │ ├── 18_coping_with_np_completeness_2_special_cases.pdf │ ├── 18_coping_with_np_completeness_3_exact_algorithms.pdf │ ├── 18_coping_with_np_completeness_4_approximation_algorithms.pdf │ └── Programming Assignment: Programming Assignment 4 │ │ └── Programming Assignment: Programming Assignment 4.pdf └── Week5 │ └── Practice Programming Assignment: (Optional) Programming Assignment 5 │ └── Practice Programming Assignment: (Optional) Programming Assignment 5.pdf ├── Algorithmic Toolbox ├── Week2 │ ├── Program1.py │ ├── Program2.py │ ├── Program3.py │ ├── Program4.py │ ├── Program5.py │ ├── Program6.py │ ├── Program7.py │ ├── Program8.py │ └── Programming Assignment: Programming Assignment 2: Algorithmic Warm-up.pdf ├── Week3 │ ├── Program1.py │ ├── Program2.py │ ├── Program3.py │ ├── Program4.py │ ├── Program5.py │ ├── Program6.cpp │ └── week3_greedy_algorithms.pdf ├── Week4 │ ├── Program1.py │ ├── Program2.py │ ├── Program3.py │ └── week4_divide_and_conquer.pdf ├── Week5 │ ├── Program1.py │ ├── Program2.py │ ├── Program3.py │ ├── Program4.py │ ├── Program5.py │ └── week5_dynamic_programming1.pdf └── Week6 │ ├── Program1.py │ ├── Program2.py │ └── week6_dynamic_programming2.pdf ├── Algorithms on Graphs ├── Week1 │ ├── 09_graph_decomposition_1_basics.pdf │ ├── 09_graph_decomposition_2_representations.pdf │ ├── 09_graph_decomposition_3_explore.pdf │ ├── 09_graph_decomposition_4_connectivity.pdf │ ├── 09_graph_decomposition_5_pre-and-post-orders.pdf │ └── Programming Assignment: Programming Assignment 1: Decomposition of Graphs │ │ ├── Program1.cpp │ │ ├── Program2.cpp │ │ └── Programming Assignment: Programming Assignment 1: Decomposition of Graphs.pdf ├── Week2 │ ├── 09_graph_decomposition_6_dags.pdf │ ├── 09_graph_decomposition_7_topological-sort.pdf │ ├── 09_graph_decomposition_8_strongly-connected-components.pdf │ ├── 09_graph_decomposition_9_computing-sccs.pdf │ └── Programming Assignment: Programming Assignment 2: Decomposition of Graphs │ │ ├── Program1.cpp │ │ ├── Program2.cpp │ │ ├── Program3.cpp │ │ └── Programming Assignment: Programming Assignment 2: Decomposition of Graphs.pdf ├── Week3 │ ├── 10_shortest_paths_in_graphs_1_bfs.pdf │ └── Programming Assignment: Programming Assignment 3: Paths in Graphs │ │ ├── Program1.cpp │ │ ├── Program2.cpp │ │ └── Programming Assignment: Programming Assignment 3: Paths in Graphs.pdf ├── Week4 │ ├── 10_shortest_paths_in_graphs_2_dijkstra.pdf │ ├── 10_shortest_paths_in_graphs_3_bellman_ford.pdf │ └── Programming Assignment: Programming Assignment 4: Paths in Graphs │ │ ├── Program1.cpp │ │ ├── Program2.cpp │ │ ├── Programming Assignment: Programming Assignment 4: Paths in Graphs.pdf │ │ └── _Program3.py ├── Week5 │ ├── 11_1_minimum_spanning_trees.pdf │ └── Programming Assignment: Programming Assignment 5: Minimum Spanning Trees │ │ ├── Program1.cpp │ │ ├── Program2.cpp │ │ └── Programming Assignment: Programming Assignment 5: Minimum Spanning Trees.pdf └── Week6 │ ├── 19_advanced_shortest_paths_1_bidirectional_dijkstra.pdf │ ├── 19_advanced_shortest_paths_2_A_star.pdf │ ├── 19_advanced_shortest_paths_3_contraction_hierarchies.pdf │ └── Practice Programming Assignment: Advanced Shortest Paths │ └── Practice Programming Assignment: Advanced Shortest Paths.pdf ├── Algorithms on Strings ├── Week1 │ ├── Practice Quiz: Tries and Suffix Trees.png │ ├── Programming Assignment: Programming Assignment 1 │ │ ├── Program1.py │ │ ├── Program2.py │ │ ├── Program3.py │ │ └── Programming Assignment: Programming Assignment 1.pdf │ └── Suffix-Trees-Reduced.pdf ├── Week2 │ ├── BWT-Suffix-Arrays-Reduced.pdf │ ├── Programming Assignment: Programming Assignment 2 │ │ ├── Program1.py │ │ ├── Program4.py │ │ └── Programming Assignment: Programming Assignment 2.pdf │ ├── better_bwmatching.pdf │ └── bwmatching.pdf ├── Week3 │ └── 14_algorithmic_challenges_1_knuth_morris_pratt.pdf └── Week4 │ ├── 14_algorithmic_challenges_2_suffix_array.pdf │ ├── 14_algorithmic_challenges_3_from_suffix_array_to_suffix_tree.pdf │ └── Programming Assignment: Programming Assignment 3 │ ├── Program1.py │ ├── Program2.py │ └── Programming Assignment: Programming Assignment 3.pdf ├── Data Structures ├── Week1 │ ├── Program1.py │ ├── Program2.cpp │ ├── _61d056196c0646e8667f6765d9aa0f96_Programming-Assignment-1.pdf │ └── spoj0.py ├── Week3 │ ├── Program1.cpp │ ├── Program3.cpp │ └── _c9371d52e542255e07157e2c33819ca8_Programming-Assignment-2.pdf ├── Week4 │ ├── Program1.py │ ├── Program2.py │ ├── Program3.py │ └── _3534ea217849fead5923c07550874ab4_Programming-Assignment-3.pdf └── Week6 │ ├── Program1.cpp │ ├── Program1.py │ ├── Program2.cpp │ ├── Program3.cpp │ └── _9e9dde3a6fc7020663126285ae606c07_Programming-Assignment-4.pdf ├── LICENSE └── README.md /Advanced Algorithms and Complexity/Week1/15_flows_1_transporting_goods.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week1/15_flows_1_transporting_goods.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week1/15_flows_2_network_flows.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week1/15_flows_2_network_flows.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week1/15_flows_3_residual_networks.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week1/15_flows_3_residual_networks.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week1/15_flows_4_maxflow_mincut.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week1/15_flows_4_maxflow_mincut.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week1/15_flows_5_ford_fulkerson.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week1/15_flows_5_ford_fulkerson.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week1/15_flows_6_example.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week1/15_flows_6_example.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week1/15_flows_7_edmonds_karp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week1/15_flows_7_edmonds_karp.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week1/15_flows_8_bipartite_matching.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week1/15_flows_8_bipartite_matching.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week1/15_flows_9_image_segmentation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week1/15_flows_9_image_segmentation.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week1/Programming Assignment: Programming Assignment 1/Program1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | typedef vector vi; 9 | 10 | #define MAX_V 100 11 | #define INF 1000000000 12 | 13 | int res[MAX_V][MAX_V], mf, f, s, t; // global variables 14 | vi p; 15 | 16 | void augment(int v, int minEdge) { // traverse BFS spanning tree from s to t 17 | if (v == s) { f = minEdge; return; } // record minEdge in a global variable f 18 | else if (p[v] != -1) { augment(p[v], min(minEdge, res[p[v]][v])); // recursive 19 | res[p[v]][v] -= f; res[v][p[v]] += f; } // update 20 | } 21 | 22 | int main() { 23 | int n, m, u, v, c; 24 | 25 | scanf("%d %d", &n, &m); 26 | s = 0; t = n-1; 27 | memset(res, 0, sizeof(res)); 28 | for (int i = 0; i < m; i++) { 29 | scanf("%d %d %d", &u, &v, &c); 30 | u--; v--; 31 | res[u][v] += c; 32 | } 33 | 34 | mf = 0; // mf stands for max_flow 35 | while (1) { // O(VE^2) (actually O(V^3E) Edmonds Karp's algorithm 36 | f = 0; 37 | // run BFS, compare with the original BFS shown in Section 4.2.2 38 | vi dist(MAX_V, INF); dist[s] = 0; queue q; q.push(s); 39 | p.assign(MAX_V, -1); // record the BFS spanning tree, from s to t! 40 | while (!q.empty()) { 41 | int u = q.front(); q.pop(); 42 | if (u == t) break; // immediately stop BFS if we already reach sink t 43 | for (int v = 0; v < MAX_V; v++) // note: this part is slow 44 | if (res[u][v] > 0 && dist[v] == INF) 45 | dist[v] = dist[u] + 1, q.push(v), p[v] = u; 46 | } 47 | augment(t, INF); // find the min edge weight `f' along this path, if any 48 | if (f == 0) break; // we cannot send any more flow (`f' = 0), terminate 49 | mf += f; // we can still send a flow, increase the max flow! 50 | } 51 | 52 | printf("%d\n", mf); // this is the max flow value 53 | 54 | return 0; 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week1/Programming Assignment: Programming Assignment 1/Program2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | typedef vector vi; 10 | 11 | #define MAX_V 205 12 | #define INF 1000000000 13 | 14 | int res[MAX_V][MAX_V], mf, f, s, t; // global variables 15 | vi p; 16 | 17 | void augment(int v, int minEdge) { // traverse BFS spanning tree from s to t 18 | if (v == s) { f = minEdge; return; } // record minEdge in a global variable f 19 | else if (p[v] != -1) { augment(p[v], min(minEdge, res[p[v]][v])); // recursive 20 | res[p[v]][v] -= f; res[v][p[v]] += f; } // update 21 | } 22 | 23 | int main() { 24 | int n, m, u, v, c; 25 | 26 | scanf("%d %d", &n, &m); 27 | s = 0; t = n+m+1; 28 | memset(res, 0, sizeof(res)); 29 | 30 | for (int i=1; i<=n; i++) 31 | res[s][i] = 1; 32 | 33 | for (int j=n+1; j<=n+m; j++) 34 | res[j][t] = 1; 35 | 36 | for (int i = 1; i <= n; i++) { 37 | for (int j = n+1; j <= n+m; j++){ 38 | scanf("%d", &c); 39 | res[i][j] += c; 40 | } 41 | } 42 | 43 | /* 44 | for(int i=0; i<10; i++){ 45 | for(int j=0; j<10; j++) 46 | cout< q; q.push(s); 58 | p.assign(MAX_V, -1); // record the BFS spanning tree, from s to t! 59 | while (!q.empty()) { 60 | int u = q.front(); q.pop(); 61 | if (u == t) break; // immediately stop BFS if we already reach sink t 62 | for (int v = 0; v < MAX_V; v++) // note: this part is slow 63 | if (res[u][v] > 0 && dist[v] == INF) 64 | dist[v] = dist[u] + 1, q.push(v), p[v] = u; 65 | } 66 | augment(t, INF); // find the min edge weight `f' along this path, if any 67 | if (f == 0) break; // we cannot send any more flow (`f' = 0), terminate 68 | mf += f; // we can still send a flow, increase the max flow! 69 | } 70 | 71 | //printf("%d\n", mf); // this is the max flow value 72 | 73 | /* 74 | for(int i=0; i<10; i++){ 75 | for(int j=0; j<10; j++) 76 | cout<= 10**9: 87 | print("Infinity") 88 | else: 89 | l = [str.format("{0:.15f}", e) for e in l] 90 | print("Bounded solution") 91 | print(" ".join(l)) 92 | 93 | -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week2/Programming Assignment: Programming Assignment 2/Programming Assignment: Programming Assignment 2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week2/Programming Assignment: Programming Assignment 2/Programming Assignment: Programming Assignment 2.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week3/17_np_complete_problems_1_search_problems.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week3/17_np_complete_problems_1_search_problems.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week3/17_np_complete_problems_2_reductions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week3/17_np_complete_problems_2_reductions.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week3/Programming Assignment: Programming Assignment 3/Programming Assignment: Programming Assignment 3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week3/Programming Assignment: Programming Assignment 3/Programming Assignment: Programming Assignment 3.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week3/sudokusolver.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import os 3 | 4 | puzzle=[ 5 | "5***1***4", 6 | "***2*6***", 7 | "**8*9*6**", 8 | "*4*****1*", 9 | "7*1*8*4*6", 10 | "*5*****3*", 11 | "**6*4*1**", 12 | "***5*2***", 13 | "2***6***8" 14 | ] 15 | 16 | clauses = [] 17 | 18 | digits = range(1, 10) 19 | 20 | def varnum(i, j, k): 21 | assert(i in digits and j in digits and k in digits) 22 | return 100*i + 10*j + k 23 | 24 | 25 | def exactly_one_of(literals): 26 | clauses.append([l for l in literals]) 27 | 28 | for pair in itertools.combinations(literals, 2): 29 | clauses.append([-l for l in pair]) 30 | 31 | 32 | # cell [i,j] contains exactly one digit 33 | for (i, j) in itertools.product(digits, repeat=2): 34 | exactly_one_of([varnum(i, j, k) for k in digits]) 35 | 36 | # k appears exactly once in row i 37 | for (i, k) in itertools.product(digits, repeat=2): 38 | exactly_one_of([varnum(i, j, k) for j in digits]) 39 | 40 | # k appears exactly once in column j 41 | for (j, k) in itertools.product(digits, repeat=2): 42 | exactly_one_of([varnum(i, j, k) for i in digits]) 43 | 44 | # k appears exactly once in a 3x3 block 45 | for (i, j) in itertools.product([1, 4, 7], repeat=2): 46 | for k in digits: 47 | exactly_one_of([varnum(i + deltai, j + deltaj, k) for (deltai, deltaj) in itertools.product(range(3), repeat=2)]) 48 | 49 | 50 | for (i, j) in itertools.product(digits, repeat=2): 51 | if puzzle[i - 1][j - 1] != "*": 52 | k = int(puzzle[i - 1][j - 1]) 53 | assert(k in digits) 54 | # [i,j] already contains k: 55 | clauses.append([varnum(i, j, k)]) 56 | 57 | with open('tmp.cnf', 'w') as f: 58 | f.write("p cnf {} {}\n".format(999, len(clauses))) 59 | for c in clauses: 60 | c.append(0); 61 | f.write(" ".join(map(str, c))+"\n") 62 | 63 | os.system("minisat tmp.cnf tmp.sat") 64 | 65 | with open("tmp.sat", "r") as satfile: 66 | for line in satfile: 67 | if line.split()[0] == "UNSAT": 68 | print("There is no solution") 69 | elif line.split()[0] == "SAT": 70 | pass 71 | else: 72 | assignment = [int(x) for x in line.split()] 73 | 74 | for i in digits: 75 | for j in digits: 76 | for k in digits: 77 | if varnum(i, j, k) in assignment: 78 | print(k, end="") 79 | break 80 | 81 | print("") 82 | 83 | 84 | -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week4/18_coping_with_np_completeness_1_introduction.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week4/18_coping_with_np_completeness_1_introduction.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week4/18_coping_with_np_completeness_2_special_cases.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week4/18_coping_with_np_completeness_2_special_cases.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week4/18_coping_with_np_completeness_3_exact_algorithms.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week4/18_coping_with_np_completeness_3_exact_algorithms.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week4/18_coping_with_np_completeness_4_approximation_algorithms.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week4/18_coping_with_np_completeness_4_approximation_algorithms.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week4/Programming Assignment: Programming Assignment 4/Programming Assignment: Programming Assignment 4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week4/Programming Assignment: Programming Assignment 4/Programming Assignment: Programming Assignment 4.pdf -------------------------------------------------------------------------------- /Advanced Algorithms and Complexity/Week5/Practice Programming Assignment: (Optional) Programming Assignment 5/Practice Programming Assignment: (Optional) Programming Assignment 5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Advanced Algorithms and Complexity/Week5/Practice Programming Assignment: (Optional) Programming Assignment 5/Practice Programming Assignment: (Optional) Programming Assignment 5.pdf -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week2/Program1.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def fibo(n): 4 | a = 0 5 | if n==0: 6 | return a 7 | b = 1 8 | if n==1: 9 | return b 10 | for i in range(2,n+1): 11 | c = a+b 12 | a = b 13 | b = c 14 | 15 | return c 16 | 17 | 18 | if __name__ == '__main__': 19 | n = int(input()) 20 | print(fibo(n)) 21 | 22 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week2/Program2.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def fibo(n): 4 | a = 0 5 | if n==0: 6 | return a 7 | b = 1 8 | if n==1: 9 | return b 10 | for i in range(2,n+1): 11 | c = (a+b)%10 12 | a = b 13 | b = c 14 | 15 | return c 16 | 17 | 18 | if __name__ == '__main__': 19 | n = int(input()) 20 | print(fibo(n)) 21 | 22 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week2/Program3.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def gcd(a, b): 4 | if a == 0 : 5 | return b 6 | return gcd(b%a, a) 7 | 8 | 9 | if __name__ == '__main__': 10 | a, b = map(int, input().split()) 11 | print(gcd(a, b)) 12 | 13 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week2/Program4.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def gcd(a, b): 4 | if a == 0 : 5 | return b 6 | return gcd(b%a, a) 7 | 8 | 9 | if __name__ == '__main__': 10 | a, b = map(int, input().split()) 11 | print((a*b)//gcd(a, b)) 12 | 13 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week2/Program5.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def fibo(n, m): 4 | a = 0 5 | b = 1 6 | 7 | p = [a%m, b%m] 8 | 9 | while True: 10 | c = a + b 11 | a = b 12 | b = c 13 | p.append(c%m) 14 | if p[-2]==0 and p[-1]==1: 15 | break 16 | 17 | p = p[:-2] 18 | lenPeriod = len(p) 19 | 20 | #print(p) 21 | #print(lenPeriod) 22 | 23 | return p[n%lenPeriod] 24 | 25 | 26 | if __name__ == '__main__': 27 | n, m = map(int, input().split()) 28 | print(fibo(n, m)) 29 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week2/Program6.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def fibo(n): 4 | a = 0 5 | if n == 0: 6 | return 0 7 | 8 | b = 1 9 | if n == 1: 10 | return 1 11 | 12 | p = [0, 1] 13 | while True: 14 | c = a + b 15 | a = b 16 | b = c 17 | p.append((c)%10) 18 | if len(p)>59: 19 | break 20 | 21 | period = len(p) 22 | 23 | #print(p) 24 | #print(period) 25 | 26 | q = n//period 27 | r = n%period 28 | 29 | return (q*sum(p) + sum(p[:r+1]))%10 30 | 31 | 32 | if __name__ == '__main__': 33 | n = int(input()) 34 | print(fibo(n)) 35 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week2/Program7.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def fibo(n): 4 | a = 0 5 | if n == 0: 6 | return 0 7 | 8 | b = 1 9 | if n == 1: 10 | return 1 11 | 12 | p = [0, 1] 13 | while True: 14 | c = a + b 15 | a = b 16 | b = c 17 | p.append((c)%10) 18 | if len(p)>59: 19 | break 20 | 21 | period = len(p) 22 | 23 | #print(p) 24 | #print(period) 25 | 26 | q = n//period 27 | r = n%period 28 | 29 | return (q*sum(p) + sum(p[:r+1]))%10 30 | 31 | def find(m, n): 32 | return (fibo(n) - fibo(m-1))%10 33 | 34 | if __name__ == '__main__': 35 | m, n = map(int, input().split()) 36 | print(find(m, n)) 37 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week2/Program8.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def fibo(n): 4 | a = 0 5 | if n == 0: 6 | return 0 7 | 8 | b = 1 9 | if n == 1: 10 | return 1 11 | 12 | p = [0, 1] 13 | while True: 14 | c = a + b 15 | a = b 16 | b = c 17 | p.append((c*c)%10) 18 | if len(p)>29: 19 | break 20 | 21 | period = len(p) 22 | 23 | #print(p) 24 | #print(period) 25 | 26 | q = n//period 27 | r = n%period 28 | 29 | return (q*sum(p) + sum(p[:r+1]))%10 30 | 31 | 32 | if __name__ == '__main__': 33 | n = int(input()) 34 | print(fibo(n)) 35 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week2/Programming Assignment: Programming Assignment 2: Algorithmic Warm-up.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithmic Toolbox/Week2/Programming Assignment: Programming Assignment 2: Algorithmic Warm-up.pdf -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week3/Program1.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(m): 4 | c_10 = m//10 5 | m = m%10 6 | c_5 = m//5 7 | m = m%5 8 | c_1 = m 9 | 10 | return c_10 + c_5 + c_1 11 | 12 | if __name__ == '__main__': 13 | m = int(input()) 14 | print(solve(m)) 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week3/Program2.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(W, arr): 4 | arr.sort(reverse = True) 5 | value = [e[0] for e in arr] 6 | weight = [e[1] for e in arr] 7 | if weight[0]>=W: 8 | return W*value[0] 9 | if sum(weight)<=W: 10 | return sum([v*w for v, w in zip(value, weight)]) 11 | res = 0 12 | s = 0 13 | for i in range(len(weight)): 14 | if s+weight[i]>W: 15 | break 16 | else: 17 | s += weight[i] 18 | res += weight[i]*value[i] 19 | res += (W-s)*value[i] 20 | 21 | return res 22 | 23 | if __name__ == '__main__': 24 | n, W = map(int, input().split()) 25 | arr=[] 26 | for n0 in range(n): 27 | v, w = map(int, input().split()) 28 | arr.append([v/w, w]) 29 | print("%0.4f" %solve(W, arr)) 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week3/Program3.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(a, b): 4 | a.sort() 5 | b.sort() 6 | res = sum([i*j for i, j in zip(a, b)]) 7 | return res 8 | 9 | 10 | if __name__ == '__main__': 11 | n = int(input()) 12 | a = [int(i) for i in input().split()] 13 | b = [int(i) for i in input().split()] 14 | print(solve(a, b)) 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week3/Program4.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(arr): 4 | arr.sort() 5 | m = [] 6 | while arr: 7 | a = arr[0][0] 8 | b = arr[0][1] 9 | arr.remove(arr[0]) 10 | l = [] 11 | for i in range(len(arr)): 12 | _a = arr[i][0] 13 | _b = arr[i][1] 14 | if max(a, _a)<=min(b, _b): 15 | l.append(arr[i]) 16 | a = max(a, _a) 17 | b = min(b, _b) 18 | for e in l: 19 | arr.remove(e) 20 | m.append(b) 21 | 22 | print(len(m)) 23 | for e in m: 24 | print(e, end=" ") 25 | print() 26 | 27 | if __name__ == '__main__': 28 | n = int(input()) 29 | arr = [] 30 | for n0 in range(n): 31 | a, b = map(int, input().split()) 32 | arr.append([a, b]) 33 | solve(arr) 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week3/Program5.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | import math 4 | 5 | def solve(n): 6 | k = ((math.sqrt(1 + 8*n)) -1)/2 7 | k = int(k) 8 | print(k) 9 | s = 0 10 | for i in range(k-1): 11 | print(i+1, end=" ") 12 | s += i+1 13 | print(n-s) 14 | 15 | if __name__ == '__main__': 16 | n = int(input()) 17 | solve(n) 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week3/Program6.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank, setSize; // remember: vi is vector 150 | int numSets; 151 | public: 152 | UnionFind(int N) { 153 | setSize.assign(N, 1); numSets = N; rank.assign(N, 0); 154 | p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } 155 | int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } 156 | bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } 157 | void unionSet(int i, int j) { 158 | if (!isSameSet(i, j)) { numSets--; 159 | int x = findSet(i), y = findSet(j); 160 | // rank is used to keep the tree short 161 | if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } 162 | else { p[x] = y; setSize[y] += setSize[x]; 163 | if (rank[x] == rank[y]) rank[y]++; } } } 164 | int numDisjointSets() { return numSets; } 165 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 166 | }; 167 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 168 | // Code to find "GCD" of two numbers 169 | int gcd(int a, int b){ 170 | if(a==0) 171 | return b; 172 | return gcd(b%a, a); 173 | } 174 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 175 | // Code to find the prime numbers using sieve of Erathosthenes 176 | vector SieveOfErathosthenes(int n){ 177 | vi res; 178 | vi prime(n+1, 1); 179 | int p = 2; 180 | while(p*p <= n){ 181 | if(prime[p]){ 182 | for(int i=2*p; i 0){ 200 | // If y is odd, multiply x with result 201 | if (y & 1) 202 | res = (res*x) % p; 203 | // y must be even now 204 | y = y>>1; // y = y/2 205 | x = (x*x) % p; 206 | } 207 | return res; 208 | } 209 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 210 | // Code for Graph Algorithms 211 | vector AdjList; 212 | vi dfs_num; 213 | int numCC; 214 | 215 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 216 | //printf(" %d", u); // this vertex is visited 217 | dfs_num[u] = 1; // important step: we mark this vertex as visited 218 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 219 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 220 | if (dfs_num[v.first] == 0) // important check to avoid cycle 221 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 222 | } } 223 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 224 | //=================================================================================================================================================== 225 | // Your Code starts here 226 | 227 | int myCompare(string X, string Y){ 228 | string XY = X.append(Y); 229 | string YX = Y.append(X); 230 | return XY.compare(YX) > 0 ? 1 : 0; 231 | } 232 | 233 | int main(){ 234 | 235 | int n; cin>>n; 236 | vector a(n); 237 | for(int i=0; i>a[i]; 239 | 240 | sort(a.begin(), a.end(), myCompare); 241 | for(auto e : a) 242 | cout<k: 13 | return True 14 | return False 15 | 16 | 17 | if __name__ == '__main__': 18 | n = int(input()) 19 | a = [int(i) for i in input().split()] 20 | if solve(n, a): 21 | print("1") 22 | else: 23 | print("0") 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week4/Program3.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | import collections 4 | 5 | def solve(n, a): 6 | a.sort() 7 | print(" ".join([str(i) for i in a])) 8 | 9 | 10 | if __name__ == '__main__': 11 | n = int(input()) 12 | a = [int(i) for i in input().split()] 13 | solve(n, a) 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week4/week4_divide_and_conquer.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithmic Toolbox/Week4/week4_divide_and_conquer.pdf -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week5/Program1.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(n): 4 | dp = [0]*1000 5 | dp[0] = 0 6 | dp[1] = 1 7 | dp[2] = 2 8 | dp[3] = 1 9 | dp[4] = 1 10 | for i in range(5, n+1): 11 | dp[i] = 1 + min(dp[i-1], dp[i-3], dp[i-4]) 12 | print(dp[n]) 13 | 14 | 15 | if __name__ == '__main__': 16 | n = int(input()) 17 | solve(n) 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week5/Program2.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(n): 4 | dp = [[0, 0] for i in range(10**6 + 1)] 5 | dp[2][0], dp[2][1] = 1, 1 6 | dp[3][0], dp[3][1] = 1, 1 7 | for i in range(4, n+1): 8 | 9 | b0, c0 = -1, -1 10 | a0, a1 = dp[i-1][0], i-1 11 | if i%2 == 0: 12 | b0, b1 = dp[i//2][0], i//2 13 | if i%3 == 0: 14 | c0, c1 = dp[i//3][0], i//3 15 | 16 | if b0==-1 and c0==-1: 17 | dp[i][0], dp[i][1] = a0 + 1, a1 18 | elif b0==-1 and c0!=-1: 19 | if a0<=c0: 20 | k = a1 21 | else: 22 | k = c1 23 | dp[i][0], dp[i][1] = min(a0, c0) + 1, k 24 | elif c0==-1 and b0!=-1: 25 | if a0<=b0: 26 | k = a1 27 | else: 28 | k = b1 29 | dp[i][0], dp[i][1] = min(a0, b0) + 1, k 30 | elif b0!=-1 and c0!=-1: 31 | if a0<=b0 and a0<=c0: 32 | k = a1 33 | elif b0<=a0 and b0<=c0: 34 | k = b1 35 | elif c0<=a0 and c0<=b0: 36 | k = c1 37 | dp[i][0], dp[i][1] = min(a0, b0, c0) + 1, k 38 | 39 | print(dp[n][0]) 40 | res = dp[:n+1] 41 | l = [] 42 | i = n 43 | while i>1: 44 | l.append(i) 45 | i = res[i][1] 46 | l.append(1) 47 | l = l[::-1] 48 | print(" ".join([str(i) for i in l])) 49 | 50 | 51 | if __name__ == '__main__': 52 | n = int(input()) 53 | solve(n) 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week5/Program3.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(s1, s2): 4 | l1 = [None] + list(s1) 5 | m = len(l1) 6 | l2 = [None] + list(s2) 7 | n = len(l2) 8 | dp = [[0 for j in range(n)] for i in range(m)] 9 | for i in range(n): 10 | dp[0][i] = i 11 | for i in range(m): 12 | dp[i][0] = i 13 | 14 | for i in range(1, m): 15 | for j in range(1, n): 16 | if l1[i] == l2[j]: 17 | dp[i][j] = dp[i-1][j-1] 18 | else: 19 | dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1 20 | print(dp[m-1][n-1]) 21 | 22 | 23 | if __name__ == '__main__': 24 | s1 = input() 25 | s2 = input() 26 | solve(s1, s2) 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week5/Program4.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | n = int(input()) 4 | a = [int(i) for i in input().split()] 5 | m = int(input()) 6 | b = [int(i) for i in input().split()] 7 | 8 | dp = [[0 for j in range(m+1)] for i in range(n+1)] 9 | 10 | for i in range(1, n+1): 11 | for j in range(1, m+1): 12 | if a[i-1] == b[j-1]: 13 | dp[i][j] = dp[i-1][j-1] + 1 14 | else: 15 | dp[i][j] = max(dp[i][j-1], dp[i-1][j]) 16 | print(dp[-1][-1]) 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week5/Program5.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | n = int(input()) 4 | a = [int(i) for i in input().split()] 5 | m = int(input()) 6 | b = [int(i) for i in input().split()] 7 | l = int(input()) 8 | c = [int(i) for i in input().split()] 9 | 10 | dp = [[[0 for k in range(l+1)] for j in range(m+1)] for i in range(n+1)] 11 | 12 | for i in range(1, n+1): 13 | for j in range(1, m+1): 14 | for k in range(1, l+1): 15 | if a[i-1] == b[j-1] == c[k-1]: 16 | dp[i][j][k] = dp[i-1][j-1][k-1] + 1 17 | else: 18 | dp[i][j][k] = max(dp[i-1][j][k], dp[i][j-1][k], dp[i][j][k-1]) 19 | print(dp[-1][-1][-1]) 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week5/week5_dynamic_programming1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithmic Toolbox/Week5/week5_dynamic_programming1.pdf -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week6/Program1.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(W, w): 4 | w.sort() 5 | dp = [[0 for j in range(W+1)] for i in range(len(w))] 6 | for j in range(1, W+1): 7 | if j >= w[0]: 8 | dp[0][j] = w[0] 9 | for i in range(1, len(w)): 10 | for j in range(1, W+1): 11 | if j >= w[i]: 12 | dp[i][j] = max(dp[i-1][j], w[i] + dp[i-1][j-w[i]]) 13 | else: 14 | dp[i][j] = dp[i-1][j] 15 | #print(dp) 16 | print(dp[-1][-1]) 17 | 18 | 19 | if __name__ == '__main__': 20 | W, n = map(int, input().split()) 21 | w = [int(i) for i in input().split()] 22 | solve(W, w) 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week6/Program2.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(n, v): 4 | #if sum(v) % 3 != 0: 5 | # return False 6 | res = [] 7 | values = [] 8 | s = sum(v)//3 9 | for i in range(2**n): 10 | bit = [0 for i in range(n)] 11 | k = i 12 | p = n-1 13 | while k!=0: 14 | bit[p] = (k%2) 15 | k = k//2 16 | p -= 1 17 | 18 | #print(bit) 19 | 20 | val = [a*b for a, b in zip(v, bit)] 21 | #print(val) 22 | 23 | if sum(val) == s: 24 | res.append(bit) 25 | values.append(i) 26 | #print(res) 27 | #print(values) 28 | if len(res)<3: 29 | return False 30 | for i in range(len(values)-2): 31 | for j in range(i+1, len(values)-1): 32 | for k in range(i+2, len(values)): 33 | a = values[i] 34 | b = values[j] 35 | c = values[k] 36 | if a^b^c == (2**n-1): 37 | return True 38 | return False 39 | 40 | 41 | if __name__ == '__main__': 42 | n = int(input()) 43 | v = [int(i) for i in input().split()] 44 | if solve(n, v): 45 | print("1") 46 | else: 47 | print("0") 48 | 49 | -------------------------------------------------------------------------------- /Algorithmic Toolbox/Week6/week6_dynamic_programming2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithmic Toolbox/Week6/week6_dynamic_programming2.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week1/09_graph_decomposition_1_basics.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week1/09_graph_decomposition_1_basics.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week1/09_graph_decomposition_2_representations.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week1/09_graph_decomposition_2_representations.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week1/09_graph_decomposition_3_explore.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week1/09_graph_decomposition_3_explore.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week1/09_graph_decomposition_4_connectivity.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week1/09_graph_decomposition_4_connectivity.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week1/09_graph_decomposition_5_pre-and-post-orders.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week1/09_graph_decomposition_5_pre-and-post-orders.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week1/Programming Assignment: Programming Assignment 1: Decomposition of Graphs/Program1.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank, setSize; // remember: vi is vector 150 | int numSets; 151 | public: 152 | UnionFind(int N) { 153 | setSize.assign(N, 1); numSets = N; rank.assign(N, 0); 154 | p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } 155 | int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } 156 | bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } 157 | void unionSet(int i, int j) { 158 | if (!isSameSet(i, j)) { numSets--; 159 | int x = findSet(i), y = findSet(j); 160 | // rank is used to keep the tree short 161 | if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } 162 | else { p[x] = y; setSize[y] += setSize[x]; 163 | if (rank[x] == rank[y]) rank[y]++; } } } 164 | int numDisjointSets() { return numSets; } 165 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 166 | }; 167 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 168 | // Code to find "GCD" of two numbers 169 | int gcd(int a, int b){ 170 | if(a==0) 171 | return b; 172 | return gcd(b%a, a); 173 | } 174 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 175 | // Code to find the prime numbers using sieve of Erathosthenes 176 | vector SieveOfErathosthenes(int n){ 177 | vi res; 178 | vi prime(n+1, 1); 179 | int p = 2; 180 | while(p*p <= n){ 181 | if(prime[p]){ 182 | for(int i=2*p; i 0){ 200 | // If y is odd, multiply x with result 201 | if (y & 1) 202 | res = (res*x) % p; 203 | // y must be even now 204 | y = y>>1; // y = y/2 205 | x = (x*x) % p; 206 | } 207 | return res; 208 | } 209 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 210 | // Code for Graph Algorithms 211 | vector AdjList; 212 | vi dfs_num; 213 | int numCC; 214 | 215 | int isReachable = 0; 216 | int toReach = 0; 217 | 218 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 219 | //printf(" %d", u); // this vertex is visited 220 | dfs_num[u] = 1; if(toReach == u) isReachable = 1; // important step: we mark this vertex as visited 221 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 222 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 223 | if (dfs_num[v.first] == 0) // important check to avoid cycle 224 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 225 | } } 226 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 227 | //=================================================================================================================================================== 228 | // Your Code starts here 229 | int main(){ 230 | 231 | int n, m; cin>>n>>m; 232 | AdjList.assign(n+1, vii()); 233 | 234 | for(int i=0; i>u>>v; 236 | AdjList[u].push_back(ii(v, 0)); 237 | AdjList[v].push_back(ii(u, 0)); 238 | } 239 | 240 | int u, v; cin>>u>>v; 241 | 242 | dfs_num.assign(n+1, 0); 243 | toReach = v; 244 | 245 | dfs(u); 246 | 247 | cout< 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank, setSize; // remember: vi is vector 150 | int numSets; 151 | public: 152 | UnionFind(int N) { 153 | setSize.assign(N, 1); numSets = N; rank.assign(N, 0); 154 | p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } 155 | int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } 156 | bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } 157 | void unionSet(int i, int j) { 158 | if (!isSameSet(i, j)) { numSets--; 159 | int x = findSet(i), y = findSet(j); 160 | // rank is used to keep the tree short 161 | if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } 162 | else { p[x] = y; setSize[y] += setSize[x]; 163 | if (rank[x] == rank[y]) rank[y]++; } } } 164 | int numDisjointSets() { return numSets; } 165 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 166 | }; 167 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 168 | // Code to find "GCD" of two numbers 169 | int gcd(int a, int b){ 170 | if(a==0) 171 | return b; 172 | return gcd(b%a, a); 173 | } 174 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 175 | // Code to find the prime numbers using sieve of Erathosthenes 176 | vector SieveOfErathosthenes(int n){ 177 | vi res; 178 | vi prime(n+1, 1); 179 | int p = 2; 180 | while(p*p <= n){ 181 | if(prime[p]){ 182 | for(int i=2*p; i 0){ 200 | // If y is odd, multiply x with result 201 | if (y & 1) 202 | res = (res*x) % p; 203 | // y must be even now 204 | y = y>>1; // y = y/2 205 | x = (x*x) % p; 206 | } 207 | return res; 208 | } 209 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 210 | // Code for Graph Algorithms 211 | vector AdjList; 212 | vi dfs_num; 213 | int numCC = 0; 214 | 215 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 216 | //printf(" %d", u); // this vertex is visited 217 | dfs_num[u] = 1; // important step: we mark this vertex as visited 218 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 219 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 220 | if (dfs_num[v.first] == 0) // important check to avoid cycle 221 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 222 | } } 223 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 224 | //=================================================================================================================================================== 225 | // Your Code starts here 226 | int main(){ 227 | 228 | int n, m; cin>>n>>m; 229 | AdjList.assign(n+1, vii()); 230 | for(int i=0; i>u>>v; 232 | AdjList[u].push_back(ii(v, 0)); 233 | AdjList[v].push_back(ii(u, 0)); 234 | } 235 | 236 | dfs_num.assign(n+1, 0); 237 | for(int u=1; u 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank, setSize; // remember: vi is vector 150 | int numSets; 151 | public: 152 | UnionFind(int N) { 153 | setSize.assign(N, 1); numSets = N; rank.assign(N, 0); 154 | p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } 155 | int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } 156 | bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } 157 | void unionSet(int i, int j) { 158 | if (!isSameSet(i, j)) { numSets--; 159 | int x = findSet(i), y = findSet(j); 160 | // rank is used to keep the tree short 161 | if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } 162 | else { p[x] = y; setSize[y] += setSize[x]; 163 | if (rank[x] == rank[y]) rank[y]++; } } } 164 | int numDisjointSets() { return numSets; } 165 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 166 | }; 167 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 168 | // Code to find "GCD" of two numbers 169 | int gcd(int a, int b){ 170 | if(a==0) 171 | return b; 172 | return gcd(b%a, a); 173 | } 174 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 175 | // Code to find the prime numbers using sieve of Erathosthenes 176 | vector SieveOfErathosthenes(int n){ 177 | vi res; 178 | vi prime(n+1, 1); 179 | int p = 2; 180 | while(p*p <= n){ 181 | if(prime[p]){ 182 | for(int i=2*p; i 0){ 200 | // If y is odd, multiply x with result 201 | if (y & 1) 202 | res = (res*x) % p; 203 | // y must be even now 204 | y = y>>1; // y = y/2 205 | x = (x*x) % p; 206 | } 207 | return res; 208 | } 209 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 210 | // Code for Graph Algorithms 211 | vector AdjList; 212 | vi dfs_num; 213 | int numCC; 214 | 215 | vi topoSort; 216 | 217 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 218 | //printf(" %d", u); // this vertex is visited 219 | dfs_num[u] = 1; // important step: we mark this vertex as visited 220 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 221 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 222 | if (dfs_num[v.first] == 0) // important check to avoid cycle 223 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 224 | } 225 | topoSort.push_back(u); 226 | } 227 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 228 | //=================================================================================================================================================== 229 | // Your Code starts here 230 | int main(){ 231 | 232 | int n, m; cin>>n>>m; 233 | AdjList.assign(n+1, vii()); 234 | for(int i=0; i>u>>v; 236 | AdjList[u].push_back(ii(v, 0)); 237 | } 238 | 239 | dfs_num.assign(n+1, 0); 240 | for(int u=1; u 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank, setSize; // remember: vi is vector 150 | int numSets; 151 | public: 152 | UnionFind(int N) { 153 | setSize.assign(N, 1); numSets = N; rank.assign(N, 0); 154 | p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } 155 | int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } 156 | bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } 157 | void unionSet(int i, int j) { 158 | if (!isSameSet(i, j)) { numSets--; 159 | int x = findSet(i), y = findSet(j); 160 | // rank is used to keep the tree short 161 | if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } 162 | else { p[x] = y; setSize[y] += setSize[x]; 163 | if (rank[x] == rank[y]) rank[y]++; } } } 164 | int numDisjointSets() { return numSets; } 165 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 166 | }; 167 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 168 | // Code to find "GCD" of two numbers 169 | int gcd(int a, int b){ 170 | if(a==0) 171 | return b; 172 | return gcd(b%a, a); 173 | } 174 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 175 | // Code to find the prime numbers using sieve of Erathosthenes 176 | vector SieveOfErathosthenes(int n){ 177 | vi res; 178 | vi prime(n+1, 1); 179 | int p = 2; 180 | while(p*p <= n){ 181 | if(prime[p]){ 182 | for(int i=2*p; i 0){ 200 | // If y is odd, multiply x with result 201 | if (y & 1) 202 | res = (res*x) % p; 203 | // y must be even now 204 | y = y>>1; // y = y/2 205 | x = (x*x) % p; 206 | } 207 | return res; 208 | } 209 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 210 | // Code for Graph Algorithms 211 | vector AdjList; 212 | vi dfs_num; 213 | int numCC; 214 | 215 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 216 | //printf(" %d", u); // this vertex is visited 217 | dfs_num[u] = 1; // important step: we mark this vertex as visited 218 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 219 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 220 | if (dfs_num[v.first] == 0) // important check to avoid cycle 221 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 222 | } } 223 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 224 | //=================================================================================================================================================== 225 | // Your Code starts here 226 | int main(){ 227 | 228 | int n, m; cin>>n>>m; 229 | AdjList.assign(n+1, vii()); 230 | for(int i=0; i>u>>v; 232 | AdjList[u].push_back(ii(v, 1)); 233 | AdjList[v].push_back(ii(u, 1)); 234 | } 235 | int u, v; cin>>u>>v; 236 | 237 | vi dist(n+1, INF); 238 | queue q; q.push(u); dist[u] = 0; 239 | while(!q.empty()){ 240 | int u = q.front(); q.pop(); 241 | for(int j=0; j 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank, setSize; // remember: vi is vector 150 | int numSets; 151 | public: 152 | UnionFind(int N) { 153 | setSize.assign(N, 1); numSets = N; rank.assign(N, 0); 154 | p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } 155 | int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } 156 | bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } 157 | void unionSet(int i, int j) { 158 | if (!isSameSet(i, j)) { numSets--; 159 | int x = findSet(i), y = findSet(j); 160 | // rank is used to keep the tree short 161 | if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } 162 | else { p[x] = y; setSize[y] += setSize[x]; 163 | if (rank[x] == rank[y]) rank[y]++; } } } 164 | int numDisjointSets() { return numSets; } 165 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 166 | }; 167 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 168 | // Code to find "GCD" of two numbers 169 | int gcd(int a, int b){ 170 | if(a==0) 171 | return b; 172 | return gcd(b%a, a); 173 | } 174 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 175 | // Code to find the prime numbers using sieve of Erathosthenes 176 | vector SieveOfErathosthenes(int n){ 177 | vi res; 178 | vi prime(n+1, 1); 179 | int p = 2; 180 | while(p*p <= n){ 181 | if(prime[p]){ 182 | for(int i=2*p; i 0){ 200 | // If y is odd, multiply x with result 201 | if (y & 1) 202 | res = (res*x) % p; 203 | // y must be even now 204 | y = y>>1; // y = y/2 205 | x = (x*x) % p; 206 | } 207 | return res; 208 | } 209 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 210 | // Code for Graph Algorithms 211 | vector AdjList; 212 | vi dfs_num; 213 | int numCC; 214 | 215 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 216 | //printf(" %d", u); // this vertex is visited 217 | dfs_num[u] = 1; // important step: we mark this vertex as visited 218 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 219 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 220 | if (dfs_num[v.first] == 0) // important check to avoid cycle 221 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 222 | } } 223 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 224 | //=================================================================================================================================================== 225 | // Your Code starts here 226 | int main(){ 227 | 228 | int n, m; cin>>n>>m; 229 | AdjList.assign(n+1, vii()); 230 | for(int i=0; i>u>>v; 232 | AdjList[u].push_back(ii(v, 1)); 233 | AdjList[v].push_back(ii(u, 1)); 234 | } 235 | 236 | int isBipartite = 1; int u=1; 237 | 238 | vi dist(n+1, INF); 239 | queue q; q.push(u); dist[u] = 0; 240 | while(!q.empty()){ 241 | int u = q.front(); q.pop(); 242 | for(int j=0; j 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank, setSize; // remember: vi is vector 150 | int numSets; 151 | public: 152 | UnionFind(int N) { 153 | setSize.assign(N, 1); numSets = N; rank.assign(N, 0); 154 | p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } 155 | int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } 156 | bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } 157 | void unionSet(int i, int j) { 158 | if (!isSameSet(i, j)) { numSets--; 159 | int x = findSet(i), y = findSet(j); 160 | // rank is used to keep the tree short 161 | if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } 162 | else { p[x] = y; setSize[y] += setSize[x]; 163 | if (rank[x] == rank[y]) rank[y]++; } } } 164 | int numDisjointSets() { return numSets; } 165 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 166 | }; 167 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 168 | // Code to find "GCD" of two numbers 169 | int gcd(int a, int b){ 170 | if(a==0) 171 | return b; 172 | return gcd(b%a, a); 173 | } 174 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 175 | // Code to find the prime numbers using sieve of Erathosthenes 176 | vector SieveOfErathosthenes(int n){ 177 | vi res; 178 | vi prime(n+1, 1); 179 | int p = 2; 180 | while(p*p <= n){ 181 | if(prime[p]){ 182 | for(int i=2*p; i 0){ 200 | // If y is odd, multiply x with result 201 | if (y & 1) 202 | res = (res*x) % p; 203 | // y must be even now 204 | y = y>>1; // y = y/2 205 | x = (x*x) % p; 206 | } 207 | return res; 208 | } 209 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 210 | // Code for Graph Algorithms 211 | vector AdjList; 212 | vi dfs_num; 213 | int numCC; 214 | 215 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 216 | //printf(" %d", u); // this vertex is visited 217 | dfs_num[u] = 1; // important step: we mark this vertex as visited 218 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 219 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 220 | if (dfs_num[v.first] == 0) // important check to avoid cycle 221 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 222 | } } 223 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 224 | //=================================================================================================================================================== 225 | // Your Code starts here 226 | int main(){ 227 | 228 | int n, m; cin>>n>>m; 229 | AdjList.assign(n+1, vii()); 230 | for(int i=0; i>u>>v>>w; 232 | AdjList[u].push_back(ii(v, w)); 233 | } 234 | int u, v; cin>>u>>v; 235 | 236 | vi dist(n+1, INF); dist[u] = 0; 237 | priority_queue, greater > pq; pq.push(ii(0, u)); 238 | 239 | while(!pq.empty()){ 240 | ii front = pq.top(); pq.pop(); 241 | int d = front.first; int u = front.second; 242 | if(d>dist[u]) 243 | continue; 244 | for(int j=0; j 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank, setSize; // remember: vi is vector 150 | int numSets; 151 | public: 152 | UnionFind(int N) { 153 | setSize.assign(N, 1); numSets = N; rank.assign(N, 0); 154 | p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } 155 | int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } 156 | bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } 157 | void unionSet(int i, int j) { 158 | if (!isSameSet(i, j)) { numSets--; 159 | int x = findSet(i), y = findSet(j); 160 | // rank is used to keep the tree short 161 | if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } 162 | else { p[x] = y; setSize[y] += setSize[x]; 163 | if (rank[x] == rank[y]) rank[y]++; } } } 164 | int numDisjointSets() { return numSets; } 165 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 166 | }; 167 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 168 | // Code to find "GCD" of two numbers 169 | int gcd(int a, int b){ 170 | if(a==0) 171 | return b; 172 | return gcd(b%a, a); 173 | } 174 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 175 | // Code to find the prime numbers using sieve of Erathosthenes 176 | vector SieveOfErathosthenes(int n){ 177 | vi res; 178 | vi prime(n+1, 1); 179 | int p = 2; 180 | while(p*p <= n){ 181 | if(prime[p]){ 182 | for(int i=2*p; i 0){ 200 | // If y is odd, multiply x with result 201 | if (y & 1) 202 | res = (res*x) % p; 203 | // y must be even now 204 | y = y>>1; // y = y/2 205 | x = (x*x) % p; 206 | } 207 | return res; 208 | } 209 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 210 | // Code for Graph Algorithms 211 | vector AdjList; 212 | vi dfs_num; 213 | int numCC; 214 | 215 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 216 | //printf(" %d", u); // this vertex is visited 217 | dfs_num[u] = 1; // important step: we mark this vertex as visited 218 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 219 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 220 | if (dfs_num[v.first] == 0) // important check to avoid cycle 221 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 222 | } } 223 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 224 | //=================================================================================================================================================== 225 | // Your Code starts here 226 | int main(){ 227 | 228 | int n, m; cin>>n>>m; 229 | AdjList.assign(n+1, vii()); 230 | for(int i=0; i>u>>v>>w; 232 | AdjList[u].push_back(ii(v, w)); 233 | } 234 | 235 | vi dist(n+1, INF); dist[1] = 0; 236 | 237 | for(int i=0; i dist[u] + v.second) 249 | hasNegativeCycle = 1; 250 | } 251 | 252 | cout< distance[u] + cost[u][i]: 16 | distance[v] = distance[u] + cost[u][i] 17 | reachable[v] = 1 18 | i += 1 19 | 20 | for u in range(vertices): 21 | i = 0 # magic variable 22 | for v in adj[u]: 23 | if distance[v] > distance[u] + cost[u][i]: 24 | if v not in queue: 25 | queue.append(v) 26 | i += 1 27 | 28 | while queue: 29 | u = queue.pop(0) 30 | visited[u] = True 31 | shortest[u] = 0 32 | for v in adj[u]: 33 | if not visited[v] and v not in queue: 34 | queue.append(v) 35 | 36 | 37 | if __name__ == '__main__': 38 | user_input = sys.stdin.read() 39 | data = list(map(int, user_input.split())) 40 | n, m = data[0:2] 41 | data = data[2:] 42 | edges = list( 43 | zip(zip(data[0:(3 * m):3], data[1:(3 * m):3]), data[2:(3 * m):3])) 44 | data = data[3 * m:] 45 | adj = [[] for _ in range(n)] 46 | cost = [[] for _ in range(n)] 47 | for ((a, b), w) in edges: 48 | adj[a - 1].append(b - 1) 49 | cost[a - 1].append(w) 50 | s = data[0] 51 | s -= 1 52 | distance = [float('inf')] * n 53 | reachable = [0] * n 54 | shortest = [1] * n 55 | shortet_paths(adj, cost, s, distance, reachable, shortest) 56 | for x in range(n): 57 | if reachable[x] == 0: 58 | print('*') 59 | elif shortest[x] == 0: 60 | print('-') 61 | else: 62 | print(distance[x]) 63 | -------------------------------------------------------------------------------- /Algorithms on Graphs/Week5/11_1_minimum_spanning_trees.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week5/11_1_minimum_spanning_trees.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week5/Programming Assignment: Programming Assignment 5: Minimum Spanning Trees/Programming Assignment: Programming Assignment 5: Minimum Spanning Trees.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week5/Programming Assignment: Programming Assignment 5: Minimum Spanning Trees/Programming Assignment: Programming Assignment 5: Minimum Spanning Trees.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week6/19_advanced_shortest_paths_1_bidirectional_dijkstra.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week6/19_advanced_shortest_paths_1_bidirectional_dijkstra.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week6/19_advanced_shortest_paths_2_A_star.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week6/19_advanced_shortest_paths_2_A_star.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week6/19_advanced_shortest_paths_3_contraction_hierarchies.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week6/19_advanced_shortest_paths_3_contraction_hierarchies.pdf -------------------------------------------------------------------------------- /Algorithms on Graphs/Week6/Practice Programming Assignment: Advanced Shortest Paths/Practice Programming Assignment: Advanced Shortest Paths.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Graphs/Week6/Practice Programming Assignment: Advanced Shortest Paths/Practice Programming Assignment: Advanced Shortest Paths.pdf -------------------------------------------------------------------------------- /Algorithms on Strings/Week1/Practice Quiz: Tries and Suffix Trees.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week1/Practice Quiz: Tries and Suffix Trees.png -------------------------------------------------------------------------------- /Algorithms on Strings/Week1/Programming Assignment: Programming Assignment 1/Program1.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(patterns): 4 | 5 | node = ['#', False, []] # key, end, list 6 | trie = [node] 7 | counter = 0 # keeps track of the number of nodes 8 | for pattern in patterns: 9 | curr = 0 10 | for i in range(len(pattern)): 11 | c = pattern[i] 12 | found = False 13 | for j in range(len(trie[curr][2])): 14 | if trie[(trie[curr][2])[j]][0] == c: 15 | curr = trie[curr][2][j] 16 | found = True 17 | break 18 | if not found: 19 | counter += 1 20 | trie.append([c, False, []]) 21 | trie[curr][2].append(counter) 22 | curr = counter 23 | if i == len(pattern)-1: 24 | trie[curr][1] = True 25 | 26 | #print(trie) 27 | 28 | for i in range(len(trie)): 29 | u = i 30 | for v in trie[u][2]: 31 | print(str(u)+'->'+str(v)+':'+str(trie[v][0])) 32 | 33 | 34 | 35 | if __name__ == '__main__': 36 | n = int(input()) 37 | patterns = [] 38 | for n0 in range(n): 39 | pattern = input() 40 | patterns.append(pattern) 41 | solve(patterns) 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /Algorithms on Strings/Week1/Programming Assignment: Programming Assignment 1/Program2.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def find(text, trie): 4 | res = [] 5 | for i in range(len(text)): 6 | curr = 0 7 | j = i 8 | present = False 9 | 10 | while True: 11 | p = curr 12 | for k in range(len(trie[curr][2])): 13 | if trie[(trie[curr][2])[k]][0] == text[j]: 14 | curr = (trie[curr][2])[k] 15 | present = trie[curr][1] 16 | j += 1 17 | break 18 | 19 | if present: 20 | res.append(i) 21 | break 22 | 23 | if j>=len(text): 24 | break 25 | 26 | if p == curr: 27 | break 28 | 29 | return res 30 | 31 | def solve(text, patterns): 32 | 33 | node = ['#', False, []] # key, end, list 34 | trie = [node] 35 | counter = 0 # keeps track of the number of nodes 36 | for pattern in patterns: 37 | curr = 0 38 | for i in range(len(pattern)): 39 | c = pattern[i] 40 | found = False 41 | for j in range(len(trie[curr][2])): 42 | if trie[(trie[curr][2])[j]][0] == c: 43 | curr = trie[curr][2][j] 44 | found = True 45 | break 46 | if not found: 47 | counter += 1 48 | trie.append([c, False, []]) 49 | trie[curr][2].append(counter) 50 | curr = counter 51 | if i == len(pattern)-1: 52 | trie[curr][1] = True 53 | 54 | #print(trie) 55 | 56 | for e in find(text, trie): 57 | print(e, end=' ') 58 | print() 59 | 60 | 61 | 62 | if __name__ == '__main__': 63 | text = input() 64 | n = int(input()) 65 | patterns = [] 66 | for n0 in range(n): 67 | pattern = input() 68 | patterns.append(pattern) 69 | solve(text, patterns) 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /Algorithms on Strings/Week1/Programming Assignment: Programming Assignment 1/Program3.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def find(text, trie): 4 | res = [] 5 | for i in range(len(text)): 6 | curr = 0 7 | j = i 8 | present = False 9 | 10 | while True: 11 | p = curr 12 | for k in range(len(trie[curr][2])): 13 | if trie[(trie[curr][2])[k]][0] == text[j]: 14 | curr = (trie[curr][2])[k] 15 | present = trie[curr][1] 16 | j += 1 17 | break 18 | 19 | if present: 20 | res.append(i) 21 | break 22 | 23 | if j>=len(text): 24 | break 25 | 26 | if p == curr: 27 | break 28 | 29 | return res 30 | 31 | def solve(text, patterns): 32 | 33 | node = ['#', False, []] # key, end, list 34 | trie = [node] 35 | counter = 0 # keeps track of the number of nodes 36 | for pattern in patterns: 37 | curr = 0 38 | for i in range(len(pattern)): 39 | c = pattern[i] 40 | found = False 41 | for j in range(len(trie[curr][2])): 42 | if trie[(trie[curr][2])[j]][0] == c: 43 | curr = trie[curr][2][j] 44 | found = True 45 | break 46 | if not found: 47 | counter += 1 48 | trie.append([c, False, []]) 49 | trie[curr][2].append(counter) 50 | curr = counter 51 | if i == len(pattern)-1: 52 | trie[curr][1] = True 53 | 54 | #print(trie) 55 | 56 | for e in find(text, trie): 57 | print(e, end=' ') 58 | print() 59 | 60 | 61 | 62 | if __name__ == '__main__': 63 | text = input() 64 | n = int(input()) 65 | patterns = [] 66 | for n0 in range(n): 67 | pattern = input() 68 | patterns.append(pattern) 69 | solve(text, patterns) 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /Algorithms on Strings/Week1/Programming Assignment: Programming Assignment 1/Programming Assignment: Programming Assignment 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week1/Programming Assignment: Programming Assignment 1/Programming Assignment: Programming Assignment 1.pdf -------------------------------------------------------------------------------- /Algorithms on Strings/Week1/Suffix-Trees-Reduced.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week1/Suffix-Trees-Reduced.pdf -------------------------------------------------------------------------------- /Algorithms on Strings/Week2/BWT-Suffix-Arrays-Reduced.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week2/BWT-Suffix-Arrays-Reduced.pdf -------------------------------------------------------------------------------- /Algorithms on Strings/Week2/Programming Assignment: Programming Assignment 2/Program1.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def BWT(text): 4 | 5 | n = len(text) 6 | text = text + text 7 | 8 | l = [] 9 | for i in range(n): 10 | l.append(text[i:i+n]) 11 | 12 | l.sort() 13 | 14 | res = '' 15 | for s in l: 16 | res += s[-1] 17 | 18 | return res 19 | 20 | 21 | if __name__ == "__main__": 22 | 23 | text = input() 24 | print(BWT(text)) 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Algorithms on Strings/Week2/Programming Assignment: Programming Assignment 2/Program4.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def SortCharacters(S): 4 | 5 | order = [0 for i in range(len(S))] 6 | count = [0 for i in range(256)] 7 | 8 | for i in range(len(S)): 9 | count[ord(S[i])] += 1 10 | 11 | for j in range(1, 256): 12 | count[j] += count[j-1] 13 | 14 | for i in range(len(S)-1, -1, -1): 15 | c = ord(S[i]) 16 | count[c] -= 1 17 | order[count[c]] = i 18 | 19 | return order 20 | 21 | 22 | def ComputeCharClasses(S, order): 23 | 24 | Class = [0 for i in range(len(S))] 25 | Class[order[0]] = 0 26 | 27 | for i in range(1, len(S)): 28 | if S[order[i]] != S[order[i-1]]: 29 | Class[order[i]] = Class[order[i-1]] + 1 30 | else: 31 | Class[order[i]] = Class[order[i-1]] 32 | 33 | return Class 34 | 35 | 36 | def SortDoubled(S, L, order, Class): 37 | 38 | count = [0 for i in range(len(S))] 39 | newOrder = [0 for i in range(len(S))] 40 | 41 | for i in range(len(S)): 42 | count[Class[i]] += 1 43 | 44 | for j in range(1, len(S)): 45 | count[j] += count[j-1] 46 | 47 | for i in range(len(S)-1, -1, -1): 48 | start = (order[i] - L + len(S)) % len(S) 49 | cl = Class[start] 50 | count[cl] -= 1 51 | newOrder[count[cl]] = start 52 | 53 | return newOrder 54 | 55 | 56 | def UpdateClasses(newOrder, Class, L): 57 | 58 | n = len(newOrder) 59 | newClass = [0 for i in range(n)] 60 | 61 | newClass[newOrder[0]] = 0 62 | 63 | for i in range(1, n): 64 | cur = newOrder[i] 65 | prev = newOrder[i-1] 66 | mid = cur + L 67 | midPrev = (prev + L) % n 68 | if Class[cur] != Class[prev] or Class[mid] != Class[midPrev]: 69 | newClass[cur] = newClass[prev] + 1 70 | else: 71 | newClass[cur] = newClass[prev] 72 | 73 | return newClass 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | if __name__ == '__main__': 86 | 87 | S = input() 88 | 89 | order = SortCharacters(S) 90 | Class = ComputeCharClasses(S, order) 91 | L = 1 92 | 93 | while L < len(S): 94 | order = SortDoubled(S, L, order, Class) 95 | Class = UpdateClasses(order, Class, L) 96 | L = 2*L 97 | 98 | for e in order: 99 | print(e, end = " ") 100 | print() 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /Algorithms on Strings/Week2/Programming Assignment: Programming Assignment 2/Programming Assignment: Programming Assignment 2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week2/Programming Assignment: Programming Assignment 2/Programming Assignment: Programming Assignment 2.pdf -------------------------------------------------------------------------------- /Algorithms on Strings/Week2/better_bwmatching.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week2/better_bwmatching.pdf -------------------------------------------------------------------------------- /Algorithms on Strings/Week2/bwmatching.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week2/bwmatching.pdf -------------------------------------------------------------------------------- /Algorithms on Strings/Week3/14_algorithmic_challenges_1_knuth_morris_pratt.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week3/14_algorithmic_challenges_1_knuth_morris_pratt.pdf -------------------------------------------------------------------------------- /Algorithms on Strings/Week4/14_algorithmic_challenges_2_suffix_array.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week4/14_algorithmic_challenges_2_suffix_array.pdf -------------------------------------------------------------------------------- /Algorithms on Strings/Week4/14_algorithmic_challenges_3_from_suffix_array_to_suffix_tree.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week4/14_algorithmic_challenges_3_from_suffix_array_to_suffix_tree.pdf -------------------------------------------------------------------------------- /Algorithms on Strings/Week4/Programming Assignment: Programming Assignment 3/Program1.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def lps(pattern): 4 | pattern = '#'+pattern 5 | length = len(pattern) 6 | table = [0 for i in range(length)] 7 | 8 | table[1] = 0 9 | 10 | for i in range(2, length): 11 | j = table[i-1] 12 | while pattern[j+1] != pattern[i] and j>0: 13 | j = table[j] 14 | 15 | if pattern[j+1] == pattern[i]: 16 | table[i] = j+1 17 | 18 | return table 19 | 20 | 21 | if __name__ == '__main__': 22 | pattern = input() 23 | text = input() 24 | table = lps(pattern+'$'+text) 25 | 26 | for i in range(len(pattern)+2, len(table)): 27 | if table[i] == len(pattern): 28 | print(i-2*len(pattern)-1, end=" ") 29 | 30 | print() 31 | 32 | -------------------------------------------------------------------------------- /Algorithms on Strings/Week4/Programming Assignment: Programming Assignment 3/Program2.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def SortCharacters(S): 4 | 5 | order = [0 for i in range(len(S))] 6 | count = [0 for i in range(256)] 7 | 8 | for i in range(len(S)): 9 | count[ord(S[i])] += 1 10 | 11 | for j in range(1, 256): 12 | count[j] += count[j-1] 13 | 14 | for i in range(len(S)-1, -1, -1): 15 | c = ord(S[i]) 16 | count[c] -= 1 17 | order[count[c]] = i 18 | 19 | return order 20 | 21 | 22 | def ComputeCharClasses(S, order): 23 | 24 | Class = [0 for i in range(len(S))] 25 | Class[order[0]] = 0 26 | 27 | for i in range(1, len(S)): 28 | if S[order[i]] != S[order[i-1]]: 29 | Class[order[i]] = Class[order[i-1]] + 1 30 | else: 31 | Class[order[i]] = Class[order[i-1]] 32 | 33 | return Class 34 | 35 | 36 | def SortDoubled(S, L, order, Class): 37 | 38 | count = [0 for i in range(len(S))] 39 | newOrder = [0 for i in range(len(S))] 40 | 41 | for i in range(len(S)): 42 | count[Class[i]] += 1 43 | 44 | for j in range(1, len(S)): 45 | count[j] += count[j-1] 46 | 47 | for i in range(len(S)-1, -1, -1): 48 | start = (order[i] - L + len(S)) % len(S) 49 | cl = Class[start] 50 | count[cl] -= 1 51 | newOrder[count[cl]] = start 52 | 53 | return newOrder 54 | 55 | 56 | def UpdateClasses(newOrder, Class, L): 57 | 58 | n = len(newOrder) 59 | newClass = [0 for i in range(n)] 60 | 61 | newClass[newOrder[0]] = 0 62 | 63 | for i in range(1, n): 64 | cur = newOrder[i] 65 | prev = newOrder[i-1] 66 | mid = cur + L 67 | midPrev = (prev + L) % n 68 | if Class[cur] != Class[prev] or Class[mid] != Class[midPrev]: 69 | newClass[cur] = newClass[prev] + 1 70 | else: 71 | newClass[cur] = newClass[prev] 72 | 73 | return newClass 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | if __name__ == '__main__': 86 | 87 | S = input() 88 | 89 | order = SortCharacters(S) 90 | Class = ComputeCharClasses(S, order) 91 | L = 1 92 | 93 | while L < len(S): 94 | order = SortDoubled(S, L, order, Class) 95 | Class = UpdateClasses(order, Class, L) 96 | L = 2*L 97 | 98 | for e in order: 99 | print(e, end = " ") 100 | print() 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /Algorithms on Strings/Week4/Programming Assignment: Programming Assignment 3/Programming Assignment: Programming Assignment 3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChanchalKumarMaji/Data-Structures-and-Algorithms-Specialization/8eed0b4f01f2ab122c75707b15d4d2d7d0f56d38/Algorithms on Strings/Week4/Programming Assignment: Programming Assignment 3/Programming Assignment: Programming Assignment 3.pdf -------------------------------------------------------------------------------- /Data Structures/Week1/Program1.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | def solve(S): 4 | 5 | brackets = [] 6 | for i in range(len(S)): 7 | if S[i]=='(' or S[i]==')' or S[i]=='{' or S[i]=='}' or S[i]=='[' or S[i]==']': 8 | brackets.append((S[i], i+1)) 9 | #print(brackets) 10 | 11 | stack = [] 12 | for bracket in brackets: 13 | b, idx = bracket[0], bracket[1] 14 | if b=='(' or b=='{' or b=='[': 15 | stack.append(bracket) 16 | elif b==')' or b=='}' or b==']': 17 | if len(stack)==0: 18 | return idx 19 | else: 20 | pre = stack[-1] 21 | pre_b, pre_idx = pre[0], pre[1] 22 | stack.pop() 23 | if b==')': 24 | if pre_b!='(': 25 | return idx 26 | elif b=='}': 27 | if pre_b!='{': 28 | return idx 29 | elif b==']': 30 | if pre_b!='[': 31 | return idx 32 | if len(stack)==0: 33 | return "Success" 34 | else: 35 | return stack[0][1] 36 | 37 | 38 | 39 | 40 | if __name__ == '__main__': 41 | S = input() 42 | print(solve(S)) 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /Data Structures/Week1/Program2.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank, setSize; // remember: vi is vector 150 | int numSets; 151 | public: 152 | UnionFind(int N) { 153 | setSize.assign(N, 1); numSets = N; rank.assign(N, 0); 154 | p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; } 155 | int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } 156 | bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } 157 | void unionSet(int i, int j) { 158 | if (!isSameSet(i, j)) { numSets--; 159 | int x = findSet(i), y = findSet(j); 160 | // rank is used to keep the tree short 161 | if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } 162 | else { p[x] = y; setSize[y] += setSize[x]; 163 | if (rank[x] == rank[y]) rank[y]++; } } } 164 | int numDisjointSets() { return numSets; } 165 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 166 | }; 167 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 168 | // Code to find "GCD" of two numbers 169 | int gcd(int a, int b){ 170 | if(a==0) 171 | return b; 172 | return gcd(b%a, a); 173 | } 174 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 175 | // Code to find the prime numbers using sieve of Erathosthenes 176 | vector SieveOfErathosthenes(int n){ 177 | vi res; 178 | vi prime(n+1, 1); 179 | int p = 2; 180 | while(p*p <= n){ 181 | if(prime[p]){ 182 | for(int i=2*p; i 0){ 200 | // If y is odd, multiply x with result 201 | if (y & 1) 202 | res = (res*x) % p; 203 | // y must be even now 204 | y = y>>1; // y = y/2 205 | x = (x*x) % p; 206 | } 207 | return res; 208 | } 209 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 210 | // Code for Graph Algorithms 211 | vector AdjList; 212 | vi dfs_num; 213 | int numCC; 214 | 215 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 216 | //printf(" %d", u); // this vertex is visited 217 | dfs_num[u] = 1; // important step: we mark this vertex as visited 218 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 219 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 220 | if (dfs_num[v.first] == 0) // important check to avoid cycle 221 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 222 | } } 223 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 224 | //=================================================================================================================================================== 225 | // Your Code starts here 226 | int main(){ 227 | 228 | int n; cin>>n; 229 | int s; 230 | AdjList.assign(n, vii()); 231 | for(int v=0; v>u; 233 | if(u==-1) 234 | s = v; 235 | else 236 | AdjList[u].push_back(ii(v, 1)); 237 | } 238 | 239 | vi dist(n, INF); dist[s] = 0; 240 | queue q; q.push(s); 241 | while(!q.empty()){ 242 | int u = q.front(); q.pop(); 243 | for(int j=0; j=end: 21 | while len(q)!=0 and q[0][0]+q[0][1]<=s: 22 | end = start 23 | res[q[0][2]] = end 24 | end += q[0][0]+q[0][1] 25 | q.popleft() 26 | 27 | q.append((process[i][0], process[i][1], i)) 28 | 29 | start = end 30 | end = start + q[0][1] 31 | 32 | else: 33 | if len(q) 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank; 150 | vector setSize; // remember: vi is vector 151 | int numSets; 152 | public: 153 | UnionFind(int N, vector r) { 154 | setSize.assign(N, 0); for(int i=0; i rank[y]) { p[y] = x; setSize[x] += setSize[y]; res = max(res, setSize[x]); } 163 | else { p[x] = y; setSize[y] += setSize[x]; res = max(res, setSize[y]); 164 | if (rank[x] == rank[y]) rank[y]++; } } } 165 | int numDisjointSets() { return numSets; } 166 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 167 | }; 168 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 169 | // Code to find "GCD" of two numbers 170 | int gcd(int a, int b){ 171 | if(a==0) 172 | return b; 173 | return gcd(b%a, a); 174 | } 175 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 176 | // Code to find the prime numbers using sieve of Erathosthenes 177 | vector SieveOfErathosthenes(int n){ 178 | vi res; 179 | vi prime(n+1, 1); 180 | int p = 2; 181 | while(p*p <= n){ 182 | if(prime[p]){ 183 | for(int i=2*p; i 0){ 201 | // If y is odd, multiply x with result 202 | if (y & 1) 203 | res = (res*x) % p; 204 | // y must be even now 205 | y = y>>1; // y = y/2 206 | x = (x*x) % p; 207 | } 208 | return res; 209 | } 210 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 211 | // Code for Graph Algorithms 212 | vector AdjList; 213 | vi dfs_num; 214 | int numCC; 215 | 216 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 217 | //printf(" %d", u); // this vertex is visited 218 | dfs_num[u] = 1; // important step: we mark this vertex as visited 219 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 220 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 221 | if (dfs_num[v.first] == 0) // important check to avoid cycle 222 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 223 | } } 224 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 225 | //=================================================================================================================================================== 226 | // Your Code starts here 227 | 228 | ll res = 0; 229 | 230 | int main(){ 231 | 232 | ll n, m; cin>>n>>m; 233 | vector r(n); 234 | for(int i=0; i>r[i]; 236 | 237 | UnionFind UF(n, r); 238 | 239 | res = *max_element(r.begin(), r.end()); 240 | 241 | while(m--){ 242 | int a, b; cin>>a>>b; 243 | a--; b--; 244 | UF.unionSet(a, b, res); 245 | cout< 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank; 150 | vector setSize; // remember: vi is vector 151 | int numSets; 152 | public: 153 | UnionFind(int N, vector r) { 154 | setSize.assign(N, 0); for(int i=0; i rank[y]) { p[y] = x; setSize[x] += setSize[y]; res = max(res, setSize[x]); } 163 | else { p[x] = y; setSize[y] += setSize[x]; res = max(res, setSize[y]); 164 | if (rank[x] == rank[y]) rank[y]++; } } } 165 | int numDisjointSets() { return numSets; } 166 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 167 | }; 168 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 169 | // Code to find "GCD" of two numbers 170 | int gcd(int a, int b){ 171 | if(a==0) 172 | return b; 173 | return gcd(b%a, a); 174 | } 175 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 176 | // Code to find the prime numbers using sieve of Erathosthenes 177 | vector SieveOfErathosthenes(int n){ 178 | vi res; 179 | vi prime(n+1, 1); 180 | int p = 2; 181 | while(p*p <= n){ 182 | if(prime[p]){ 183 | for(int i=2*p; i 0){ 201 | // If y is odd, multiply x with result 202 | if (y & 1) 203 | res = (res*x) % p; 204 | // y must be even now 205 | y = y>>1; // y = y/2 206 | x = (x*x) % p; 207 | } 208 | return res; 209 | } 210 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 211 | // Code for Graph Algorithms 212 | vector AdjList; 213 | vi dfs_num; 214 | int numCC; 215 | 216 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 217 | //printf(" %d", u); // this vertex is visited 218 | dfs_num[u] = 1; // important step: we mark this vertex as visited 219 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 220 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 221 | if (dfs_num[v.first] == 0) // important check to avoid cycle 222 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 223 | } } 224 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 225 | //=================================================================================================================================================== 226 | // Your Code starts here 227 | 228 | vector nodes; 229 | vi res; 230 | 231 | void inOrder(int root){ 232 | if(root == -1) 233 | return; 234 | inOrder(nodes[root][1]); 235 | res.push_back(nodes[root][0]); 236 | inOrder(nodes[root][2]); 237 | } 238 | 239 | int main(){ 240 | 241 | int n; cin>>n; 242 | if(n == 0){ 243 | cout<<"CORRECT"<>k>>l>>r; 249 | nodes[i] = (vi){k, l, r}; 250 | } 251 | 252 | inOrder(0); 253 | 254 | if(is_sorted(res.begin(), res.end())) 255 | cout<<"CORRECT"< 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | typedef long long ll; 19 | typedef pair ii; 20 | typedef vector vii; 21 | typedef vector vi; 22 | 23 | #define INF 1000000000 24 | 25 | // Common memset settings 26 | //memset(memo, -1, sizeof memo); // initialize DP memoization table with -1 27 | //memset(arr, 0, sizeof arr); // to clear array of integers 28 | 29 | 30 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 31 | // Code to print "VECTOR" objects 32 | template 33 | ostream& operator << (ostream& o, const vector& v){ 34 | o << "[ "; 35 | for(int i=0; i 46 | ostream& operator << (ostream& o, const set& s){ 47 | o << "[ "; 48 | for(auto it : s){ 49 | o << it; 50 | if(it != *s.rbegin()) 51 | o << ", "; 52 | } 53 | o << " ]"; 54 | return o; 55 | } 56 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 57 | // Code to print "MAP" elements 58 | template 59 | ostream& operator << (ostream& o, const map& m){ 60 | for(auto it : m) 61 | o << it.first << " : " << it.second << "\n"; 62 | return o; 63 | } 64 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 65 | // Code to print "PAIR" class 66 | template 67 | ostream& operator << (ostream& o, const pair& p){ 68 | o << "( "; 69 | o << p.first << ", " << p.second << " )"; 70 | return o; 71 | } 72 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 73 | // Code to print "STACK" objects 74 | template 75 | ostream& operator << (ostream& o, const stack& s){ 76 | o << "[ "; 77 | stack temp = s; 78 | while(!temp.empty()){ 79 | o << temp.top(); 80 | temp.pop(); 81 | if(temp.size() >= 1) 82 | o << ", "; 83 | } 84 | o << " ]"; 85 | return o; 86 | } 87 | //----------------------------------------------------------------------------------------------------------------------------------------------------- 88 | // Code to print "QUEUE" objects 89 | template 90 | ostream& operator << (ostream& o, const queue& q){ 91 | o << "[ "; 92 | queue temp = q; 93 | while(!temp.empty()){ 94 | o << temp.front(); 95 | temp.pop(); 96 | if(temp.size() >= 1) 97 | o << ", "; 98 | } 99 | o << " ]"; 100 | return o; 101 | } 102 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 103 | // Code to print "PRIORITY QUEUE" elements 104 | template 105 | ostream& operator << (ostream& o, const priority_queue& q){ 106 | o << "[ "; 107 | priority_queue temp = q; 108 | while(!temp.empty()){ 109 | o << temp.top(); 110 | temp.pop(); 111 | if(temp.size() >= 1) 112 | o << ", "; 113 | } 114 | o << " ]"; 115 | return o; 116 | } 117 | //--------------------------------------------------------------------------------------------------------------------------------------------------- 118 | /* C++ STL Algorithms 119 | 1. a. sort(first_iterator, last_iterator) – To sort the given vector 120 | b. sort(start_iterator, end_iterator, compare_function) - this also sorts the given range but you can define how the sorting should be done by compare_function 121 | 2. reverse(first_iterator, last_iterator) – To reverse a vector 122 | 3. *max_element(first_iterator, last_iterator) – To find the maximum element of a vector 123 | 4. *min_element(first_iterator, last_iterator) – To find the minimum element of a vector 124 | 5. a. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements 125 | b. accumulate(first_iterator, last_iterator, initial value of sum, myoperator) 126 | 6. count(first_iterator, last_iterator, x) – To count the occurrences of x in vector 127 | 7. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector 128 | 8. a. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not 129 | b. binary_search(first_iterator, last_iterator, value, compare_function) 130 | 9. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than x 131 | 10. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than x 132 | 11. a. is_sorted(first_iterator, last_iterator) - returns true if the range [first,last) is sorted into ascending order 133 | b. is_sorted(first_iterator, last_iterator, compare_function) - it also checks the given range but you can define how the sorting must be done 134 | 12. __gcd(m, n) - Handle 0,0 cases separately 135 | 13. 136 | */ 137 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 138 | // Code for "sort" with user defined way 139 | struct MyClass{ 140 | bool operator () (int i, int j){ 141 | return i>j; 142 | } 143 | }; 144 | MyClass obj; 145 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 146 | // Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 147 | class UnionFind { // OOP style 148 | private: 149 | vi p, rank; 150 | vector setSize; // remember: vi is vector 151 | int numSets; 152 | public: 153 | UnionFind(int N, vector r) { 154 | setSize.assign(N, 0); for(int i=0; i rank[y]) { p[y] = x; setSize[x] += setSize[y]; res = max(res, setSize[x]); } 163 | else { p[x] = y; setSize[y] += setSize[x]; res = max(res, setSize[y]); 164 | if (rank[x] == rank[y]) rank[y]++; } } } 165 | int numDisjointSets() { return numSets; } 166 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 167 | }; 168 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 169 | // Code to find "GCD" of two numbers 170 | int gcd(int a, int b){ 171 | if(a==0) 172 | return b; 173 | return gcd(b%a, a); 174 | } 175 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 176 | // Code to find the prime numbers using sieve of Erathosthenes 177 | vector SieveOfErathosthenes(int n){ 178 | vi res; 179 | vi prime(n+1, 1); 180 | int p = 2; 181 | while(p*p <= n){ 182 | if(prime[p]){ 183 | for(int i=2*p; i 0){ 201 | // If y is odd, multiply x with result 202 | if (y & 1) 203 | res = (res*x) % p; 204 | // y must be even now 205 | y = y>>1; // y = y/2 206 | x = (x*x) % p; 207 | } 208 | return res; 209 | } 210 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 211 | // Code for Graph Algorithms 212 | vector AdjList; 213 | vi dfs_num; 214 | int numCC; 215 | 216 | void dfs(int u) { // DFS for normal usage: as graph traversal algorithm 217 | //printf(" %d", u); // this vertex is visited 218 | dfs_num[u] = 1; // important step: we mark this vertex as visited 219 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 220 | ii v = AdjList[u][j]; // v is a (neighbor, weight) pair 221 | if (dfs_num[v.first] == 0) // important check to avoid cycle 222 | dfs(v.first); // recursively visits unvisited neighbors v of vertex u 223 | } } 224 | //---------------------------------------------------------------------------------------------------------------------------------------------------- 225 | //=================================================================================================================================================== 226 | // Your Code starts here 227 | 228 | vector nodes; 229 | vi res; 230 | 231 | bool p = true; 232 | 233 | void inOrder(int root){ 234 | if(root == -1) 235 | return; 236 | if(nodes[root][1] != -1 and nodes[nodes[root][1]][0] >= nodes[root][0]) 237 | p = false; 238 | 239 | if(nodes[root][2] != -1 and nodes[nodes[root][2]][0] < nodes[root][0]) 240 | p = false; 241 | 242 | inOrder(nodes[root][1]); 243 | res.push_back(nodes[root][0]); 244 | inOrder(nodes[root][2]); 245 | } 246 | 247 | int main(){ 248 | 249 | int n; cin>>n; 250 | if(n == 0){ 251 | cout<<"CORRECT"<>k>>l>>r; 257 | nodes[i] = (vi){k, l, r}; 258 | } 259 | 260 | inOrder(0); 261 | 262 | if(is_sorted(res.begin(), res.end()) and p) 263 | cout<<"CORRECT"<