├── .DS_Store ├── BS0: Binary Search ├── .DS_Store ├── FindFloorOfAElementInSortedArray.cpp ├── LeetCode30.cpp ├── MinimumDifferenceElementInASortedArray.cpp ├── Notes.txt ├── RotationNumberInSortedRotatedArrayAndIndexOfMinimumElement.cpp ├── SearchAnElementInSortedRotatedArray.cpp ├── SearchingInANearlySortedArray.cpp ├── binarysearch.cpp ├── binarysearchtemp.cpp ├── distancevitto.cpp ├── kk.cpp ├── n+nod.cpp ├── peakelement.cpp ├── set_stl_usasge.cpp └── sqrt.cpp ├── Coding Minutes Course └── oddeven.cpp ├── DC1: Divide & Conquer └── maximumsubarray.cpp ├── DP0 : Recursion & Backtracking ├── brackets.cpp ├── consecutiveone.cpp ├── friendpairing.cpp ├── hamiltonianpath.cpp ├── input.txt ├── nqueens.cpp ├── nqueenscount.cpp ├── output.txt ├── subsetprint.cpp ├── sudokosolver.cpp ├── tiling_problem.cpp └── towerofhanoi.cpp ├── DP1: Dynamic Programming ├── .DS_Store ├── PrintSetBit.cpp ├── coinchangedp.cpp ├── goldmine.cpp ├── knapsack_bottomup.cpp ├── knapsack_memo.cpp ├── knapsack_rec.cpp ├── knapsack_testcase.py ├── lcs_bottomup.cpp ├── lcs_memo.cpp ├── lcs_rec.cpp ├── lcs_testcase.py ├── lis_bottomup.cpp ├── lis_memo.cpp ├── lis_rec.cpp ├── lis_testcase.py ├── rockclimbing.cpp ├── rockclimbing.py ├── rockclimbing_rec.cpp ├── rodcutt_testcase.py ├── rodcutting_bottomup.cpp ├── rodcutting_memo.cpp ├── rodcutting_rec.cpp ├── subsetsum_memo.cpp ├── subsetsum_rec.cpp ├── subsetsumrec.cpp ├── test_knapsack.py ├── test_lcs.py ├── test_lis.py └── test_rod.py ├── DP2: Matrix Chain Multiplication ├── MCMBottomUp.cpp ├── MCMRecursion.cpp ├── MCMmemoization.cpp └── matrixChainMultiplication.cpp ├── DS0: Stack Queue LinkedList ├── LinkedList.cpp ├── ParanthesesRelated-1.cpp ├── ParanthesesRelated.cpp ├── allfix_final.cpp ├── circularqueue.cpp ├── infixpostfixprefix.cpp ├── infixtoevaluation.cpp └── stackqueue.cpp ├── DS1: Tree Binary Tree ├── .DS_Store ├── BST.cpp ├── BinaryTree.cpp └── avltree.cpp ├── DS2: Heap ├── BinomialHeap.cpp └── binaryheap.cpp ├── G1: Basic Graph (BFS, DFS) ├── Bfs.java ├── BfsShortestPath.java ├── Bipartite.java ├── CycleDetectionDirected.java ├── CycleDetectionUndirected.java ├── Graph.cpp ├── bipartitie.cpp ├── cycle_detection_directed.cpp ├── cycle_detection_undirected.cpp ├── dfs.java ├── graphwithedges.cpp ├── topologicalSort.java └── topological_sort.cpp ├── G2: Grid Recursion ├── floodfillalgo.cpp ├── labshortestpathgrid.cpp ├── minimumstepknightneedtoreachtarget.cpp └── ratinamze.cpp ├── G4: Disjoint Set Union ├── DSUrankPathCompression.java ├── dsu1.cpp ├── dsu2.cpp └── inp.txt ├── G5: Bridge Articulation Point ├── ArticulationPointAndBridges.java ├── EulerTour.java ├── articulation point and bridges.cpp ├── bestEulerTour.java ├── bridge.cpp ├── bridge_articulation.cpp ├── inp.txt ├── input1.txt ├── output.txt └── output1.txt ├── G6: Euler Circuit ├── best euler tour.cpp ├── euler tours.cpp └── inp.txt ├── G7: Strongly Connected Compound ├── KosarajuAlgorithm.java ├── TopologicalOrder.java ├── inp.txt ├── kosaraju algorithm for SCC.cpp ├── scc.cpp └── topological Order.cpp ├── G8: Minimum Spanning Tree ├── Kruskal Algo Test Driver Code.py ├── Kruskal.java ├── Kruskal_MST.cpp ├── Prim Algo Test Driver Code.py ├── Prim_MST.cpp ├── Prims.java ├── Prim’s and Kruskal’s Algorithm for Minimum Spanning Tree Analysis.pdf ├── README.md ├── Random_Graph_Generation.py ├── input1.txt ├── input2.txt ├── input3.txt └── input4.txt ├── G9: Shortest Path Algorithm ├── G9.1: Single Source Shortest Path │ ├── 743.network-delay-time.cpp │ ├── Bellman_Ford_Algorithm.cpp │ ├── Dijkstra_Algorithm.cpp │ ├── Floyd_Warshall_Algorithm.cpp │ ├── Kruskals_Algorithm.cpp │ ├── Prims_Algorithm.cpp │ ├── Readme.md │ ├── bellmanford.cpp │ ├── dijkastra.cpp │ └── inputdj.txt └── G9.2: All Pair Shortest Path │ ├── floydwarshallworking.cpp │ ├── inputdj.txt │ ├── jhonsonfinal.cpp │ ├── jhonsons2working.cpp │ ├── jhonsonsalgorithm.cpp │ ├── jhonsonscoded.cpp │ └── output.txt ├── Greedy: Huffman Coding ├── hf1.cpp ├── hf2.cpp └── hftemplate.cpp ├── LICENSE ├── NF0: Network Flow Basic ├── dinic's algprithm.cpp ├── dinicsAlgo.java ├── driver.cpp ├── driver2.cpp ├── edmond-karp-coded.cpp ├── edmond-karp.cpp ├── edmondkarp_fordfulkerson.cpp ├── inp.txt ├── mbm_maxflow.cpp ├── showsir.sh ├── showsir2.sh └── sirinput.txt ├── NT1: Eucleadian Algorithm GCD ├── Linear_Diophantine_Equations.cpp ├── Linear_diaphantine_eqn.png ├── Multiplicative_Modulo_Inverse_using_extended_Eucledian.png ├── gcd_extended.cpp └── multiplicative_modulo_inverse.cpp ├── README.md ├── Single-Source-Shortest-Path ├── BFS.cpp ├── Bellman_Ford_Algorithm.cpp ├── DFS.cpp ├── DetectCycleUndirectedGraph.cpp ├── DetectingCycleDirectedGraph.cpp ├── Dijkstra_Algorithm.cpp ├── Floyd_Warshall_Algorithm.cpp ├── Kruskals_Algorithm.cpp ├── Prims_Algorithm.cpp └── binomialHeap.cpp ├── Sort1: Sorting Algo ├── CountingInversionUsingMergeSort.cpp └── sorting.cpp └── T1: Segment Tree ├── FLIPCOIN-codechef.cpp ├── Readme.md ├── segment+tree+with+lazy+propagation.cpp └── segmenttree.cpp /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbdullahArean/Design-And-Analysis-Of-Algorithm-Data-Structure/b823db9bc7bf953d6e00a82d638b2ba698bf0e4b/.DS_Store -------------------------------------------------------------------------------- /BS0: Binary Search/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbdullahArean/Design-And-Analysis-Of-Algorithm-Data-Structure/b823db9bc7bf953d6e00a82d638b2ba698bf0e4b/BS0: Binary Search/.DS_Store -------------------------------------------------------------------------------- /BS0: Binary Search/Notes.txt: -------------------------------------------------------------------------------- 1 | Topic : Binary Search 2 | Resources: 3 | 1. Aditya Verma Playlist (https://www.youtube.com/playlist?list=PL_z_8CaSLPWeYfhtuKHj-9MpYb6XQJ_f2) 4 | 2. Errichto (https://www.youtube.com/watch?v=LcWPKR1uef4&ab_channel=Errichto2) 5 | 3. Must do Problems (https://www.youtube.com/watch?v=U66U1-umNbQ&ab_channel=KartikArora) 6 | 4. Advanced Binary Search Predicate funtion (https://www.youtube.com/watch?v=JAfJssvFgDI&ab_channel=Luv) 7 | 5. Binary Search Problems (https://www.youtube.com/watch?v=vh0jtsTXhno&list=PLamzFoFxwoNhR2uFoqm6nr8VgsERgTmYy&ab_channel=IDeserve) 8 | 9 | Notes: 10 | 1. Use Mid = Low + (High-Low)/2 istead of (Low+High)/2 to avoid integer overflow 11 | 2. Number of time array is rotated is the index of minimum element (0,1,....,N-1) 12 | 3. Finding minimum element in a rotated sorted array: 13 | minimum element of this kind of array is smaller than both of their components 14 | if mid is not that kind, compare with start and end, ans go to the unsorted part 15 | 4. Infinte Sorted Array (Important for Interview) : https://youtu.be/FzvK5uuaki8 + https://youtu.be/8x6dmO6XW8k 16 | 5. Binary Search on Answers is an Important concept. 17 | 18 | -------------------------------------------------------------------------------- /BS0: Binary Search/RotationNumberInSortedRotatedArrayAndIndexOfMinimumElement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Link : https://www.youtube.com/watch?v=4WmTRFZilj8&list=PL_z_8CaSLPWeYfhtuKHj-9MpYb6XQJ_f2&index=7&ab_channel=AdityaVerma 3 | About Problem : Binary Search Implementation 4 | Tags : 5 | Notes : 6 | Finding minimum element in a rotated sorted array: 7 | minimum element of this kind of array is smaller than both of their components 8 | if mid is not that kind, compare with start and end, ans go to the unsorted part 9 | 10 | */ 11 | 12 | #include 13 | using namespace std; 14 | const int MAXN = 1e5; 15 | void printarray(int arr[],int low, int high){ 16 | for(int i=low; i<=high; i++) printf("%d ",arr[i]); 17 | printf("\n"); 18 | } 19 | int BSUpperBound(int arr[], int N, int value) { 20 | int low = 0,high = N-1, mid; 21 | while (low < high) { 22 | //printarray(arr,low,high); 23 | mid = low+ (high-low)/2; 24 | if(arr[mid]>value) high = mid; 25 | else low= mid+1; 26 | } 27 | if(value>=arr[N-1]) low++; //To match built in functions 28 | return low; 29 | } 30 | int BSLowerBound(int arr[], int N, int value) { 31 | int low = 0,high = N-1, mid; 32 | while (low < high) { //No Equal Sign Needed 33 | //printarray(arr,low,high); 34 | mid = low+ (high-low)/2; 35 | 36 | if(arr[mid]>=value) { 37 | high = mid; 38 | } 39 | else { 40 | low= mid+1; 41 | } 42 | } 43 | if(value>=arr[N-1]) low++; //To match built in functions 44 | return low; 45 | } 46 | int BinarySearch(int arr[], int N, int value){ 47 | 48 | int low = 0,high = N-1, mid; 49 | while(low<=high){ //Equal Sign is a must or else false result! 50 | //printarray(arr,low,high); 51 | mid = (high+low)/2; 52 | if(arr[mid]>value) high=mid-1; 53 | else if( arr[mid]arr[low])low=mid+1; 68 | else if( arr[mid] 14 | using namespace std; 15 | const int MAXN = 1e5; 16 | void printarray(int arr[],int low, int high){ 17 | for(int i=low; i<=high; i++) printf("%d ",arr[i]); 18 | printf("\n"); 19 | } 20 | int BSUpperBound(int arr[], int N, int value) { 21 | int low = 0,high = N-1, mid; 22 | while (low < high) { 23 | //printarray(arr,low,high); 24 | mid = low+ (high-low)/2; 25 | if(arr[mid]>value) high = mid; 26 | else low= mid+1; 27 | } 28 | if(value>=arr[N-1]) low++; //To match built in functions 29 | return low; 30 | } 31 | int BSLowerBound(int arr[], int N, int value) { 32 | int low = 0,high = N-1, mid; 33 | while (low < high) { //No Equal Sign Needed 34 | //printarray(arr,low,high); 35 | mid = low+ (high-low)/2; 36 | 37 | if(arr[mid]>=value) { 38 | high = mid; 39 | } 40 | else { 41 | low= mid+1; 42 | } 43 | } 44 | if(value>=arr[N-1]) low++; //To match built in functions 45 | return low; 46 | } 47 | int BinarySearch(int arr[], int N, int value){ 48 | 49 | int low = 0,high = N-1, mid; 50 | while(low<=high){ //Equal Sign is a must or else false result! 51 | //printarray(arr,low,high); 52 | mid = (high+low)/2; 53 | if(arr[mid]>value) high=mid-1; 54 | else if( arr[mid]value) high=mid-1; 68 | else if( arr[mid]arr[low])low=mid+1; 83 | else if( arr[mid] 13 | using namespace std; 14 | const int MAXN = 1e5; 15 | void printarray(int arr[],int low, int high){ 16 | for(int i=low; i<=high; i++) printf("%d ",arr[i]); 17 | printf("\n"); 18 | } 19 | int LOWER_BOUND(int arr[], int N, int X) 20 | { 21 | int MIDELEMENT; 22 | int LOW = 0; 23 | int HIGH = N; 24 | while (LOW < HIGH) { 25 | MIDELEMENT = LOW + (HIGH - LOW) / 2; 26 | if (X <= arr[MIDELEMENT]) { 27 | HIGH = MIDELEMENT; 28 | } 29 | else { 30 | LOW = MIDELEMENT + 1; 31 | } 32 | } 33 | if(LOW < N && arr[LOW] < X) { 34 | LOW++; 35 | } 36 | return LOW; 37 | } 38 | int UPPER_BOUND(int arr[], int N, int X) 39 | { 40 | int MIDELEMENT; 41 | int LOW = 0; 42 | int HIGH = N; 43 | while (LOW < HIGH) { 44 | MIDELEMENT = LOW + (HIGH - LOW) / 2; 45 | if (X >= arr[MIDELEMENT]) { 46 | LOW = MIDELEMENT + 1; 47 | } 48 | else { 49 | HIGH = MIDELEMENT; 50 | } 51 | } 52 | if(LOW < N && arr[LOW] <= X) { 53 | LOW++; 54 | } 55 | return LOW; 56 | } 57 | int BinarySearch(int arr[], int N, int value){ 58 | 59 | int low = 0,high = N-1, mid; 60 | while(low<=high){ //Equal Sign is a must or else false result! 61 | //printarray(arr,low,high); 62 | mid = (high+low)/2; 63 | if(arr[mid]>value) high=mid-1; 64 | else if( arr[mid]value) high=mid-1; 78 | else if( arr[mid] 2 | using namespace std; 3 | const long long int MAXN = 100000; 4 | 5 | int SolutionForAssumedInput(int a, int b, double assume) 6 | { 7 | int a= assume*a; 8 | int b= assume*b; 9 | int peri= 2*(a+b); 10 | if(fabs(peri-400)<10e-6) return -1; 11 | if(p eri>400) return +1; 12 | else return 0; 13 | } 14 | int BinarySearchOnRealLifeProblems() 15 | { 16 | int lo, hi, mid; // Define The Search Space 17 | while (hi > lo) 18 | { 19 | int mid = lo + (hi - lo) / 2; 20 | } 21 | return lo; 22 | } 23 | int main() 24 | { 25 | freopen("inp.txt", "r", stdin); 26 | freopen("output.txt", "w", stdout); 27 | int testcase; 28 | cin >> testcase; 29 | getchar(); 30 | for (int i = 0; i < testcase; i++) 31 | { 32 | double a,b; 33 | scanf("%lf : %lf",&a,&b); 34 | 35 | } 36 | } -------------------------------------------------------------------------------- /BS0: Binary Search/distancevitto.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Link : https://onlinejudge.org/external/100/10041.pdf 3 | Tags : Median is the saviour 4 | Notes : 5 | */ 6 | #include 7 | using namespace std; 8 | const int MAXN = 1e5; 9 | void printarray(int arr[],int low, int high){ 10 | for(int i=low; i<=high; i++) printf("%d ",arr[i]); 11 | printf("\n"); 12 | } 13 | int BSUpperBound(int arr[], int N, int value) { 14 | int low = 0,high = N-1, mid; 15 | while (low < high) { 16 | //printarray(arr,low,high); 17 | mid = low+ (high-low)/2; 18 | if(arr[mid]>value) high = mid; 19 | else low= mid+1; 20 | } 21 | if(value>=arr[N-1]) low++; //To match built in functions 22 | return low; 23 | } 24 | int BSLowerBound(int arr[], int N, int value) { 25 | int low = 0,high = N-1, mid; 26 | while (low < high) { 27 | //printarray(arr,low,high); 28 | mid = low+ (high-low)/2; 29 | if(arr[mid]>=value) { 30 | high = mid; 31 | } 32 | else { 33 | low= mid+1; 34 | } 35 | } 36 | if(value>=arr[N-1]) low++; //To match built in functions 37 | return low; 38 | } 39 | int BinarySearch(int arr[], int N, int value){ 40 | 41 | int low = 0,high = N-1, mid; 42 | while(low<=high){ //Equal Sign is a must or else false result! 43 | //printarray(arr,low,high); 44 | mid = (high+low)/2; 45 | if(arr[mid]>value) high=mid-1; 46 | else if( arr[mid]>n; 62 | while(n--){ 63 | cin>>r; 64 | for(int i=0; i>arr[i]; 66 | if(i==0) {max= arr[i]; min = arr[i];} 67 | else if(arr[i]>max) max= arr[i]; 68 | else if(arr[i]dis) ansdist = dis; 77 | } 78 | printf("%d\n", ansdist); 79 | } 80 | } 81 | void Solution(){ 82 | int n,r, arr[(int)1e6]; 83 | cin>>n; 84 | while(n--){ 85 | cin>>r; 86 | for(int i=0; i>arr[i]; 87 | sort(arr, arr+n); 88 | int median = arr[r / 2]; 89 | 90 | int ans = 0; 91 | for (int i = 0; i < r; i++) { 92 | ans += abs(median - arr[i]); 93 | } 94 | printf("%d\n", ans); 95 | } 96 | 97 | } 98 | int main(){ 99 | ios_base::sync_with_stdio(false); 100 | cin.tie(NULL); 101 | Solution(); 102 | return 0; 103 | } -------------------------------------------------------------------------------- /BS0: Binary Search/kk.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | const long long int MAXN = 100000; 4 | 5 | int nightneeded(int arr[], int num, int maxd){ 6 | int cur=maxd; 7 | int ans=0; 8 | for(int i=0; imaxd) return -1; 10 | if(cur>=arr[i]) {cur-=arr[i];} 11 | else { 12 | cur=maxd; ans++; 13 | cur-=arr[i]; 14 | } 15 | } 16 | if(ans==0) ans++; 17 | return ans; 18 | } 19 | void print(int arr[], int num, int maxd){ 20 | int cur=maxd; 21 | int print=0; 22 | for(int i=0; i=arr[i]) {cur-=arr[i];print+=arr[i];} 24 | else { 25 | cout<lo){ 37 | int mid = lo +(hi-lo)/2; 38 | int night=nightneeded(arr, n,mid); 39 | if(night==-1) lo=mid+1; 40 | else if(night>k)lo=mid+1; 41 | else if(night>t; 51 | for(int i=0; i>n>>k; 54 | for(int j=0; j>arr[j]; 55 | //cout< 2 | #define ll long long int 3 | using namespace std; 4 | const ll MAXN = 1000000; 5 | ll DivisorCount[MAXN], arr[MAXN],countnum; 6 | ll BSUpperBound(ll arr[], ll N, ll value) { 7 | ll low = 0,high = N-1, mid; 8 | while (low < high) { 9 | //prllarray(arr,low,high); 10 | mid = low+ (high-low)/2; 11 | if(arr[mid]>value) high = mid; 12 | else low= mid+1; 13 | } 14 | if(value>=arr[N-1]) low++; //To match built in functions 15 | return low; 16 | } 17 | ll BSLowerBound(ll arr[], ll N, ll value) { 18 | ll low = 0,high = N-1, mid; 19 | while (low < high) { //No Equal Sign Needed 20 | //prllarray(arr,low,high); 21 | mid = low+ (high-low)/2; 22 | 23 | if(arr[mid]>=value) { 24 | high = mid; 25 | } 26 | else { 27 | low= mid+1; 28 | } 29 | } 30 | if(value>=arr[N-1]) low++; //To match built in functions 31 | return low; 32 | } 33 | void DivisorCountTill(){ 34 | for (ll i = 1; i <= MAXN; i++) { 35 | for (ll j = i; j <= MAXN; j += i) { 36 | DivisorCount[j]++; //// here cnt[x] means count of divisors of x 37 | } 38 | } 39 | } 40 | void generateseq(){ 41 | DivisorCountTill(); 42 | arr[0]=1; 43 | ll i=1; 44 | for(i; ; i++){ 45 | arr[i] = arr[i-1]+ DivisorCount[arr[i-1]]; 46 | if(arr[i]>=MAXN) {countnum=++i;return;} 47 | } 48 | 49 | } 50 | int main(){ 51 | generateseq(); 52 | //for(int i=0; i>n; 55 | for(int k=1; k<=n; k++) 56 | { 57 | ll a, b; 58 | cin>>a>>b; 59 | printf("Case %d: %lld\n",k ,BSUpperBound(arr,countnum,b)-BSLowerBound(arr, countnum,a)); 60 | } 61 | return 0; 62 | } -------------------------------------------------------------------------------- /BS0: Binary Search/set_stl_usasge.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to demonstrate various functions of 2 | // Set in C++ STL 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | // empty set container 12 | set > s1; 13 | 14 | // insert elements in random order 15 | s1.insert(40); 16 | s1.insert(30); 17 | s1.insert(60); 18 | s1.insert(20); 19 | s1.insert(50); 20 | 21 | // only one 50 will be added to the set 22 | s1.insert(50); 23 | s1.insert(10); 24 | 25 | // printing set s1 26 | set >::iterator itr; 27 | cout << "\nThe set s1 is : \n"; 28 | for (itr = s1.begin(); itr != s1.end(); itr++) { 29 | cout << *itr << " "; 30 | } 31 | cout << endl; 32 | 33 | // assigning the elements from s1 to s2 34 | set s2(s1.begin(), s1.end()); 35 | 36 | // print all elements of the set s2 37 | cout << "\nThe set s2 after assign from s1 is : \n"; 38 | for (itr = s2.begin(); itr != s2.end(); itr++) { 39 | cout << *itr << " "; 40 | } 41 | cout << endl; 42 | 43 | // remove all elements up to 30 in s2 44 | cout << "\ns2 after removal of elements less than 30 " 45 | ":\n"; 46 | s2.erase(s2.begin(), s2.find(30)); 47 | for (itr = s2.begin(); itr != s2.end(); itr++) { 48 | cout << *itr << " "; 49 | } 50 | 51 | // remove element with value 50 in s2 52 | int num; 53 | num = s2.erase(50); 54 | cout << "\ns2.erase(50) : "; 55 | cout << num << " removed\n"; 56 | for (itr = s2.begin(); itr != s2.end(); itr++) { 57 | cout << *itr << " "; 58 | } 59 | 60 | cout << endl; 61 | 62 | // lower bound and upper bound for set s1 63 | cout << "s1.lower_bound(40) : \n" 64 | << *s1.lower_bound(40) << endl; 65 | cout << "s1.upper_bound(40) : \n" 66 | << *s1.upper_bound(40) << endl; 67 | 68 | // lower bound and upper bound for set s2 69 | cout << "s2.lower_bound(40) :\n" 70 | << *s2.lower_bound(40) << endl; 71 | cout << "s2.upper_bound(40) : \n" 72 | << *s2.upper_bound(40) << endl; 73 | 74 | return 0; 75 | } 76 | 77 | -------------------------------------------------------------------------------- /BS0: Binary Search/sqrt.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Link : 3 | About Problem : 4 | Tags : 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | const int MAXN = 1e5; 10 | #define ll long long int 11 | 12 | double sqrtbinarysearch(ll n){ 13 | double low=0, high=n, mid; 14 | while((high-low)>1e-9){//Precsion 15 | mid=(high+low)/2; 16 | if(mid*mid>n) high = mid; 17 | else low= mid; 18 | } 19 | return low; 20 | } 21 | double nthsqrtbinarysearch(ll n){ 22 | double low=0, high=n, mid; 23 | while((high-low)>1e-9){//Precsion 24 | mid=(high+low)/2; 25 | if(mid*mid*mid>n) high = mid;//Multiply n times 26 | else low= mid; 27 | } 28 | return low; 29 | } 30 | void Solution(){ 31 | printf("%.9lf",nthsqrtbinarysearch(456)); 32 | 33 | } 34 | 35 | int main(){ 36 | ios_base::sync_with_stdio(false); 37 | cin.tie(NULL); 38 | 39 | Solution(); 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Coding Minutes Course/oddeven.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool oddeven(int n) 4 | { 5 | // odd returns true, even returns false 6 | if (n & 1) // is same as (n % 2) 7 | return 1; 8 | return 0; 9 | } 10 | bool getith(int n, int i) 11 | { 12 | // here int mask = 1< 2 | #include 3 | 4 | // Utility function to find the maximum of two numbers 5 | int max(int x, int y) { 6 | return (x > y) ? x : y; 7 | } 8 | 9 | // Function to find the maximum subarray sum using divide-and-conquer 10 | int maximum_sum(int nums[], int low, int high) 11 | { 12 | // If the array contains 0 or 1 element 13 | if (high <= low) { 14 | return nums[low]; 15 | } 16 | 17 | // Find the middle array element 18 | int mid = (low + high) / 2; 19 | 20 | // Find maximum subarray sum for the left subarray, 21 | // including the middle element 22 | int left_max = INT_MIN; 23 | int sum = 0; 24 | for (int i = mid; i >= low; i--) 25 | { 26 | sum += nums[i]; 27 | if (sum > left_max) { 28 | left_max = sum; 29 | } 30 | } 31 | 32 | // Find maximum subarray sum for the right subarray, 33 | // excluding the middle element 34 | int right_max = INT_MIN; 35 | sum = 0; // reset sum to 0 36 | for (int i = mid + 1; i <= high; i++) 37 | { 38 | sum += nums[i]; 39 | if (sum > right_max) { 40 | right_max = sum; 41 | } 42 | } 43 | 44 | // Recursively find the maximum subarray sum for the left 45 | // and right subarray, and take maximum 46 | int max_left_right = max(maximum_sum(nums, low, mid), 47 | maximum_sum(nums, mid + 1, high)); 48 | 49 | // return the maximum of the three 50 | return max(max_left_right, left_max + right_max); 51 | } 52 | 53 | int main(void) 54 | { 55 | int arr[] = { 2, -4, 1, 9, -6, 7, -3 }; 56 | int n = sizeof(arr) / sizeof(arr[0]); 57 | 58 | printf("The maximum sum of the subarray is %d", 59 | maximum_sum(arr, 0, n - 1)); 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/brackets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void generateBrackets(string output, int n, int open, int close ,int i){ 5 | //base case 6 | if(i==2*n){ 7 | cout<>n; 25 | generateBrackets(output, n, 0,0,0); 26 | } -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/consecutiveone.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector dp; 4 | int solve(int prev, int n) 5 | { 6 | if (n == 0) 7 | return 0; 8 | if (n == 1) 9 | { 10 | if (prev == 0) 11 | return 2; 12 | if (prev == 1) 13 | return 1; 14 | } 15 | if (prev == 0) 16 | return solve(0, n - 1) + solve(1, n - 1); 17 | if (prev == 1) 18 | return solve(0, n - 1); 19 | return -1; 20 | } 21 | int solve2(int n) 22 | { 23 | dp.resize(n + 1); 24 | dp[0] = 1; 25 | dp[1] = 2; 26 | for (int i = 2; i <= n; i++) 27 | dp[i] = dp[i - 1] + dp[i - 2]; 28 | return dp[n]; 29 | } 30 | int countStrings(int n) 31 | { 32 | 33 | return solve(0, n); 34 | } 35 | int main() 36 | { 37 | auto start = std::chrono::system_clock::now(); 38 | // Some computation here 39 | for (int n = 1; n < 40; n++) 40 | { 41 | cout << n << ": " << countStrings(n) << "\n"; 42 | } 43 | auto end = std::chrono::system_clock::now(); 44 | 45 | std::chrono::duration elapsed_seconds = end - start; 46 | std::time_t end_time = std::chrono::system_clock::to_time_t(end); 47 | 48 | std::cout << "finished computation at " << std::ctime(&end_time) 49 | << "elapsed time: " << elapsed_seconds.count() << "s" 50 | << std::endl; 51 | 52 | start = std::chrono::system_clock::now(); 53 | for (int n = 1; n < 40; n++) 54 | { 55 | 56 | cout << n << ":dp: " << solve2(n) << "\n"; 57 | } 58 | end = std::chrono::system_clock::now(); 59 | 60 | elapsed_seconds = end - start; 61 | end_time = std::chrono::system_clock::to_time_t(end); 62 | 63 | std::cout << "finished computation at " << std::ctime(&end_time) 64 | << "elapsed time: " << elapsed_seconds.count() << "s" 65 | << std::endl; 66 | } -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/friendpairing.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector dp; 4 | int solve2(int n) 5 | { 6 | dp.resize(n + 1); 7 | dp[0] = 1; 8 | dp[1] = 1; 9 | for (int i = 2; i <= n; i++) 10 | dp[i] = 1* dp[i - 1] + (i- 1) * dp[i - 2]; 11 | return dp[n]; 12 | } 13 | 14 | int main() 15 | { 16 | for (int n = 0; n < 15; n++) 17 | { 18 | 19 | cout << n << ":dp: " << solve2(n) << "\n"; 20 | } 21 | } -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/hamiltonianpath.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | const int N = 1e5; 4 | vector gr[N]; 5 | int vis[N]; 6 | int n, m; 7 | bool hamiltonian_path = 0; 8 | void pathsprint() 9 | { 10 | } 11 | void paths(int cur, int cnt) 12 | { 13 | if (cnt == n) 14 | { 15 | hamiltonian_path = 1; 16 | return; 17 | } 18 | vis[cur] = 1; 19 | for (auto x : gr[cur]) 20 | { 21 | if (!vis[x]) 22 | { 23 | paths(x, cnt + 1); 24 | } 25 | } 26 | vis[cur] = 0; 27 | } 28 | int main() 29 | { 30 | freopen("input.txt", "r", stdin); 31 | freopen("output.txt", "w", stdout); 32 | cin >> n >> m; 33 | for (int i = 0; i < m; i++) 34 | { 35 | int x, y; 36 | cin >> x >> y; 37 | gr[x].push_back(y); 38 | gr[y].push_back(x); 39 | } 40 | for (int i = 0; i < n; i++) 41 | paths(i, 1); 42 | } -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/input.txt: -------------------------------------------------------------------------------- 1 | 5 -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/nqueens.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define Max 20 5 | void printBoard(int n, int board[][Max]) 6 | { 7 | for (int i = 0; i < n; i++) 8 | { 9 | for (int j = 0; j < n; j++) 10 | { 11 | if (board[i][j] == 1) 12 | cout << board[i][j] << " "; 13 | else 14 | cout << 0 << " "; 15 | } 16 | cout << "\n"; 17 | } 18 | cout << "\n"; 19 | } 20 | bool canPlace(int board[][Max], int n, int x, int y) 21 | { 22 | // Column 23 | for (int k = 0; k < x; k++) 24 | { 25 | if (board[k][y] == 1) 26 | { 27 | return false; 28 | } 29 | } 30 | 31 | // Left Diagonal 32 | int i = x, j = y; 33 | while (i >= 0 and j >= 0) 34 | { 35 | if (board[i][j] == 1) 36 | { 37 | return false; 38 | } 39 | i--; 40 | j--; 41 | } 42 | // right diagonal 43 | i = x; 44 | j = y; 45 | while (i >= 0 and j < n) 46 | { 47 | if (board[i][j] == 1) 48 | { 49 | return false; 50 | } 51 | i--; 52 | j++; 53 | } 54 | return true; 55 | } 56 | bool solveNQueen(int n, int board[][Max], int i) 57 | { 58 | // base case 59 | if (i == n) 60 | { 61 | // Print the Board 62 | printBoard(n, board); 63 | return true; 64 | } 65 | 66 | // recursive case 67 | // try to place a queen in every row 68 | for (int j = 0; j < n; j++) 69 | { 70 | // whether the current position is safe or not 71 | if (canPlace(board, n, i, j)) 72 | { 73 | board[i][j] = 1; 74 | bool success = solveNQueen(n, board, i + 1); 75 | if (success) 76 | { 77 | return true; 78 | } 79 | // backtrack 80 | board[i][j] = 0; 81 | } 82 | } 83 | return false; 84 | } 85 | int main() 86 | { 87 | 88 | char input[100]; 89 | int n = 5; 90 | while(n<20){ 91 | int board[Max][Max]={0}; 92 | solveNQueen(n, board, 0); 93 | n++; 94 | } 95 | return 0; 96 | } -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/nqueenscount.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define Max 20 5 | void printBoard(int n, int board[][Max]) 6 | { 7 | for (int i = 0; i < n; i++) 8 | { 9 | for (int j = 0; j < n; j++) 10 | { 11 | if (board[i][j] == 1) 12 | cout << board[i][j] << " "; 13 | else 14 | cout << 0 << " "; 15 | } 16 | cout << "\n"; 17 | } 18 | cout << "\n"; 19 | } 20 | bool canPlace(int board[][Max], int n, int x, int y) 21 | { 22 | // Column 23 | for (int k = 0; k < x; k++) 24 | { 25 | if (board[k][y] == 1) 26 | { 27 | return false; 28 | } 29 | } 30 | 31 | // Left Diagonal 32 | int i = x, j = y; 33 | while (i >= 0 and j >= 0) 34 | { 35 | if (board[i][j] == 1) 36 | { 37 | return false; 38 | } 39 | i--; 40 | j--; 41 | } 42 | // right diagonal 43 | i = x; 44 | j = y; 45 | while (i >= 0 and j < n) 46 | { 47 | if (board[i][j] == 1) 48 | { 49 | return false; 50 | } 51 | i--; 52 | j++; 53 | } 54 | return true; 55 | } 56 | bool solveNQueen(int n, int board[][Max], int i) 57 | { 58 | // base case 59 | if (i == n) 60 | { 61 | // Print the Board 62 | printBoard(n, board); 63 | return true; 64 | } 65 | 66 | // recursive case 67 | // try to place a queen in every row 68 | for (int j = 0; j < n; j++) 69 | { 70 | // whether the current position is safe or not 71 | if (canPlace(board, n, i, j)) 72 | { 73 | board[i][j] = 1; 74 | bool success = solveNQueen(n, board, i + 1); 75 | if (success) 76 | { 77 | return true; 78 | } 79 | // backtrack 80 | board[i][j] = 0; 81 | } 82 | } 83 | return false; 84 | } 85 | int main() 86 | { 87 | 88 | char input[100]; 89 | int n = 5; 90 | while(n<20){ 91 | int board[Max][Max]={0}; 92 | solveNQueen(n, board, 0); 93 | n++; 94 | } 95 | return 0; 96 | } -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/output.txt: -------------------------------------------------------------------------------- 1 | A -> C 2 | A -> B 3 | C -> B 4 | A -> C 5 | B -> A 6 | B -> C 7 | A -> C 8 | A -> B 9 | C -> B 10 | C -> A 11 | B -> A 12 | C -> B 13 | A -> C 14 | A -> B 15 | C -> B 16 | A -> C 17 | B -> A 18 | B -> C 19 | A -> C 20 | B -> A 21 | C -> B 22 | C -> A 23 | B -> A 24 | B -> C 25 | A -> C 26 | A -> B 27 | C -> B 28 | A -> C 29 | B -> A 30 | B -> C 31 | A -> C 32 | -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/subsetprint.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void findSubsets(char* input, char* output, int i, int j){ 6 | //Base Case 7 | if(input[i]=='\0'){ 8 | output[j]= '\0'; 9 | if(output[0]=='\0') cout<<"NULL\n"; 10 | else cout<>input; 27 | findSubsets(input, output, 0, 0); 28 | 29 | return 0; 30 | 31 | } -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/sudokosolver.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define N 9 5 | void printMat(int mat[][N], int n) 6 | { 7 | for (int i = 0; i < n; i++) 8 | { 9 | for (int j = 0; j < n; j++) 10 | { 11 | cout << mat[i][j] << " "; 12 | } 13 | cout << "\n"; 14 | } 15 | } 16 | bool isSafe(int mat[][N], int i, int j, int no, int n) 17 | { 18 | // check for row and column 19 | for (int k = 0; k < n; k++) 20 | { 21 | if (mat[k][j] == no || mat[i][k] == no) 22 | return false; 23 | } 24 | // check for grid 25 | int sqrtn = sqrt(n); 26 | int sx = (i / sqrtn) * sqrtn; 27 | int sy = (j / sqrtn) * sqrtn; 28 | for (int x = sx; x < sx + sqrtn; x++) 29 | { 30 | for (int y = sy; y < sy + sqrtn; y++) 31 | { 32 | if (mat[x][y] == no) 33 | return false; 34 | } 35 | } 36 | return true; 37 | } 38 | bool solveSudoku(int mat[][N], int i, int j, int n) 39 | { 40 | // base case 41 | if (i == n) 42 | { 43 | // print the solution later 44 | printMat(mat, n); 45 | return true; 46 | } 47 | // recursive case 48 | if (j == n) 49 | { 50 | return solveSudoku(mat, i + 1, 0, n); 51 | } 52 | // skip prefilled cell 53 | if (mat[i][j] != 0) 54 | { 55 | return solveSudoku(mat, i, j + 1, n); 56 | } 57 | // cell to be filled 58 | for (int no = 1; no <= n; no++) 59 | { 60 | // whether it is safe or not 61 | if (isSafe(mat, i, j, no, n)) 62 | { 63 | mat[i][j] = no; 64 | bool solveSubProblem = solveSudoku(mat, i, j + 1, n); 65 | if (solveSubProblem == true) 66 | { 67 | return true; 68 | } 69 | } 70 | } 71 | // if no option works 72 | mat[i][j] = 0; 73 | return false; 74 | } 75 | int main() 76 | { 77 | int mat[N][N] = { 78 | {5, 3, 0, 0, 7, 0, 0, 0, 0}, 79 | {6, 0, 0, 1, 9, 5, 0, 0, 0}, 80 | {0, 9, 8, 0, 0, 0, 0, 6, 0}, 81 | {8, 0, 0, 0, 6, 0, 0, 0, 3}, 82 | {4, 0, 0, 8, 0, 3, 0, 0, 1}, 83 | {7, 0, 0, 0, 2, 0, 0, 0, 6}, 84 | {0, 6, 0, 0, 0, 0, 2, 8, 0}, 85 | {0, 0, 0, 4, 1, 9, 0, 0, 5}, 86 | {0, 0, 0, 0, 8, 0, 0, 7, 9}}; 87 | if (!solveSudoku(mat, 0, 0, N)) 88 | { 89 | cout << "Solution Does Not Exists\n"; 90 | } 91 | } -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/tiling_problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int tiling_problem(int n) 4 | { 5 | if (n < 4) 6 | return 1; 7 | return tiling_problem(n - 1) + tiling_problem(n - 4); 8 | } 9 | int main() 10 | { 11 | freopen("input.txt", "r", stdin); 12 | freopen("output.txt", "w", stdout); 13 | int n; 14 | cin >> n; 15 | cout << tiling_problem(n); 16 | } -------------------------------------------------------------------------------- /DP0 : Recursion & Backtracking/towerofhanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void TowerOfHanoi(int n, char from, char helper, char to) { 6 | 7 | if (n == 0) return; 8 | 9 | // cout << n << " " << from << " " << helper << " " << to << '\n'; 10 | 11 | TowerOfHanoi(n - 1, from, to, helper); 12 | // reached here 13 | // nth rod to to 14 | cout << from << " -> " << to << '\n'; 15 | 16 | TowerOfHanoi(n - 1, helper, from, to); 17 | 18 | } 19 | int main() 20 | { 21 | // freopen("input.txt", "r", stdin); 22 | // freopen("output.txt", "w", stdout); 23 | 24 | int n; 25 | cin >> n; 26 | 27 | TowerOfHanoi(n, 'A', 'B', 'C'); 28 | 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /DP1: Dynamic Programming/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbdullahArean/Design-And-Analysis-Of-Algorithm-Data-Structure/b823db9bc7bf953d6e00a82d638b2ba698bf0e4b/DP1: Dynamic Programming/.DS_Store -------------------------------------------------------------------------------- /DP1: Dynamic Programming/PrintSetBit.cpp: -------------------------------------------------------------------------------- 1 | //Print Number of set bits from 1 to n 2 | #include 3 | using namespace std; 4 | int main(){ 5 | //Tabulation 6 | int n=10; 7 | int dp[n+1]; 8 | dp[0]=0; 9 | for(int i=1; i<=n; i++){ 10 | dp[i]=dp[i/2]+(i%2); 11 | cout< 4 | 5 | using namespace std; 6 | 7 | int count(int coins[], int n, int sum) 8 | { 9 | int i, j, x, y; 10 | 11 | // We need sum+1 rows as the table 12 | // is constructed in bottom up 13 | // manner using the base case 0 14 | // value case (sum = 0) 15 | int table[sum + 1][n]; 16 | 17 | // Fill the entries for 0 18 | // value case (sum = 0) 19 | for (i = 0; i < n; i++) 20 | table[0][i] = 1; 21 | 22 | // Fill rest of the table entries 23 | // in bottom up manner 24 | for (i = 1; i < sum + 1; i++) { 25 | for (j = 0; j < n; j++) { 26 | // Count of solutions including coins[j] 27 | x = (i - coins[j] >= 0) ? table[i - coins[j]][j] 28 | : 0; 29 | 30 | // Count of solutions excluding coins[j] 31 | y = (j >= 1) ? table[i][j - 1] : 0; 32 | 33 | // total count 34 | table[i][j] = x + y; 35 | } 36 | } 37 | return table[sum][n - 1]; 38 | } 39 | 40 | // Driver Code 41 | int main() 42 | { 43 | int coins[] = { 3,4,5,7,13 }; 44 | int n = sizeof(coins) / sizeof(coins[0]); 45 | int sum = 25; 46 | for(int i=0; i<=sum; i++){ 47 | 48 | cout << i<<":"< 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int given[10][10]; 6 | vector > ansv; 7 | int f(int i, int j, int n, vector store) 8 | { 9 | if (i > n || j > n) 10 | return 0; 11 | store.push_back(given[i][j]); 12 | if (i == n && j == n) 13 | { 14 | vector tempv; 15 | int sum = 0; 16 | for (auto i : store) 17 | { 18 | sum += i; 19 | tempv.push_back(i); 20 | } 21 | tempv.push_back(sum); 22 | ansv.push_back(tempv); 23 | return given[i][j]; 24 | } 25 | else 26 | return given[i][j] + max(f(i + 1, j, n, store), f(i, j + 1, n, store)); 27 | store.pop_back(); 28 | } 29 | int main() 30 | { 31 | freopen("inp.txt", "r", stdin); 32 | freopen("output.txt", "w", stdout); 33 | int N; 34 | cin >> N; // N = number of item, W = total weight to be considered(#knapsack_tabu_rec's Weight) 35 | for (int i = 1; i <= N; i++) 36 | { 37 | for (int j = 1; j <= N; j++) 38 | { 39 | cin >> given[i][j]; 40 | } 41 | } 42 | vector temp; 43 | int ans2 = f(1, 1, N, temp); 44 | for (auto ii : ansv) 45 | { 46 | if(ii[ii.size()-1]==ans2){ 47 | for (auto jj : ii) 48 | { 49 | cout << jj << " "; 50 | } 51 | cout << endl; 52 | } 53 | } 54 | cout << ans2; 55 | } -------------------------------------------------------------------------------- /DP1: Dynamic Programming/knapsack_bottomup.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int main() 6 | { 7 | freopen("inp.txt", "r", stdin); 8 | freopen("output.txt", "a", stdout); 9 | auto start = high_resolution_clock::now(); 10 | int N, W; 11 | int weight[1001], profit[1001]; 12 | int dp[1001][1001]; 13 | cin >> N >> W; // N = number of item, W = total weight to be considered(#knapsack_tabu_rec's Weight) 14 | for (int i = 0; i < N; i++) 15 | { 16 | cin >> weight[i] >> profit[i]; 17 | } 18 | for (int i = 0; i <= N; i++) 19 | { 20 | for (int w = 0; w <= W; w++) 21 | { 22 | if (i == 0 || w == 0) 23 | dp[i][w] = 0; 24 | else if (weight[i] > w) 25 | dp[i][w] = dp[i - 1][w]; 26 | else 27 | dp[i][w] = max(profit[i] + dp[i - 1][w - weight[i]], dp[i - 1][w]); 28 | } 29 | } 30 | long long int ans = dp[N][W]; 31 | auto stop = high_resolution_clock::now(); 32 | auto duration = duration_cast(stop - start); 33 | cout << "Bottom Up/Tabulation: " << ans << " " << duration.count() << endl; 34 | } -------------------------------------------------------------------------------- /DP1: Dynamic Programming/knapsack_memo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int weight[1001],profit[1001]; 6 | int Mat[1001][1001]; 7 | int knapsack_memo(int W, int n) 8 | { 9 | if (n == 0 || W == 0) 10 | return 0; 11 | else if(Mat[n][W] != -1) 12 | return Mat[n][W]; 13 | else if (weight[n - 1] > W) 14 | return Mat[n][W] = knapsack_memo(W, n - 1); 15 | else 16 | return Mat[n][W] = max(profit[n - 1] + knapsack_memo(W - weight[n - 1], n - 1), knapsack_memo(W, n - 1)); 17 | } 18 | int main() 19 | { 20 | freopen("inp.txt", "r", stdin); 21 | freopen("output.txt", "a", stdout); 22 | auto start = high_resolution_clock::now(); 23 | int N, W; 24 | memset(Mat,-1,sizeof(Mat)); 25 | cin >> N >> W; // N = number of item, W = total weight to be considered(#knapsack_rec's Weight) 26 | for (int i = 0; i < N; i++) 27 | { 28 | cin >> weight[i] >> profit[i]; 29 | } 30 | int ans=knapsack_memo(W, N); 31 | auto stop = high_resolution_clock::now(); 32 | auto duration = duration_cast(stop - start); 33 | cout <<"Top Down/Memoization: "< 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int weight[1001], profit[1001]; 6 | int knapsack_rec(int W, int n) 7 | { 8 | if (n == 0 || W == 0) 9 | return 0; 10 | if (weight[n - 1] > W) 11 | return knapsack_rec(W, n - 1); 12 | else 13 | return max(profit[n - 1] + knapsack_rec(W - weight[n - 1], n - 1), knapsack_rec(W, n - 1)); 14 | } 15 | int main() 16 | { 17 | freopen("inp.txt", "r", stdin); 18 | freopen("output.txt", "w", stdout); 19 | auto start = high_resolution_clock::now(); 20 | int N, W; 21 | cin >> N >> W; // N = number of item, W = total weight to be considered(#knapsack_tabu_rec's Weight) 22 | for (int i = 0; i < N; i++) 23 | { 24 | cin >> weight[i] >> profit[i]; 25 | } 26 | int ans= knapsack_rec(W, N); 27 | auto stop = high_resolution_clock::now(); 28 | auto duration = duration_cast(stop - start); 29 | cout << "Recursion: " < 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int dp[100][100]; 6 | int lcs_tabu(string s1, string s2) 7 | { 8 | int n = s1.length(); 9 | int m = s2.length(); 10 | for (int i = 0; i <= n + 1; i++) 11 | { 12 | for (int j = 0; j <= m + 1; j++) 13 | { 14 | if (i == 0 || j == 0) 15 | dp[i][j] = 0; 16 | } 17 | } 18 | for (int i = 1; i <= n + 1; i++) 19 | { 20 | for (int j = 1; j <= m + 1; j++) 21 | { 22 | if (s1[i - 1] == s2[j - 1]) 23 | dp[i][j] = 1 + dp[i - 1][j - 1]; 24 | else 25 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); 26 | } 27 | } 28 | return dp[n][m]; 29 | } 30 | int main() 31 | { 32 | freopen("inp.txt", "r", stdin); 33 | freopen("output.txt", "a", stdout); 34 | auto start = high_resolution_clock::now(); 35 | int n; 36 | long long int ans=0; 37 | cin >> n; 38 | for (int i = 0; i < n; i++) 39 | { memset(dp,-1,sizeof(dp)); 40 | string str1, str2; 41 | cin >> str1>>str2; 42 | ans+=lcs_tabu(str1, str2); 43 | } 44 | auto stop = high_resolution_clock::now(); 45 | auto duration = duration_cast(stop - start); 46 | cout <<"Bottom Up/ Tabulation: "< 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int dp[100][100]; 6 | int lcs_memo(string s1, string s2, int i = 0, int j = 0) 7 | { 8 | if (i == 0 && j == 0) 9 | { 10 | int n = s1.length(); 11 | int m = s2.length(); 12 | for (int i = 0; i <= n + 1; i++) 13 | { 14 | for (int j = 0; j <= m + 1; j++) 15 | { 16 | dp[i][j] = -1; 17 | } 18 | } 19 | } 20 | if (i >= s1.length() || j >= s2.length()) 21 | return 0; 22 | if (dp[i][j] != -1) 23 | return dp[i][j]; 24 | else if (s1[i] == s2[j]) 25 | dp[i][j] = 1 + lcs_memo(s1, s2, i + 1, j + 1); 26 | else 27 | dp[i][j] = max(lcs_memo(s1, s2, i + 1, j), lcs_memo(s1, s2, i, j + 1)); 28 | return dp[i][j]; 29 | } 30 | int main() 31 | { 32 | freopen("inp.txt", "r", stdin); 33 | freopen("output.txt", "a", stdout); 34 | auto start = high_resolution_clock::now(); 35 | int n; 36 | cin >> n; 37 | long long int ans=0; 38 | for (int i = 0; i < n; i++) 39 | { 40 | //memset(dp,-1,sizeof(dp)); 41 | string str1, str2; 42 | cin >> str1>>str2; 43 | ans+=lcs_memo(str1, str2); 44 | } 45 | auto stop = high_resolution_clock::now(); 46 | auto duration = duration_cast(stop - start); 47 | cout <<"Top Down/Memoization: "< 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int lcs_rec(string s1, string s2, int i = 0, int j = 0) 6 | { 7 | if (i >= s1.length() || j >= s2.length()) 8 | return 0; 9 | else if (s1[i] == s2[j]) 10 | return 1 + lcs_rec(s1, s2, i + 1, j + 1); 11 | else 12 | return max(lcs_rec(s1, s2, i + 1, j), lcs_rec(s1, s2, i, j + 1)); 13 | } 14 | int main() 15 | { 16 | freopen("inp.txt", "r", stdin); 17 | freopen("output.txt", "w", stdout); 18 | auto start = high_resolution_clock::now(); 19 | int n; 20 | cin >> n; 21 | long long int ans=0; 22 | for (int i = 0; i < n; i++) 23 | { 24 | //memset(dp,-1,sizeof(dp)); 25 | string str1, str2; 26 | cin >> str1>>str2; 27 | ans+=lcs_rec(str1, str2); 28 | } 29 | auto stop = high_resolution_clock::now(); 30 | auto duration = duration_cast(stop - start); 31 | cout <<"Recursion: "< 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int lis(int arr[], int n) 6 | { 7 | int lis[n]; 8 | lis[0] = 1; 9 | for (int i = 1; i < n; i++) { 10 | lis[i] = 1; 11 | for (int j = 0; j < i; j++) 12 | if (arr[i] > arr[j] && lis[i] < lis[j] + 1) 13 | lis[i] = lis[j] + 1; 14 | } 15 | 16 | return *max_element(lis, lis + n); 17 | } 18 | int main() 19 | { 20 | freopen("inp.txt", "r", stdin); 21 | freopen("output.txt", "a", stdout); 22 | auto start = high_resolution_clock::now(); 23 | long long int ans=0; 24 | int n, m; 25 | cin >> n; 26 | for (int i = 0; i < n; i++) 27 | { 28 | cin >> m; 29 | int a[1000000]; 30 | for (int j = 0; j < m; j++) 31 | { 32 | cin >> a[j]; 33 | } 34 | ans+=lis(a,m);; 35 | } 36 | auto stop = high_resolution_clock::now(); 37 | auto duration = duration_cast(stop - start); 38 | cout <<"Bottom Up/ Tabulation: "< 2 | using namespace std; 3 | #include 4 | using namespace std::chrono; 5 | int lis(int idx, int prev_idx, int n, int a[],vector> &dp) 6 | { 7 | if (idx == n) 8 | { 9 | return 0; 10 | } 11 | if (dp[idx][prev_idx + 1] != -1) 12 | { 13 | return dp[idx][prev_idx + 1]; 14 | } 15 | int notTake = 0 + lis(idx + 1, prev_idx, n, a, dp); 16 | int take = INT_MIN; 17 | if (prev_idx == -1 || a[idx] > a[prev_idx]) 18 | { 19 | take = 1 + lis(idx + 1, idx, n, a, dp); 20 | } 21 | return dp[idx][prev_idx + 1] = max(take, notTake); 22 | } 23 | int main() 24 | { 25 | freopen("inp.txt", "r", stdin); 26 | freopen("output.txt", "a", stdout); 27 | auto start = high_resolution_clock::now(); 28 | long long int ans=0; 29 | int n, m; 30 | cin >> n; 31 | for (int i = 0; i < n; i++) 32 | { 33 | cin >> m; 34 | int a[10000]; 35 | vector> dp(m + 1, vector(m + 1, -1)); 36 | for (int j = 0; j < m; j++) 37 | { 38 | cin >> a[j]; 39 | } 40 | ans+=lis(0, -1, m, a, dp);; 41 | } 42 | auto stop = high_resolution_clock::now(); 43 | auto duration = duration_cast(stop - start); 44 | cout <<"Top Down/ Memoization: "< 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int lis_rec(int idx, int prev_idx, int n, int a[]) 6 | { 7 | if (idx == n) 8 | return 0; 9 | int notTake = 0 + lis_rec(idx + 1, prev_idx, n, a); 10 | int take = INT_MIN; 11 | if (prev_idx == -1 || a[idx] > a[prev_idx]) 12 | { 13 | take = 1 + lis_rec(idx + 1, idx, n, a); 14 | } 15 | return max(take, notTake); 16 | } 17 | int main() 18 | { 19 | freopen("inp.txt", "r", stdin); 20 | freopen("output.txt", "w", stdout); 21 | auto start = high_resolution_clock::now(); 22 | long long int ans=0; 23 | int n, m; 24 | cin >> n; 25 | for (int i = 0; i < n; i++) 26 | { 27 | cin >> m; 28 | int a[1000000]; 29 | for (int j = 0; j < m; j++) 30 | { 31 | cin >> a[j]; 32 | } 33 | ans+=lis_rec(0, -1, m, a);; 34 | } 35 | auto stop = high_resolution_clock::now(); 36 | auto duration = duration_cast(stop - start); 37 | cout <<"Recursion: "< 2 | using namespace std; 3 | 4 | int mat[100][100], dp[100][100]; 5 | int r, c; 6 | int rockclimbing_rec(int i, int j) 7 | { 8 | if (i >= 0 && i < r and j >= 0 && j < c) 9 | { /// If inside array 10 | int res = INT_MIN; 11 | /// Moving to three default direction, also add current cell's point 12 | res = max(res, rockclimbing_rec(i + 1, j) + mat[i][j]); 13 | res = max(res, rockclimbing_rec(i + 1, j - 1) + mat[i][j]); 14 | res = max(res, rockclimbing_rec(i + 1, j + 1) + mat[i][j]); 15 | return res; 16 | } 17 | else 18 | return 0; 19 | } 20 | int rockclimbing_memo(int i, int j) 21 | { 22 | if (i >= 0 && i < r and j >= 0 && j < c) 23 | { /// If inside array 24 | if (dp[i][j] != -1) 25 | return dp[i][j]; 26 | int res = INT_MIN; 27 | /// Moving to three default direction, also add current cell's point 28 | res = max(res, rockclimbing_memo(i + 1, j) + mat[i][j]); 29 | res = max(res, rockclimbing_memo(i + 1, j - 1) + mat[i][j]); 30 | res = max(res, rockclimbing_memo(i + 1, j + 1) + mat[i][j]); 31 | return dp[i][j] = res; 32 | } 33 | else 34 | return 0; /// If outside array 35 | } 36 | int rockclimbing_tabu(int i, int j) 37 | { 38 | for(int i=0; i> r >> c; 57 | for (int i = 0; i < r; i++) 58 | { 59 | for (int j = 0; j < c; j++) 60 | { 61 | cin >> mat[i][j]; 62 | } 63 | } 64 | cout << "Maximum Point is: Tabu" << rockclimbing_tabu(0, 0) << endl; 65 | cout<<"Tabuuuuuuuu\n"; 66 | for(int i=0; i 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int rodcutting(int price[], int n) 6 | { 7 | int revs[n + 1]; 8 | revs[0] = 0; // the revenue of a rod of length 0 is 0. 9 | int maxi = -99999; 10 | for (int j = 1; j <= n; j++) 11 | { // revs[j] indicates maximum revenue of a rod of length j. 12 | maxi = -99999;; 13 | for (int i = 0; i < j; i++) 14 | { 15 | maxi = max(maxi, price[i] + revs[j - i - 1]); 16 | } 17 | revs[j] = maxi; 18 | } 19 | return revs[n]; 20 | } 21 | int main() 22 | { 23 | freopen("inp.txt", "r", stdin); 24 | freopen("output.txt", "a", stdout); 25 | auto start = high_resolution_clock::now(); 26 | int price[1000000]; 27 | int n, m; 28 | long long int ans=0; 29 | cin >> n; 30 | for (int i = 0; i < n; i++) 31 | { 32 | cin >> m; 33 | for (int j = 0; j < m; j++) 34 | { 35 | cin >> price[j]; 36 | } 37 | ans+=rodcutting(price, m) ; 38 | } 39 | auto stop = high_resolution_clock::now(); 40 | auto duration = duration_cast(stop - start); 41 | cout <<"Bottom Up/ Tabulation: "< 2 | using namespace std; 3 | #include 4 | using namespace std::chrono; 5 | int dp[10000]; 6 | int rodcutting(int price[], int n) 7 | { 8 | if (n <= 0) 9 | return 0; 10 | if(dp[n]!=-1) return dp[n]; 11 | int max_val = INT_MIN; // set maximum value to negative infinity 12 | for (int i = 0; i < n; ++i) 13 | max_val = max(max_val, price[i] + rodcutting(price, n - i - 1)); 14 | return dp[n]=max_val; 15 | } 16 | int main() 17 | { 18 | freopen("inp.txt", "r", stdin); 19 | freopen("output.txt", "a", stdout); 20 | 21 | auto start = high_resolution_clock::now(); 22 | int price[1000000]; 23 | int n, m; 24 | long long int ans=0; 25 | cin >> n; 26 | for (int i = 0; i < n; i++) 27 | { 28 | cin >> m; 29 | for (int j = 0; j < m; j++) 30 | { 31 | memset(dp,-1,sizeof(dp)); 32 | cin >> price[j]; 33 | } 34 | ans+=rodcutting(price, m) ; 35 | } 36 | auto stop = high_resolution_clock::now(); 37 | auto duration = duration_cast(stop - start); 38 | cout <<"Top Down/Memoization : "< 2 | #include 3 | using namespace std::chrono; 4 | using namespace std; 5 | int rodcutting(int price[], int n) 6 | { 7 | if (n <= 0) 8 | return 0; 9 | int max_val = INT_MIN; // set maximum value to negative infinity 10 | for (int i = 0; i < n; ++i) 11 | max_val = max(max_val, price[i] + rodcutting(price, n - i - 1)); 12 | return max_val; 13 | } 14 | int main() 15 | { 16 | freopen("inp.txt", "r", stdin); 17 | freopen("output.txt", "w", stdout); 18 | auto start = high_resolution_clock::now(); 19 | long long int ans=0; 20 | int n, m; 21 | cin >> n; 22 | for (int i = 0; i < n; i++) 23 | { 24 | cin >> m; 25 | int price[1000000]; 26 | for (int j = 0; j < m; j++) 27 | { 28 | cin >> price[j]; 29 | } 30 | ans+=rodcutting(price, m) ; 31 | } 32 | auto stop = high_resolution_clock::now(); 33 | auto duration = duration_cast(stop - start); 34 | cout <<"Recursion: "< 2 | using namespace std; 3 | int Mat[1001][1001]; //Memoization 4 | vector given ={2,3,5,7,10, 12, 14, 15, 17, 18, 20, 21, 34,56}; 5 | int subsetsum(int S, int k){ 6 | if(S==0) return 1; 7 | if(S>0 && k>given.size()) return 0; 8 | if(S<0) return 0; 9 | if(Mat[S][k] != -1) return Mat[S][k]; //Memoization 10 | return Mat[S][k]=subsetsum(S-given[k],k+1)+subsetsum(S, k+1); 11 | } 12 | int main(){ 13 | memset(Mat,-1,sizeof(Mat)); //Memoization 14 | for(int i=1; i<=100; i++) 15 | cout< 2 | using namespace std; 3 | vector given ={2,3,5,7,10, 12, 14, 15, 17, 18, 20, 21, 34,56}; 4 | int subsetsum(int S, int k){ 5 | if(S==0) return 1; 6 | if(S>0 && k>given.size()) return 0; 7 | if(S<0) return 0; 8 | return subsetsum(S-given[k],k+1)+subsetsum(S, k+1); 9 | } 10 | int main(){ 11 | for(int i=1; i<=100; i++) 12 | cout< 2 | using namespace std; 3 | vector given ={2,3,5,7}; 4 | int subsetsum(int S, int k){ 5 | if(S==0) return 1; 6 | if(S>0 && k>given.size()) return 0; 7 | if(S<0) return 0; 8 | return subsetsum(S-given[k],k+1)+subsetsum(S, k+1); 9 | } 10 | int main(){ 11 | subsetsum(14,0); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /DP1: Dynamic Programming/test_knapsack.py: -------------------------------------------------------------------------------- 1 | import os 2 | os.system(f"python3 knapsack_testcase.py && g++ knapsack_rec.cpp && ./a.out && g++ knapsack_memo.cpp && ./a.out && g++ knapsack_bottomup.cpp && ./a.out") 3 | -------------------------------------------------------------------------------- /DP1: Dynamic Programming/test_lcs.py: -------------------------------------------------------------------------------- 1 | import os 2 | os.system(f"python3 lcs_testcase.py && g++ lcs_rec.cpp && ./a.out && g++ lcs_memo.cpp && ./a.out && g++ lcs_bottomup.cpp && ./a.out") 3 | -------------------------------------------------------------------------------- /DP1: Dynamic Programming/test_lis.py: -------------------------------------------------------------------------------- 1 | import os 2 | os.system(f"python3 lis_testcase.py && g++ lis_rec.cpp && ./a.out && g++ lis_memo.cpp && ./a.out && g++ lis_bottomup.cpp && ./a.out") 3 | -------------------------------------------------------------------------------- /DP1: Dynamic Programming/test_rod.py: -------------------------------------------------------------------------------- 1 | import os 2 | os.system(f"python3 rodcutt_testcase.py && g++ rodcutting_rec.cpp && ./a.out && g++ rodcutting_memo.cpp && ./a.out && g++ rodcutting_bottomup.cpp && ./a.out") 3 | -------------------------------------------------------------------------------- /DP2: Matrix Chain Multiplication/MCMBottomUp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int MCM(vector &arr, int N) 5 | { 6 | int arr2D[N][N]; 7 | memset(arr2D,0,sizeof(arr2D)); 8 | for(int i = N-1 ; i >= 1 ; i--) 9 | { 10 | for(int j = i+1; j < N ; j++) 11 | { 12 | int res = INT_MAX; 13 | for(int k = i ; k < j; k++) 14 | { 15 | int Totaloperations = arr[i-1]*arr[k]*arr[j] + arr2D[i][k] + arr2D[k+1][j]; 16 | if(Totaloperations < res) 17 | res = Totaloperations; 18 | } 19 | arr2D[i][j] = res; 20 | } 21 | } 22 | return arr2D[1][N-1]; 23 | } 24 | 25 | int main() 26 | { 27 | int N; 28 | cin>>N; 29 | vectorarr(N+1); 30 | for(int i = 0 ; i <= N ; i++) 31 | { 32 | cin>>arr[i]; 33 | } 34 | int ans = MCM(arr,N+1); 35 | cout<<"Total Number of Minimum Operation is : "< 2 | using namespace std; 3 | 4 | 5 | 6 | int MCM(int i, int j , vector &arr) 7 | { 8 | if(i == j) 9 | return 0; 10 | int res = INT_MAX; 11 | for(int k = i; k < j ; k++) 12 | { 13 | int TotalOperations = arr[i-1]*arr[k]*arr[j] + MCM(i,k,arr) + MCM(k+1,j,arr); 14 | if(TotalOperations < res) 15 | res = TotalOperations; 16 | } 17 | return res; 18 | 19 | } 20 | 21 | int main() 22 | { 23 | int N; 24 | cin>>N; 25 | vectorarr(N+1); 26 | for(int i = 0 ; i <= N ; i++) 27 | { 28 | cin>>arr[i]; 29 | } 30 | int ans = MCM(1,N,arr); 31 | cout<<"Total Number of Minimum Operation is : "< 2 | using namespace std; 3 | 4 | 5 | int dp_arr[105][105]; 6 | 7 | int MCM(int i, int j , vector &arr) 8 | { 9 | if(i == j) 10 | return 0; 11 | else if(dp_arr[i][j] != -1) 12 | return dp_arr[i][j]; 13 | int res = INT_MAX; 14 | for(int k = i; k < j ; k++) 15 | { 16 | int TotalOperations = arr[i-1]*arr[k]*arr[j] + MCM(i,k,arr) + MCM(k+1,j,arr); 17 | if(TotalOperations < res) 18 | res = TotalOperations; 19 | } 20 | return dp_arr[i][j] = res; 21 | 22 | } 23 | 24 | int main() 25 | { 26 | memset(dp_arr,-1,sizeof(dp_arr)); 27 | int N; 28 | cin>>N; 29 | vectorarr(N+1); 30 | for(int i = 0 ; i <= N ; i++) 31 | { 32 | cin>>arr[i]; 33 | } 34 | int ans = MCM(1,N,arr); 35 | cout<<"Total Number of Minimum Operation is : "< 2 | using namespace std; 3 | 4 | int dp[100][100]; 5 | 6 | int MatrixChainRecursion(int p[], int i, int j){ 7 | 8 | if (i == j) return 0; 9 | 10 | int k; 11 | int val = INT_MAX; 12 | int count; 13 | 14 | for (k = i; k < j; k++){ 15 | count = MatrixChainRecursion(p, i, k) + MatrixChainRecursion(p, k + 1, j) + p[i - 1] * p[k] * p[j]; 16 | val = min(count, val); 17 | } 18 | 19 | return val; 20 | } 21 | 22 | 23 | //Time Complexity: O(N^3 ) 24 | //Auxiliary Space: O(N^2) 25 | // Function for matrix chain multiplication 26 | int MatrixChainMemoised(int *p, int i, int j){ 27 | 28 | if (i == j) return 0; 29 | 30 | if (dp[i][j] != -1) return dp[i][j]; 31 | 32 | dp[i][j] = INT_MAX; 33 | for (int k = i; k < j; k++){ 34 | dp[i][j] = min(dp[i][j], MatrixChainMemoised(p, i, k)+ MatrixChainMemoised(p, k + 1, j)+ p[i - 1] * p[k] * p[j]); 35 | } 36 | 37 | return dp[i][j]; 38 | } 39 | 40 | 41 | 42 | 43 | //Time Complexity: O(N^3 ) 44 | //Auxiliary Space: O(N^2) 45 | int MatrixChainBottomUp(int p[], int n){ 46 | 47 | int m[n][n]; 48 | 49 | int i, j, k, L, q; 50 | 51 | // cost is zero when multiplying one matrix. 52 | for (i = 1; i < n; i++) 53 | m[i][i] = 0; 54 | 55 | // L is chain length. 56 | for (L = 2; L < n; L++){ 57 | for (i = 1; i < n - L + 1; i++){ 58 | j = i + L - 1; 59 | m[i][j] = INT_MAX; 60 | for (k = i; k <= j - 1; k++){ 61 | q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; 62 | if (q < m[i][j]) 63 | m[i][j] = q; 64 | } 65 | } 66 | } 67 | 68 | return m[1][n - 1]; 69 | } 70 | 71 | int main(){ 72 | int arr[] = { 1, 2, 3, 4 }; 73 | int N = sizeof(arr) / sizeof(arr[0]); 74 | memset(dp,-1,sizeof(dp)); 75 | // Function call 76 | cout << "Minimum number of multiplications is "<< MatrixChainRecursion(arr, 1, N - 1)< 2 | using namespace std; 3 | #define DIV ' ' 4 | int check_priority(char ch) 5 | { 6 | if (ch == '^') 7 | return 4; 8 | else if (ch == '/' || ch == '*') 9 | return 3; 10 | else if (ch == '-') 11 | return 2; 12 | else if (ch == '+') 13 | return 1; 14 | else 15 | return -1; 16 | } 17 | 18 | string infToPost(string infix) 19 | { 20 | stack stack1; 21 | string postfix; 22 | 23 | for (int i = 0; i < infix.length(); i++) 24 | { 25 | char ch = infix[i]; 26 | if (ch >= '0' && ch <= '9') 27 | { 28 | postfix += ch; 29 | if (i != infix.length() - 1 && (infix[i + 1] >= '0' && infix[i + 1] <= '9')) 30 | continue; 31 | postfix += DIV; 32 | } 33 | else if (ch == '(') 34 | stack1.push('('); 35 | else if (ch == ')') 36 | { 37 | while (stack1.top() != '(') 38 | { 39 | postfix += stack1.top(); 40 | postfix += DIV; 41 | stack1.pop(); 42 | } 43 | stack1.pop(); 44 | } 45 | else 46 | { 47 | while (!stack1.empty() && check_priority(infix[i]) <= check_priority(stack1.top())) 48 | { 49 | postfix += stack1.top(); 50 | postfix += DIV; 51 | stack1.pop(); 52 | } 53 | stack1.push(ch); 54 | } 55 | } 56 | while (!stack1.empty()) 57 | { 58 | postfix += stack1.top(); 59 | postfix += DIV; 60 | stack1.pop(); 61 | } 62 | 63 | postfix.pop_back(); 64 | 65 | return postfix ; 66 | } 67 | void postfixtoeval(string pofx) 68 | { 69 | //cout<s; 73 | int i=0; 74 | double op1,op2; 75 | while( (ch=pofx[i++]) != '\0') 76 | { 77 | if(isdigit(ch)) s.push(ch-'0'); /* Push the operand */ 78 | else if(ch==DIV) 79 | flag=0; 80 | else 81 | { /* Operator,pop two operands */ 82 | flag=0; 83 | op2= s.top(); s.pop(); 84 | op1= s.top(); s.pop(); 85 | switch(ch) 86 | { 87 | case '+':s.push(op1+op2);break; 88 | case '-':s.push(op1-op2);break; 89 | case '*':s.push(op1*op2);break; 90 | case '/':s.push(op1/op2);break; 91 | case '^':s.push(pow(op1,op2)); break; 92 | } 93 | } 94 | } 95 | printf("%0.4lf\n",s.top()); 96 | } 97 | 98 | int main() 99 | { 100 | ios_base::sync_with_stdio(false); 101 | cin.tie(NULL); 102 | freopen("inp.txt","r",stdin); freopen("output.txt","w",stdout); 103 | 104 | string infix; 105 | cin >> infix; 106 | postfixtoeval( infToPost(infix)); 107 | 108 | return 0; 109 | } -------------------------------------------------------------------------------- /DS0: Stack Queue LinkedList/circularqueue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define MAX 10000 4 | class Queuey 5 | { 6 | private: 7 | int arr[MAX]; 8 | int size; 9 | int front = -1, rear = -1; 10 | 11 | public: 12 | Queuey(int arraysize) 13 | {size=arraysize; 14 | 15 | } 16 | bool IsFull() { 17 | return (rear+1)%size == front; 18 | } 19 | bool IsEmpty() 20 | { 21 | return rear == -1 && front == -1; 22 | } 23 | void Enqueue(int data) 24 | { 25 | if(IsFull()) { 26 | printf("Overflow"); 27 | return; 28 | } 29 | //if it's the 1st element 30 | if(front == -1) { 31 | front = 0; 32 | } 33 | 34 | rear = (rear + 1)%size; 35 | arr[rear] = data; 36 | 37 | } 38 | int Dequeue() 39 | { 40 | if(IsEmpty()) { 41 | printf("empty queue"); 42 | return -1; 43 | } 44 | int res = arr[front]; 45 | 46 | //if only 1 element is present 47 | if(front == rear) { 48 | front = rear = -1; 49 | } else { 50 | front = (front+1)%size; 51 | } 52 | 53 | return res; 54 | } 55 | int Front() 56 | { 57 | if(IsEmpty()) printf("The Queue is empty"); 58 | else return arr[front]; 59 | 60 | } 61 | 62 | void Print() 63 | { 64 | int i=front; 65 | while(i!=rear){ 66 | printf("%d =>",arr[i]); 67 | i=(i+1)%size; 68 | } 69 | printf("%d =>",arr[rear]); 70 | } 71 | }; 72 | int main(){ 73 | Queuey q1= Queuey(10); 74 | q1.Enqueue(12); 75 | q1.Enqueue(142); 76 | q1.Enqueue(122); 77 | q1.Enqueue(12524); 78 | q1.Enqueue(125245); 79 | q1.Enqueue(12667); 80 | q1.Enqueue(1285); 81 | q1.Enqueue(1256785); 82 | q1.Enqueue(1285); 83 | q1.Enqueue(1258764); 84 | //q1.Enqueue(1285); 85 | //q1.Enqueue(1256785); 86 | // q1.Enqueue(1285); 87 | // q1.Enqueue(1258764); 88 | //q1.Dequeue(); 89 | q1.Print(); 90 | } 91 | 92 | 93 | -------------------------------------------------------------------------------- /DS1: Tree Binary Tree/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbdullahArean/Design-And-Analysis-Of-Algorithm-Data-Structure/b823db9bc7bf953d6e00a82d638b2ba698bf0e4b/DS1: Tree Binary Tree/.DS_Store -------------------------------------------------------------------------------- /G1: Basic Graph (BFS, DFS)/Bfs.java: -------------------------------------------------------------------------------- 1 | package BreadthFirstSearch; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.LinkedList; 7 | import java.util.Queue; 8 | 9 | public class Bfs { 10 | 11 | 12 | static class Graph{ 13 | int V; 14 | ArrayList[] list; 15 | 16 | public Graph(int v){ 17 | V = v; 18 | list = new ArrayList[v]; 19 | for(int i = 0; i < v; i++){ 20 | list[i] = new ArrayList<>(); 21 | } 22 | } 23 | 24 | void addEdge(int i, int j, boolean unDirected){ 25 | list[i].add(j); 26 | if(unDirected) 27 | list[j].add(i); 28 | } 29 | 30 | void bfs(int source){ 31 | 32 | Queue q = new LinkedList<>(); 33 | Boolean[] visited = new Boolean[V]; 34 | Arrays.fill(visited, false); 35 | 36 | q.add(source); 37 | visited[source] = true; 38 | 39 | while(!q.isEmpty()){ 40 | //Do some work for every node 41 | int f = q.poll(); 42 | System.out.println(f); 43 | // q.pop(); 44 | 45 | //PUsh the nbrs of current node inside q if they are not already visited 46 | for(int nbr : list[f]){ 47 | if(!visited[nbr]){ 48 | q.add(nbr); 49 | visited[nbr] = true; 50 | } 51 | } 52 | } 53 | } 54 | 55 | 56 | } 57 | 58 | public static void main(String[] args){ 59 | Graph g = new Graph(7); 60 | g.addEdge(0,1, true); 61 | g.addEdge(1,2, true); 62 | g.addEdge(2,3, true); 63 | g.addEdge(3,5, true); 64 | g.addEdge(5,6, true); 65 | g.addEdge(4,5, true); 66 | g.addEdge(0,4, true); 67 | g.addEdge(3,4, true); 68 | g.bfs(1); 69 | 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /G1: Basic Graph (BFS, DFS)/BfsShortestPath.java: -------------------------------------------------------------------------------- 1 | package BreadthFirstSearch; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | public class BfsShortestPath { 9 | 10 | static class Graph{ 11 | int V; 12 | ArrayList[] list; 13 | 14 | public Graph(int v){ 15 | V = v; 16 | list = new ArrayList[v]; 17 | for(int i = 0; i < v; i++){ 18 | list[i] = new ArrayList<>(); 19 | } 20 | } 21 | 22 | void addEdge(int i, int j, boolean unDirected){ 23 | list[i].add(j); 24 | if(unDirected) 25 | list[j].add(i); 26 | } 27 | 28 | void bfs(int source,int dest){ 29 | 30 | Queue q = new LinkedList<>(); 31 | boolean[] visited = new boolean[V]; 32 | Arrays.fill(visited, false); 33 | 34 | int[] dist = new int[V]; 35 | int[] parent = new int[V]; 36 | 37 | for(int i=0;i[] graph, int node, int[] visited, int parent, int color){ 9 | //come to node 10 | visited[node] = color; //1 or 2, both mean visited 11 | 12 | for(int nbr : graph[node]){ 13 | 14 | if(visited[nbr]==0){ 15 | boolean subProb = dfs_helper(graph,nbr,visited,node,3-color); 16 | 17 | if(!subProb){ 18 | return false; 19 | } 20 | 21 | } 22 | else if(nbr!=parent && color==visited[nbr]){ 23 | return false; 24 | } 25 | 26 | } 27 | return true; 28 | } 29 | 30 | 31 | static boolean dfs(ArrayList[] graph, int N){ 32 | 33 | int[] visited = new int[N]; // 0- Not Visited, 1 - Visited Color is 1, 2 - Visted Color 2 34 | 35 | int color = 1; 36 | boolean ans = dfs_helper(graph,0,visited,-1,color); 37 | //later one 38 | 39 | //colors 40 | for(int i=0;i[] graph = new ArrayList[N]; 53 | for(int i = 0; i < N; i++){ 54 | graph[i] = new ArrayList<>(); 55 | } 56 | 57 | while(M-- > 0){ 58 | int x = scn.nextInt(), y = scn.nextInt(); 59 | 60 | graph[x].add(y); 61 | graph[y].add(x); 62 | 63 | } 64 | 65 | //BFS or DFS, by coloring the nodes at each step (current node has color 1, nbr should have a color 2) 66 | if(dfs(graph,N)){ 67 | System.out.println("Yes its bipartite"); 68 | } 69 | else{ 70 | System.out.println("Not bipartite"); 71 | } 72 | 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /G1: Basic Graph (BFS, DFS)/CycleDetectionDirected.java: -------------------------------------------------------------------------------- 1 | package CycleDetection; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class CycleDetectionDirected { 6 | 7 | static class Graph { 8 | int V; 9 | ArrayList[] list; 10 | 11 | public Graph(int v) { 12 | V = v; 13 | list = new ArrayList[v]; 14 | for (int i = 0; i < v; i++) { 15 | list[i] = new ArrayList<>(); 16 | } 17 | } 18 | 19 | void addEdge(int i, int j) { 20 | list[i].add(j); 21 | } 22 | 23 | boolean dfs(int node,boolean[] visited, boolean[] stack){ 24 | //arrive at node 25 | visited[node] = true; 26 | stack[node] = true; 27 | 28 | //do some work at node,return true if backedge is found here itself 29 | for(int nbr : list[node]){ 30 | 31 | if(stack[nbr]){ 32 | return true; 33 | } 34 | else if(!visited[nbr]){ 35 | boolean nbrFoundACycle = dfs(nbr,visited,stack); 36 | if(nbrFoundACycle){ 37 | return true; 38 | } 39 | } 40 | } 41 | 42 | //going back 43 | stack[node] = false; 44 | return false; 45 | } 46 | 47 | boolean contains_cycle(){ 48 | boolean[] visited = new boolean[V]; 49 | boolean[] stack = new boolean[V]; 50 | 51 | for(int i=0;i[] list; 10 | 11 | public Graph(int v) { 12 | V = v; 13 | list = new ArrayList[v]; 14 | for (int i = 0; i < v; i++) { 15 | list[i] = new ArrayList<>(); 16 | } 17 | } 18 | 19 | void addEdge(int i, int j) { 20 | list[i].add(j); 21 | list[j].add(i); 22 | } 23 | 24 | boolean dfs(int node, boolean[] visited, int parent){ 25 | //mark that node visited 26 | visited[node] = true; 27 | 28 | for(int nbr : list[node]){ 29 | 30 | if(!visited[nbr]){ 31 | 32 | boolean nbrFoundACycle = dfs(nbr,visited,node); 33 | if(nbrFoundACycle){ 34 | return true; 35 | } 36 | } 37 | //nbr is visited and its not the parent of current node in the current dfs call 38 | else if(nbr!=parent){ 39 | return true; 40 | } 41 | } 42 | return false; 43 | } 44 | 45 | boolean contains_cycle(){ 46 | //Graph is single component 47 | boolean[] visited = new boolean[V]; 48 | return dfs(0, visited, -1); 49 | } 50 | 51 | } 52 | 53 | public static void main(String[] args){ 54 | 55 | Graph g = new Graph(3); 56 | // g.addEdge(0,1); 57 | g.addEdge(2,0); 58 | g.addEdge(2,0); 59 | 60 | System.out.println(g.contains_cycle()); 61 | 62 | } 63 | 64 | } 65 | 66 | -------------------------------------------------------------------------------- /G1: Basic Graph (BFS, DFS)/bipartitie.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool dfs_helper(vector graph[],int node,int *visited,int parent, int color){ 6 | //come to node 7 | visited[node] = color; //1 or 2, both mean visited 8 | 9 | for(auto nbr : graph[node]){ 10 | 11 | if(visited[nbr]==0){ 12 | int subprob = dfs_helper(graph,nbr,visited,node,3-color); 13 | 14 | if(subprob==false){ 15 | return false; 16 | } 17 | 18 | } 19 | else if(nbr!=parent and color==visited[nbr]){ 20 | return false; 21 | } 22 | 23 | } 24 | return true; 25 | } 26 | 27 | 28 | bool dfs(vector graph[],int N){ 29 | 30 | int visited[N] = {0}; // 0- Not Visited, 1 - Visited Color is 1, 2 - Visted Color 2 31 | 32 | int color = 1; 33 | int ans = dfs_helper(graph,0,visited,-1,color); 34 | //later one 35 | 36 | //colors 37 | for(int i=0;i>N>>M; 50 | 51 | vector graph[N]; 52 | while(M--){ 53 | int x,y; 54 | cin>>x>>y; 55 | 56 | graph[x].push_back(y); 57 | graph[y].push_back(x); 58 | 59 | } 60 | 61 | //BFS or DFS, by coloring the nodes at each step (current node has color 1, nbr should have a color 2) 62 | if(dfs(graph,N)){ 63 | cout<<"Yes its bipartite"; 64 | } 65 | else{ 66 | cout<<"Not bipartite"; 67 | } 68 | 69 | 70 | 71 | return 0; 72 | } 73 | 74 | -------------------------------------------------------------------------------- /G1: Basic Graph (BFS, DFS)/cycle_detection_directed.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | list *l; 8 | int V; 9 | 10 | public: 11 | Graph(int V){ 12 | this->V = V; 13 | l = new list[V]; 14 | } 15 | 16 | void addEdge(int x,int y){ 17 | l[x].push_back(y); 18 | } 19 | 20 | bool dfs(int node,vector &visited, vector &stack){ 21 | //arrive at node 22 | visited[node] = true; 23 | stack[node] = true; 24 | 25 | //do some work at node,return true if backedge is found here itself 26 | for(int nbr : l[node]){ 27 | 28 | if(stack[nbr]==true){ 29 | return true; 30 | } 31 | else if(visited[nbr]==false){ 32 | bool nbrFoundACycle = dfs(nbr,visited,stack); 33 | if(nbrFoundACycle){ 34 | return true; 35 | } 36 | } 37 | } 38 | 39 | //going back 40 | stack[node] = false; 41 | return false; 42 | } 43 | 44 | bool contains_cycle(){ 45 | vector visited(V,false); 46 | vector stack(V,false); 47 | 48 | for(int i=0;i > edges){ 63 | //Complete this method 64 | 65 | Graph g(V); 66 | for(auto edge : edges){ 67 | g.addEdge(edge.first,edge.second); 68 | } 69 | return g.contains_cycle(); 70 | 71 | } 72 | 73 | int main(){ 74 | 75 | Graph g(3); 76 | g.addEdge(0,1); 77 | g.addEdge(1,2); 78 | g.addEdge(2,0); 79 | 80 | cout << g.contains_cycle() < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | list *l; 8 | int V; 9 | 10 | public: 11 | Graph(int V){ 12 | this->V = V; 13 | l = new list[V]; 14 | } 15 | 16 | //undirected graph 17 | void addEdge(int x,int y){ 18 | l[x].push_back(y); 19 | l[y].push_back(x); 20 | } 21 | bool dfs(int node, vector &visited, int parent){ 22 | //mark that node visited 23 | visited[node] = true; 24 | 25 | for(auto nbr : l[node]){ 26 | 27 | if(!visited[nbr]){ 28 | 29 | bool nbrFoundACycle = dfs(nbr,visited,node); 30 | if(nbrFoundACycle){ 31 | return true; 32 | } 33 | } 34 | //nbr is visited and its not the parent of current node in the current dfs call 35 | else if(nbr!=parent){ 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | 42 | bool contains_cycle(){ 43 | //Graph is single component 44 | vector visited(V,false); 45 | return dfs(0, visited, -1); 46 | } 47 | 48 | }; 49 | 50 | bool contains_cycle(int V,vector > edges){ 51 | //Complete this method 52 | 53 | Graph g(V); 54 | for(auto edge:edges){ 55 | g.addEdge(edge.first,edge.second); 56 | } 57 | return g.contains_cycle(); 58 | 59 | } 60 | 61 | int main(){ 62 | 63 | Graph g(3); 64 | g.addEdge(0,1); 65 | g.addEdge(1,2); 66 | //g.addEdge(2,0); 67 | 68 | cout << g.contains_cycle() <[] list; 14 | 15 | public Graph(int v){ 16 | V = v; 17 | list = new ArrayList[v]; 18 | for(int i = 0; i < v; i++){ 19 | list[i] = new ArrayList<>(); 20 | } 21 | } 22 | 23 | void addEdge(int i, int j, boolean unDirected){ 24 | list[i].add(j); 25 | if(unDirected) 26 | list[j].add(i); 27 | } 28 | 29 | private void dfsHelper(int source, boolean[] visited){ 30 | visited[source] = true; 31 | System.out.print(source + " "); 32 | 33 | for(int nbr: list[source]){ 34 | if(!visited[nbr]){ 35 | dfsHelper(nbr, visited); 36 | } 37 | } 38 | } 39 | 40 | void dfs(int source){ 41 | boolean[] visited = new boolean[V]; 42 | Arrays.fill(visited, false); 43 | dfsHelper(source, visited); 44 | } 45 | 46 | 47 | } 48 | 49 | public static void main(String[] args){ 50 | 51 | Graph g = new Graph(7); 52 | g.addEdge(0,1, true); 53 | g.addEdge(1,2, true); 54 | g.addEdge(2,3, true); 55 | g.addEdge(3,5, true); 56 | g.addEdge(5,6, true); 57 | g.addEdge(4,5, true); 58 | g.addEdge(0,4, true); 59 | g.addEdge(3,4, true); 60 | g.dfs(1); 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /G1: Basic Graph (BFS, DFS)/graphwithedges.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | class Node{ 10 | public: 11 | string name; 12 | list nbrs; 13 | Node(string name){ 14 | this->name= name; 15 | } 16 | }; 17 | class Graph{ 18 | unordered_map ma; 19 | public: 20 | Graph(vector datas){ 21 | for(auto data : datas){ 22 | ma[data]= new Node(data); 23 | } 24 | } 25 | void addEdge(string x, string y, bool undir=false){ 26 | ma[x]->nbrs.push_back(y); 27 | if(undir){ 28 | ma[y]->nbrs.push_back(x); 29 | } 30 | } 31 | void PrintAdjList(){ 32 | for(auto citypair : ma){ 33 | auto city = citypair.first; 34 | cout< "; 35 | Node *node = citypair.second; 36 | for(auto nbr : node->nbrs){ 37 | cout<< nbr << " "; 38 | } 39 | cout< vis; 47 | unordered_map dis; 48 | for(auto i:ma){ 49 | vis[i.first]= 0; 50 | dis[i.first]= INT_MAX; 51 | } 52 | vis[beginWord]=1; 53 | dis[beginWord]=1; 54 | queue cont; 55 | cont.push(beginWord); 56 | while(!cont.empty()){ 57 | string u= cont.front(); 58 | cont.pop(); 59 | //cout<nbrs){ 61 | if(vis[j]==false){ 62 | string v= j; 63 | vis[v]=true; 64 | dis[v]= dis[u]+1; 65 | cont.push(v); 66 | } 67 | } 68 | } 69 | if(ma.count(endWord)!=0){ 70 | if(dis[endWord]==INT_MAX) return 0; 71 | else return dis[endWord]; 72 | } 73 | return 0; 74 | 75 | } 76 | 77 | }; 78 | bool isonewordaway(string a, string b){ 79 | int len= a.length(); 80 | int count=0; 81 | for(int i=0; i& wordList) 89 | { 90 | //https://leetcode.com/problems/word-ladder/ 91 | wordList.push_back(beginWord); 92 | Graph g = Graph(wordList); 93 | int wlistlen= wordList.size(); 94 | for(int i=0; i wordli = {"hot","dot","dog","lot","log","cog"}; 108 | cout<[] list; 13 | 14 | public Graph(int v){ 15 | V = v; 16 | list = new ArrayList[v]; 17 | for(int i = 0; i < v; i++){ 18 | list[i] = new ArrayList<>(); 19 | } 20 | } 21 | 22 | void addEdge(int i, int j, boolean bidir){ 23 | list[i].add(j); 24 | if(bidir){ 25 | list[j].add(i); 26 | } 27 | } 28 | 29 | void bfs(int s){ 30 | Queue q = new LinkedList<>(); 31 | q.add(s); 32 | 33 | 34 | int[] dist = new int[V]; 35 | //Init all nodes with inf dist 36 | for(int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | class Graph{ 8 | int V; 9 | public: 10 | list *l; 11 | 12 | Graph(int v){ 13 | V = v; 14 | l = new list[V]; 15 | } 16 | 17 | void addEdge(int u,int v,bool bidir=true){ 18 | l[u].push_back(v); 19 | if(bidir){ 20 | l[v].push_back(u); 21 | } 22 | } 23 | //Iterate using a loop - Breadth First Search 24 | void bfs(int s){ 25 | queue q; 26 | q.push(s); 27 | 28 | 29 | int *dist = new int[V]; 30 | //Init all nodes with inf dist 31 | for(int i=0;i 3 | using namespace std; 4 | 5 | // Dimensions of paint screen 6 | #define M 8 7 | #define N 8 8 | 9 | // A recursive function to replace previous color 'prevC' at '(x, y)' 10 | // and all surrounding pixels of (x, y) with new color 'newC' and 11 | void floodFillUtil(int screen[][N], int x, int y, int prevC, int newC) 12 | { 13 | // Base cases 14 | if (x < 0 || x >= M || y < 0 || y >= N) 15 | return; 16 | if (screen[x][y] != prevC) 17 | return; 18 | if (screen[x][y] == newC) 19 | return; 20 | 21 | // Replace the color at (x, y) 22 | screen[x][y] = newC; 23 | 24 | // Recur for north, east, south and west 25 | floodFillUtil(screen, x+1, y, prevC, newC); 26 | floodFillUtil(screen, x-1, y, prevC, newC); 27 | floodFillUtil(screen, x, y+1, prevC, newC); 28 | floodFillUtil(screen, x, y-1, prevC, newC); 29 | } 30 | 31 | // It mainly finds the previous color on (x, y) and 32 | // calls floodFillUtil() 33 | void floodFill(int screen[][N], int x, int y, int newC) 34 | { 35 | int prevC = screen[x][y]; 36 | if(prevC==newC) return; 37 | floodFillUtil(screen, x, y, prevC, newC); 38 | } 39 | 40 | // Driver code 41 | int main() 42 | { 43 | int screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1}, 44 | {1, 1, 1, 1, 1, 1, 0, 0}, 45 | {1, 0, 0, 1, 1, 0, 1, 1}, 46 | {1, 2, 2, 2, 2, 0, 1, 0}, 47 | {1, 1, 1, 2, 2, 0, 1, 0}, 48 | {1, 1, 1, 2, 2, 2, 2, 0}, 49 | {1, 1, 1, 1, 1, 2, 1, 1}, 50 | {1, 1, 1, 1, 1, 2, 2, 1}, 51 | }; 52 | int x = 4, y = 4, newC = 3; 53 | floodFill(screen, x, y, newC); 54 | 55 | cout << "Updated screen after call to floodFill: \n"; 56 | for (int i=0; i 2 | using namespace std; 3 | #define IO ios_base :: sync_with_stdio(0),cin.tie(0) 4 | #define ll long long int 5 | #define ull unsigned long long int 6 | 7 | #define WHITE 0 //Not visited 8 | #define GREY 1 //Started visiting 9 | #define BLACK 2 //Finished visiting 10 | 11 | 12 | int depth[1005][1005]; //Keep track of the distance 13 | int color[1005][1005]; //Keep track of the color 14 | char grid[1005][1005]; //The given grid 15 | 16 | //Important Concept : In grid we can move to four sides, there dx[i], dy[i] easily 17 | //keep track of where to go next 18 | int dx[4] = {0,0,-1,1}; 19 | int dy[4] = {-1,1,0,0}; 20 | 21 | int BFS(int n,int m,int sx, int sy, int desx, int desy){ 22 | //We will apply simple BFS on Grid 23 | queueq; //A queue to keep track which box visited or not 24 | 25 | int vx,vy,ux,uy; //u is the current working box and v is any adjacent box of u 26 | 27 | while(!q.empty()) q.pop(); //Making the queue empty 28 | 29 | q.push(sx); 30 | q.push(sy); 31 | 32 | color[sx][sy] = GREY; 33 | depth[sx][sy] = 0; 34 | 35 | while(!q.empty()){ 36 | ux = q.front(); 37 | q.pop(); 38 | 39 | uy = q.front(); 40 | q.pop(); 41 | 42 | for(int i=0; i<4; i++) 43 | { 44 | vx = ux + dx[i]; 45 | vy = uy + dy[i]; 46 | 47 | if(vx>=0 && vx=0 && vy 4 | using namespace std; 5 | 6 | // structure for storing a cell's data 7 | struct cell { 8 | int x, y; 9 | int dis; 10 | cell() {} 11 | cell(int x, int y, int dis) 12 | : x(x), y(y), dis(dis) 13 | { 14 | } 15 | }; 16 | 17 | // Utility method returns true if (x, y) lies 18 | // inside Board 19 | bool isInside(int x, int y, int N) 20 | { 21 | if (x >= 1 && x <= N && y >= 1 && y <= N) 22 | return true; 23 | return false; 24 | } 25 | 26 | // Method returns minimum step 27 | // to reach target position 28 | int minStepToReachTarget( 29 | int knightPos[], int targetPos[], 30 | int N) 31 | { 32 | // x and y direction, where a knight can move 33 | int dx[] = { -2, -1, 1, 2, -2, -1, 1, 2 }; 34 | int dy[] = { -1, -2, -2, -1, 1, 2, 2, 1 }; 35 | 36 | // queue for storing states of knight in board 37 | queue q; 38 | 39 | // push starting position of knight with 0 distance 40 | q.push(cell(knightPos[0], knightPos[1], 0)); 41 | 42 | cell t; 43 | int x, y; 44 | bool visit[N + 1][N + 1]; 45 | 46 | // make all cell unvisited 47 | for (int i = 1; i <= N; i++) 48 | for (int j = 1; j <= N; j++) 49 | visit[i][j] = false; 50 | 51 | // visit starting state 52 | visit[knightPos[0]][knightPos[1]] = true; 53 | 54 | // loop until we have one element in queue 55 | while (!q.empty()) { 56 | t = q.front(); 57 | q.pop(); 58 | 59 | // if current cell is equal to target cell, 60 | // return its distance 61 | if (t.x == targetPos[0] && t.y == targetPos[1]) 62 | return t.dis; 63 | 64 | // loop for all reachable states 65 | for (int i = 0; i < 8; i++) { 66 | x = t.x + dx[i]; 67 | y = t.y + dy[i]; 68 | 69 | // If reachable state is not yet visited and 70 | // inside board, push that state into queue 71 | if (isInside(x, y, N) && !visit[x][y]) { 72 | visit[x][y] = true; 73 | q.push(cell(x, y, t.dis + 1)); 74 | } 75 | } 76 | } 77 | } 78 | 79 | // Driver code to test above methods 80 | int main() 81 | { 82 | int N = 30; 83 | int knightPos[] = { 1, 1 }; 84 | int targetPos[] = { 30, 30 }; 85 | cout << minStepToReachTarget(knightPos, targetPos, N); 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /G2: Grid Recursion/ratinamze.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ implementation of the above approach 3 | #include 4 | #define MAX 5 5 | using namespace std; 6 | 7 | // Function returns true if the 8 | // move taken is valid else 9 | // it will return false. 10 | bool isSafe(int row, int col, int m[][MAX], 11 | int n, bool visited[][MAX]) 12 | { 13 | if (row == -1 || row == n || col == -1 || 14 | col == n || visited[row][col] 15 | || m[row][col] == 0) 16 | return false; 17 | 18 | return true; 19 | } 20 | 21 | // Function to print all the possible 22 | // paths from (0, 0) to (n-1, n-1). 23 | void printPathUtil(int row, int col, int m[][MAX], 24 | int n, string& path, vector& 25 | possiblePaths, bool visited[][MAX]) 26 | { 27 | // This will check the initial point 28 | // (i.e. (0, 0)) to start the paths. 29 | if (row == -1 || row == n || col == -1 30 | || col == n || visited[row][col] 31 | || m[row][col] == 0) 32 | return; 33 | 34 | // If reach the last cell (n-1, n-1) 35 | // then store the path and return 36 | if (row == n - 1 && col == n - 1) { 37 | possiblePaths.push_back(path); 38 | return; 39 | } 40 | 41 | // Mark the cell as visited 42 | visited[row][col] = true; 43 | 44 | // Try for all the 4 directions (down, left, 45 | // right, up) in the given order to get the 46 | // paths in lexicographical order 47 | 48 | // Check if downward move is valid 49 | if (isSafe(row + 1, col, m, n, visited)) 50 | { 51 | path.push_back('D'); 52 | printPathUtil(row + 1, col, m, n, 53 | path, possiblePaths, visited); 54 | path.pop_back(); 55 | } 56 | 57 | // Check if the left move is valid 58 | if (isSafe(row, col - 1, m, n, visited)) 59 | { 60 | path.push_back('L'); 61 | printPathUtil(row, col - 1, m, n, 62 | path, possiblePaths, visited); 63 | path.pop_back(); 64 | } 65 | 66 | // Check if the right move is valid 67 | if (isSafe(row, col + 1, m, n, visited)) 68 | { 69 | path.push_back('R'); 70 | printPathUtil(row, col + 1, m, n, 71 | path, possiblePaths, visited); 72 | path.pop_back(); 73 | } 74 | 75 | // Check if the upper move is valid 76 | if (isSafe(row - 1, col, m, n, visited)) 77 | { 78 | path.push_back('U'); 79 | printPathUtil(row - 1, col, m, n, 80 | path, possiblePaths, visited); 81 | path.pop_back(); 82 | } 83 | 84 | // Mark the cell as unvisited for 85 | // other possible paths 86 | visited[row][col] = false; 87 | } 88 | 89 | // Function to store and print 90 | // all the valid paths 91 | void printPath(int m[MAX][MAX], int n) 92 | { 93 | // vector to store all the possible paths 94 | vector possiblePaths; 95 | string path; 96 | bool visited[n][MAX]; 97 | memset(visited, false, sizeof(visited)); 98 | 99 | // Call the utility function to 100 | // find the valid paths 101 | printPathUtil(0, 0, m, n, path, 102 | possiblePaths, visited); 103 | 104 | // Print all possible paths 105 | for (int i = 0; i < possiblePaths.size(); i++) 106 | cout << possiblePaths[i] << " "; 107 | } 108 | 109 | // Driver code 110 | int main() 111 | { 112 | int m[MAX][MAX] = { { 1, 0, 0, 0, 0 }, 113 | { 1, 1, 1, 1, 1 }, 114 | { 1, 1, 1, 0, 1 }, 115 | { 0, 0, 0, 0, 1 }, 116 | { 0, 0, 0, 0, 1 } }; 117 | int n = sizeof(m) / sizeof(m[0]); 118 | printPath(m, n); 119 | 120 | return 0; 121 | } 122 | -------------------------------------------------------------------------------- /G4: Disjoint Set Union/DSUrankPathCompression.java: -------------------------------------------------------------------------------- 1 | package DisjointSetUnion; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class DSUrankPathCompression { 7 | 8 | static class Pair{ 9 | public int first, second; 10 | public Pair(int a, int b){ 11 | first = a; 12 | second = b; 13 | } 14 | } 15 | 16 | 17 | static class Graph{ 18 | int V; 19 | List l; 20 | 21 | 22 | public Graph(int V){ 23 | this.V = V; 24 | this.l = new ArrayList<>(); 25 | } 26 | 27 | void addEdge(int u,int v){ 28 | l.add(new Pair(u,v)); 29 | } 30 | // Find 31 | int findSet(int i,int parent[]){ 32 | if(parent[i]==-1){ 33 | return i; 34 | } 35 | int p = findSet(parent[i],parent); 36 | //compress the path for next time 37 | parent[i] = p; 38 | return p; 39 | 40 | } 41 | 42 | 43 | //Union 44 | void union_set(int u,int v,int rank[],int parent[]){ 45 | 46 | int p1 = findSet(u,parent); 47 | int p2 = findSet(v,parent); 48 | 49 | if(p1!=p2){ 50 | if(rank[p1] 2 | using namespace std; 3 | const int MAXN = 1e5; 4 | // Link: https://cp-algorithms.com/data_structures/disjoint_set_union.html 5 | int parent[MAXN]; 6 | int size[MAXN]; 7 | void makeset(int v) 8 | { 9 | /* 10 | To create a new set (operation make_set(v)), 11 | we simply create a tree with root in the vertex v, 12 | meaning that it is its own ancestor. 13 | */ 14 | parent[v] = v; 15 | size[v] = 1; 16 | } 17 | int findset(int v) 18 | { 19 | /* 20 | Finally the implementation of the find representative 21 | function (operation find_set(v)): we simply climb the 22 | ancestors of the vertex v until we reach the root, i.e. 23 | a vertex such that the reference to the ancestor leads to 24 | itself. This operation is easily implemented recursively. 25 | */ 26 | if (v == parent[v]) 27 | return v; 28 | //return findset(parent[v]); // Without Path Compression 29 | return parent[v] = findset(parent[v]); 30 | /* 31 | ****make the paths for all those nodes shorter, by setting the parent of each visited vertex directly to p. 32 | ****first find the representative of the set (root vertex), and then in the process of stack unwinding the visited 33 | nodes are attached directly to the representative. 34 | 35 | */ 36 | } 37 | void unionset(int a, int b) 38 | { 39 | /* 40 | To combine two sets (operation union_sets(a, b)), we first find 41 | he representative of the set in which a is located, and the 42 | representative of the set in which b is located. If the representatives 43 | are identical, that we have nothing to do, the sets are already merged. 44 | Otherwise, we can simply specify that one of the representatives is the 45 | parent of the other representative - thereby combining the two trees. 46 | */ 47 | a = findset(a); 48 | b = findset(b); 49 | if (a != b) 50 | { 51 | if (size[a] < size[b]) 52 | swap(a, b); 53 | parent[b] = a; 54 | size[a] += size[b]; 55 | } 56 | } 57 | int main() 58 | { 59 | ios_base::sync_with_stdio(false); 60 | cin.tie(NULL); 61 | 62 | return 0; 63 | } 64 | /* 65 | Time complexity 66 | 67 | As mentioned before, if we combine both optimizations - path compression with union by size / rank - we will reach nearly constant time queries. It turns out, that the final amortized time complexity is 68 | , where is the inverse Ackermann function, which grows very slowly. In fact it grows so slowly, that it doesn't exceed for all reasonable (approximately 69 | 70 | ). 71 | 72 | Amortized complexity is the total time per operation, evaluated over a sequence of multiple operations. The idea is to guarantee the total time of the entire sequence, while allowing single operations to be much slower then the amortized time. E.g. 73 | in our case a single call might take 74 | in the worst case, but if we do such calls back to back we will end up with an average time of 75 | 76 | . 77 | 78 | We will also not present a proof for this time complexity, since it is quite long and complicated. 79 | Also, it's worth mentioning that DSU with union by size / rank, but without path compression works in 80 | time per query. 81 | */ -------------------------------------------------------------------------------- /G4: Disjoint Set Union/dsu2.cpp: -------------------------------------------------------------------------------- 1 | //12 2 | //12 3 | //12 4 | #include 5 | using namespace std; 6 | const int MAXN = 1e6; 7 | int track1[MAXN]; 8 | int track2[MAXN]; 9 | void makesetfrominp(int v) 10 | { 11 | track1[v] = v; 12 | track2[v] = 1; 13 | } 14 | int findsetandreturnidentifier(int v) 15 | { 16 | if (v == track1[v]) 17 | return v; 18 | return track1[v] = findsetandreturnidentifier(track1[v]); 19 | } 20 | void uniongivenset(int a, int b) 21 | { 22 | a = findsetandreturnidentifier(a); 23 | b = findsetandreturnidentifier(b); 24 | if (a != b) 25 | { 26 | if (track2[a] < track2[b]) 27 | swap(a, b); 28 | track1[b] = a;track2[a] += track2[b]; 29 | } 30 | } 31 | int main() 32 | { 33 | ios_base::sync_with_stdio(false); 34 | cin.tie(NULL); 35 | int n, k; 36 | cin >> n >> k; 37 | for (int i = 0; i < n; ++i) 38 | { 39 | makesetfrominp(i); 40 | } 41 | while (k--) 42 | { 43 | string s; int a,b; 44 | cin>>s>>a>>b; 45 | if(s=="JOIN"){ 46 | uniongivenset(a,b); 47 | 48 | } 49 | else { 50 | if(findsetandreturnidentifier(a)==findsetandreturnidentifier(b)) cout<<"Yes"<[] gr = new ArrayList[N]; 22 | static Set arti_points = new HashSet<>(); 23 | static { 24 | for(int i = 0 ; i < N ; i++){ 25 | gr[i] = new ArrayList<>(); 26 | } 27 | } 28 | 29 | static int tme = 1; 30 | static boolean[] vis = new boolean[N]; 31 | static int[] disc = new int[N]; 32 | static int[] low = new int[N]; 33 | 34 | static ArrayList bridges = new ArrayList<>(); 35 | 36 | static void dfs(int cur, int par) { 37 | vis[cur] = true; 38 | disc[cur] = low[cur] = tme++; 39 | int child = 0; 40 | for (int x : gr[cur]) { 41 | 42 | if (!vis[x]) { 43 | dfs(x, cur); 44 | child++; 45 | // we know low and disc of x 46 | low[cur] = Math.min(low[cur], low[x]); 47 | 48 | // bridges 49 | if (low[x] > disc[cur]) { 50 | bridges.add(new Pair(cur, x)); 51 | } 52 | 53 | // articulation points 54 | if (par != 0 && low[x] >= disc[cur]) { 55 | arti_points.add(cur); 56 | } 57 | 58 | } 59 | else if (x != par) { 60 | // backedge 61 | low[cur] = Math.min(low[cur], disc[x]); 62 | } 63 | } 64 | 65 | // root is an arti or not 66 | if (par == 0 && child > 1) { 67 | arti_points.add(cur); 68 | } 69 | 70 | } 71 | 72 | 73 | public static void main(String[] args) 74 | { 75 | Scanner scn = new Scanner(System.in); 76 | int n = scn.nextInt(), m = scn.nextInt(); 77 | 78 | for (int i = 0; i < m; i++) { 79 | int x = scn.nextInt(), y = scn.nextInt(); 80 | gr[x].add(y); 81 | gr[y].add(x); 82 | 83 | } 84 | 85 | dfs(1, 0); 86 | 87 | for (int x : arti_points) System.out.println(x); 88 | 89 | for (Pair x : bridges) { 90 | System.out.println( x.first + " " + x.second ); 91 | } 92 | 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /G5: Bridge Articulation Point/EulerTour.java: -------------------------------------------------------------------------------- 1 | package EulerTour; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class EulerTour { 7 | 8 | static final int N = (int) (1e5 + 1); 9 | 10 | static ArrayList[] gr = new ArrayList[N]; 11 | 12 | static { 13 | for(int i = 0; i < N; i++){ 14 | gr[i] = new ArrayList<>(); 15 | } 16 | } 17 | 18 | 19 | static void dfs1(int cur, int par) { 20 | // time in 21 | System.out.print(cur + " "); 22 | for (int x : gr[cur]) { 23 | if (x != par) { 24 | // x is child node 25 | dfs1(x, cur); 26 | } 27 | } 28 | // time out 29 | System.out.print(cur + " "); 30 | } 31 | 32 | static void dfs2(int cur, int par) { 33 | System.out.print(cur + " "); 34 | for (int x : gr[cur]) { 35 | if (x != par) { 36 | // x is child node 37 | dfs2(x, cur); 38 | System.out.print(cur + " "); 39 | } 40 | } 41 | } 42 | 43 | public static void main(String[] args){ 44 | 45 | Scanner scn = new Scanner(System.in); 46 | int n = scn.nextInt(); 47 | for (int i = 0; i < n-1; i++) { 48 | int x = scn.nextInt(), y = scn.nextInt(); 49 | gr[x].add(y); 50 | gr[y].add(x); 51 | 52 | } 53 | 54 | 55 | // dfs1(1, 0); 56 | 57 | dfs2(1, 0); 58 | 59 | } 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /G5: Bridge Articulation Point/articulation point and bridges.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5; 6 | 7 | vector gr[N]; 8 | 9 | int vis[N], disc[N], low[N], tme = 1; 10 | 11 | vector> bridges; 12 | set arti_points; 13 | 14 | void dfs(int cur, int par) { 15 | vis[cur] = 1; 16 | disc[cur] = low[cur] = tme++; 17 | int child = 0; 18 | for (auto x : gr[cur]) { 19 | 20 | if (!vis[x]) { 21 | dfs(x, cur); 22 | child++; 23 | // we know low and disc of x 24 | low[cur] = min(low[cur], low[x]); 25 | 26 | // bridges 27 | if (low[x] > disc[cur]) { 28 | bridges.push_back({cur, x}); 29 | } 30 | 31 | // articulation points 32 | if (par != 0 && low[x] >= disc[cur]) { 33 | arti_points.insert(cur); 34 | } 35 | 36 | } 37 | else if (x != par) { 38 | // backedge 39 | low[cur] = min(low[cur], disc[x]); 40 | } 41 | } 42 | 43 | // root is an arti or not 44 | if (par == 0 && child > 1) { 45 | arti_points.insert(cur); 46 | } 47 | 48 | return; 49 | } 50 | 51 | 52 | int main() 53 | { 54 | freopen("input.txt", "r", stdin); 55 | freopen("output.txt", "w", stdout); 56 | 57 | int n, m; 58 | cin >> n >> m; 59 | 60 | for (int i = 0; i < m; i++) { 61 | int x, y; 62 | cin >> x >> y; 63 | gr[x].push_back(y); 64 | gr[y].push_back(x); 65 | } 66 | 67 | dfs(1, 0); 68 | 69 | for (auto x : arti_points) cout << x << '\n'; 70 | 71 | for (auto x : bridges) { 72 | cout << x.first << " " << x.second << '\n'; 73 | } 74 | 75 | return 0; 76 | } -------------------------------------------------------------------------------- /G5: Bridge Articulation Point/bestEulerTour.java: -------------------------------------------------------------------------------- 1 | package EulerTour; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class bestEulerTour { 7 | 8 | 9 | 10 | static final int N = (int) (1e5 + 1); 11 | 12 | static ArrayList[] gr = new ArrayList[N]; 13 | 14 | static { 15 | for(int i = 0; i < N; i++){ 16 | gr[i] = new ArrayList<>(); 17 | } 18 | } 19 | static int[] tin = new int[N]; 20 | static int[] tout = new int[N]; 21 | static int[] flat = new int[N]; 22 | static int tme = 0; 23 | 24 | static void dfs1(int cur, int par) { 25 | tin[cur] = tme++; 26 | for (int x : gr[cur]) { 27 | if (x != par) { 28 | // x is child node 29 | dfs1(x, cur); 30 | } 31 | } 32 | tout[cur] = tme++; 33 | } 34 | 35 | static void dfs2(int cur, int par) { 36 | System.out.println(cur + " "); 37 | for (int x : gr[cur]) { 38 | if (x != par) { 39 | // x is child node 40 | dfs2(x, cur); 41 | System.out.println(cur + " "); 42 | } 43 | } 44 | } 45 | 46 | static void dfs3(int cur, int par) { 47 | tin[cur] = ++tme; 48 | for (int x : gr[cur]) { 49 | if (x != par) { 50 | // x is child node 51 | dfs3(x, cur); 52 | } 53 | } 54 | tout[cur] = tme; 55 | } 56 | 57 | public static void main(String[] args){ 58 | 59 | Scanner scn = new Scanner(System.in); 60 | int n = scn.nextInt(); 61 | for (int i = 0; i < n-1; i++) { 62 | int x = scn.nextInt(), y = scn.nextInt(); 63 | gr[x].add(y); 64 | gr[y].add(x); 65 | } 66 | 67 | 68 | // tme = 1; 69 | // dfs1(1, 0); 70 | 71 | 72 | // dfs2(1, 0); 73 | 74 | tme = 0; 75 | dfs3(1, 0); 76 | 77 | for (int i = 1; i <= n; i++) { 78 | System.out.println(i + " " + tin[i] + " " + tout[i] ); 79 | } 80 | 81 | for (int i = 1; i <= n; i++) { 82 | flat[tin[i]] = i; 83 | } 84 | 85 | for (int i = 1; i <= n; i++) { 86 | System.out.print(flat[i] + " "); 87 | } 88 | 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /G5: Bridge Articulation Point/bridge.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | 5 | const int MAXN = 1e3; 6 | class Graph 7 | { 8 | int V; 9 | vector l[MAXN]; 10 | vector> br; 11 | int dis[MAXN], fin[MAXN], pre[MAXN], vis[MAXN], low[MAXN], ap[MAXN]; 12 | ll time; 13 | 14 | public: 15 | Graph(int V) 16 | { 17 | this->V = V; 18 | }; 19 | void add_new_edge(int v, int w) 20 | { 21 | l[v].push_back(w); 22 | l[w].push_back(v); 23 | } 24 | int dfsAP(int u, int p) 25 | { 26 | int children = 0; 27 | low[u] = dis[u] = ++time; 28 | for (int &v : l[u]) 29 | { 30 | if (v == p) 31 | continue; // we don't want to go back through the same path. 32 | // if we go back is because we found another way back 33 | if (!dis[v]) 34 | { // if V has not been discovered before 35 | children++; 36 | dfsAP(v, u); // recursive DFS call 37 | if (dis[u] <= low[v]) // condition #1 38 | ap[u] = 1; 39 | if (dis[u] < low[v]) // condition #1 40 | br.push_back({u,v}); 41 | low[u] = min(low[u], low[v]); // low[v] might be an ancestor of u 42 | } 43 | else // if v was already discovered means that we found an ancestor 44 | low[u] = min(low[u], dis[v]); // finds the ancestor with the least discovery time 45 | } 46 | return children; 47 | } 48 | 49 | void AP() 50 | { 51 | for (int i = 0; i < V; i++) 52 | { 53 | dis[i] = INT_MAX; 54 | low[i] = INT_MAX; 55 | } 56 | time = 0; 57 | for (int u = 0; u < V; u++) 58 | if (!dis[u]) 59 | ap[u] = dfsAP(u, u) > 1; // condition #2 60 | for (int u = 0; u < V; u++){ 61 | if(ap[u]) cout< 2 | using namespace std; 3 | #define ll long long int 4 | 5 | const int MAXN = 1e3; 6 | class Graph 7 | { 8 | int V; 9 | vector adj[MAXN]; 10 | vector> br; 11 | int dis[MAXN], fin[MAXN], pre[MAXN], vis[MAXN], low[MAXN], ap[MAXN]; 12 | ll time; 13 | 14 | private: 15 | int DFS_visit(int vertex, int parent) 16 | { 17 | int children = 0; 18 | 19 | vis[vertex] = 1; 20 | time = time + 1; 21 | dis[vertex] = time; 22 | 23 | low[vertex] = dis[vertex]; 24 | 25 | for (auto it : adj[vertex]) 26 | { 27 | int child = it; 28 | if (vertex == child) 29 | continue; 30 | if (vis[child] == 0) 31 | { 32 | children++; 33 | DFS_visit(child, vertex); 34 | // Articulation Point Get 35 | if (dis[vertex] <= low[child]) 36 | ap[vertex] = 1; 37 | if (dis[vertex] < low[child]) 38 | br.push_back({vertex, child}); 39 | 40 | // Tree Edge Means Min(lv, lchild) 41 | low[vertex] = 42 | min(low[vertex], low[child]); 43 | } 44 | else 45 | { 46 | // Back Edge Means Min(lv, dischild) 47 | low[vertex] = 48 | min(low[vertex], dis[child]); 49 | } 50 | } 51 | vis[vertex] = 2; 52 | time = time + 1; 53 | fin[vertex] = time; 54 | return children; 55 | } 56 | void Articulation_Point() 57 | { 58 | for (int i = 0; i < V; i++) 59 | { 60 | vis[i] = 0; 61 | dis[i] = INT_MIN; 62 | fin[i] = INT_MIN; 63 | low[i] = INT_MAX; 64 | pre[i] = -1; 65 | } 66 | time = 0; 67 | for (int i = 0; i < V; i++) 68 | { 69 | if (vis[i] == 0) 70 | { 71 | ap[i] = DFS_visit(i, i) > 1; 72 | } 73 | } 74 | for (int i = 0; i < V; i++) 75 | { 76 | if(ap[i]==1) 77 | cout << i <V = V; 89 | }; 90 | void add_new_edge(int v, int w) 91 | { 92 | adj[v].push_back(w); 93 | } 94 | void PrintLows() 95 | { 96 | //cout << "Low Values: " << endl; 97 | Articulation_Point(); 98 | for (int i = 0; i < V; i++) 99 | { 100 | cout << i << " Low : " << low[i]<< endl; 101 | } 102 | // for (auto i : br) 103 | // { 104 | // cout << "bridge: " << i.first << " " << i.second << endl; 105 | // } 106 | } 107 | }; 108 | 109 | int main() 110 | { 111 | freopen("input1.txt", "r", stdin); 112 | freopen("output1.txt", "w", stdout); 113 | int n_nodes, n_edges, u, v; 114 | scanf("%d", &n_nodes); 115 | scanf("%d", &n_edges); 116 | Graph graph1(n_nodes); 117 | while (n_edges--) 118 | { 119 | scanf("%d %d", &u, &v); 120 | graph1.add_new_edge(u, v); 121 | } 122 | graph1.PrintLows(); 123 | } -------------------------------------------------------------------------------- /G5: Bridge Articulation Point/inp.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 1 2 3 | 1 3 4 | 2 1 3 5 | 6 | 7 | -------------------------------------------------------------------------------- /G5: Bridge Articulation Point/input1.txt: -------------------------------------------------------------------------------- 1 | 5 5 2 | 1 0 3 | 2 0 4 | 1 2 5 | 0 3 6 | 3 4 -------------------------------------------------------------------------------- /G5: Bridge Articulation Point/output.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 1 3 | 3 4 | 4 5 | -------------------------------------------------------------------------------- /G5: Bridge Articulation Point/output1.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 1 3 | 2 4 | 4 5 | 6 6 | -------------------------------------------------------------------------------- /G6: Euler Circuit/best euler tour.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5; 6 | 7 | vector gr[N]; 8 | int tin[N], tout[N], tme = 0; 9 | int flat[N]; 10 | 11 | void dfs1(int cur, int par) { 12 | tin[cur] = tme++; 13 | for (auto x : gr[cur]) { 14 | if (x != par) { 15 | // x is child node 16 | dfs1(x, cur); 17 | } 18 | } 19 | tout[cur] = tme++; 20 | } 21 | 22 | void dfs2(int cur, int par) { 23 | cout << cur << " "; 24 | for (auto x : gr[cur]) { 25 | if (x != par) { 26 | // x is child node 27 | dfs2(x, cur); 28 | cout << cur << " "; 29 | } 30 | } 31 | } 32 | 33 | void dfs3(int cur, int par) { 34 | tin[cur] = ++tme; 35 | for (auto x : gr[cur]) { 36 | if (x != par) { 37 | // x is child node 38 | dfs3(x, cur); 39 | } 40 | } 41 | tout[cur] = tme; 42 | } 43 | 44 | int main() 45 | { 46 | freopen("input.txt", "r", stdin); 47 | freopen("output.txt", "w", stdout); 48 | 49 | int n; 50 | cin >> n; 51 | for (int i = 0; i < n - 1; i++) { 52 | int x, y; 53 | cin >> x >> y; 54 | gr[x].push_back(y); 55 | gr[y].push_back(x); 56 | } 57 | 58 | // tme = 1; 59 | // dfs1(1, 0); 60 | 61 | 62 | // dfs2(1, 0); 63 | 64 | tme = 0; 65 | dfs3(1, 0); 66 | 67 | for (int i = 1; i <= n; i++) { 68 | cout << i << " " << tin[i] << " " << tout[i] << '\n'; 69 | } 70 | 71 | for (int i = 1; i <= n; i++) { 72 | flat[tin[i]] = i; 73 | } 74 | 75 | for (int i = 1; i <= n; i++) { 76 | cout << flat[i] << " "; 77 | } 78 | 79 | return 0; 80 | } -------------------------------------------------------------------------------- /G6: Euler Circuit/euler tours.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5; 6 | 7 | vector gr[N]; 8 | 9 | void dfs1(int cur, int par) { 10 | // time in 11 | cout << cur << " "; 12 | for (auto x : gr[cur]) { 13 | if (x != par) { 14 | // x is child node 15 | dfs1(x, cur); 16 | } 17 | } 18 | // time out 19 | cout << cur << " "; 20 | } 21 | 22 | void dfs2(int cur, int par) { 23 | cout << cur << " "; 24 | for (auto x : gr[cur]) { 25 | if (x != par) { 26 | // x is child node 27 | dfs2(x, cur); 28 | cout << cur << " "; 29 | } 30 | } 31 | } 32 | 33 | int main() 34 | { 35 | freopen("input.txt", "r", stdin); 36 | freopen("output.txt", "w", stdout); 37 | 38 | int n; 39 | cin >> n; 40 | for (int i = 0; i < n - 1; i++) { 41 | int x, y; 42 | cin >> x >> y; 43 | gr[x].push_back(y); 44 | gr[y].push_back(x); 45 | } 46 | 47 | // dfs1(1, 0); 48 | 49 | dfs2(1, 0); 50 | 51 | 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /G6: Euler Circuit/inp.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /G7: Strongly Connected Compound/KosarajuAlgorithm.java: -------------------------------------------------------------------------------- 1 | package StronglyConnectedComponent; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.Scanner; 7 | 8 | public class KosarajuAlgorithm { 9 | 10 | 11 | static final int N = (int) (1e5 + 1); 12 | 13 | static ArrayList[] gr = new ArrayList[N], grr = new ArrayList[N], components = new ArrayList[N]; 14 | 15 | static { 16 | for(int i = 0; i < N; i++){ 17 | gr[i] = new ArrayList<>(); 18 | grr[i] = new ArrayList<>(); 19 | components[i] = new ArrayList<>(); 20 | } 21 | } 22 | static boolean[] vis = new boolean[N]; 23 | static int[] col = new int[N]; 24 | static ArrayList order = new ArrayList<>(); 25 | 26 | 27 | // topological sorting 28 | static void dfs1(int cur) { 29 | vis[cur] = true; 30 | for (int x : gr[cur]) { 31 | if (!vis[x]) dfs1(x); 32 | } 33 | order.add(cur); 34 | } 35 | 36 | static void dfs2(int cur, int comp) { 37 | vis[cur] = true; 38 | col[cur] = comp; 39 | components[comp].add(cur); 40 | for (int x : grr[cur]) { 41 | if (!vis[x]) 42 | dfs2(x, comp); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | 48 | Scanner scn = new Scanner(System.in); 49 | int n = scn.nextInt(), m = scn.nextInt(); 50 | 51 | for (int i = 0; i < m; i++) { 52 | int x = scn.nextInt(), y = scn.nextInt(); 53 | gr[x].add(y); 54 | grr[y].add(x); 55 | 56 | } 57 | 58 | for (int i = 1; i <= n; i++) { 59 | if (!vis[i]) 60 | dfs1(i); 61 | } 62 | 63 | Collections.reverse(order); 64 | Arrays.fill(vis, false); 65 | 66 | 67 | int comp = 1; 68 | for (int x : order) { 69 | if (!vis[x]) 70 | dfs2(x, comp++); 71 | } 72 | 73 | for (int i = 1; i <= n; i++) { 74 | System.out.println(i + " " + col[i]); 75 | 76 | } 77 | 78 | System.out.println( "Total strongly components are -> " + (comp - 1) ); 79 | // complexity O(n+m) 80 | 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /G7: Strongly Connected Compound/TopologicalOrder.java: -------------------------------------------------------------------------------- 1 | package StronglyConnectedComponent; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Scanner; 6 | 7 | public class TopologicalOrder { 8 | 9 | static final int N = (int)(1e5 + 1); 10 | 11 | static ArrayList[] gr = new ArrayList[N]; 12 | static ArrayList order; 13 | static { 14 | for(int i = 0 ; i < N ; i++){ 15 | gr[i] = new ArrayList<>(); 16 | } 17 | } 18 | 19 | static boolean[] vis = new boolean[N]; 20 | 21 | static void dfs(int cur, int par) { 22 | vis[cur] = true; 23 | for (int x : gr[cur]) { 24 | if (!vis[x]) { 25 | dfs(x, cur); 26 | } 27 | } 28 | // I am here because I came back from the subtree 29 | order.add(cur); 30 | return; 31 | } 32 | 33 | 34 | public static void main(String[] args) { 35 | 36 | Scanner scn = new Scanner(System.in); 37 | int n = scn.nextInt(), m = scn.nextInt(); 38 | 39 | for (int i = 0; i < m; i++) { 40 | int x = scn.nextInt(), y = scn.nextInt(); 41 | gr[x].add(y); 42 | 43 | } 44 | 45 | 46 | for (int i = 1; i <= n; i++) { 47 | if (!vis[i]) dfs(i, 0); 48 | } 49 | 50 | Collections.reverse(order); 51 | 52 | for (int x : order) 53 | System.out.println(x); 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /G7: Strongly Connected Compound/inp.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbdullahArean/Design-And-Analysis-Of-Algorithm-Data-Structure/b823db9bc7bf953d6e00a82d638b2ba698bf0e4b/G7: Strongly Connected Compound/inp.txt -------------------------------------------------------------------------------- /G7: Strongly Connected Compound/kosaraju algorithm for SCC.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5; 6 | 7 | vector gr[N], grr[N]; 8 | int vis[N], col[N]; 9 | vector order; 10 | 11 | vector components[N]; 12 | 13 | // topological sorting 14 | void dfs1(int cur) { 15 | vis[cur] = 1; 16 | for (auto x : gr[cur]) { 17 | if (!vis[x]) dfs1(x); 18 | } 19 | order.push_back(cur); 20 | } 21 | 22 | void dfs2(int cur, int comp) { 23 | vis[cur] = 1; 24 | col[cur] = comp; 25 | components[comp].push_back(cur); 26 | for (auto x : grr[cur]) { 27 | if (!vis[x]) dfs2(x, comp); 28 | } 29 | } 30 | 31 | int main() 32 | { 33 | freopen("input.txt", "r", stdin); 34 | freopen("output.txt", "w", stdout); 35 | 36 | int n, m; 37 | cin >> n >> m; 38 | 39 | for (int i = 0; i < m; i++) { 40 | int x, y; 41 | cin >> x >> y; 42 | gr[x].push_back(y); 43 | grr[y].push_back(x); 44 | } 45 | 46 | for (int i = 1; i <= n; i++) { 47 | if (!vis[i]) dfs1(i); 48 | } 49 | 50 | reverse(order.begin(), order.end()); 51 | memset(vis, 0, sizeof(vis)); 52 | 53 | int comp = 1; 54 | for (auto x : order) { 55 | // cout << x << " "; 56 | if (!vis[x]) dfs2(x, comp++); 57 | } 58 | 59 | for (int i = 1; i <= n; i++) { 60 | cout << i << " " << col[i] << '\n'; 61 | } 62 | 63 | cout << "Total strongly components are -> " << comp - 1 << '\n'; 64 | 65 | // complexity O(n+m) 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /G7: Strongly Connected Compound/topological Order.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5 + 1; 6 | 7 | vector gr[N]; 8 | vector order; 9 | int vis[N]; 10 | 11 | void dfs(int cur, int par) { 12 | vis[cur] = 1; 13 | for (auto x : gr[cur]) { 14 | if (!vis[x]) { 15 | dfs(x, cur); 16 | } 17 | } 18 | // I am here because I came back from the subtree 19 | order.push_back(cur); 20 | return; 21 | } 22 | 23 | 24 | int main() 25 | { 26 | freopen("input.txt", "r", stdin); 27 | freopen("output.txt", "w", stdout); 28 | 29 | int n, m; 30 | cin >> n >> m; 31 | for (int i = 0; i < m; i++) { 32 | int x, y; 33 | cin >> x >> y; 34 | gr[x].push_back(y); 35 | } 36 | 37 | for (int i = 1; i <= n; i++) { 38 | if (!vis[i]) dfs(i, 0); 39 | } 40 | 41 | reverse(order.begin(), order.end()); 42 | 43 | for (auto x : order) cout << x << " "; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /G8: Minimum Spanning Tree/Kruskal Algo Test Driver Code.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | import sys 3 | import random 4 | import os 5 | 6 | #Generate 7 | for i in range(20): 8 | nvertex = random.randint(100,500) 9 | G = nx.erdos_renyi_graph(nvertex, 0.5, seed=123, directed=False) 10 | for (u,v,w) in G.edges(data=True): 11 | w['weight'] = random.randint(0,10000) 12 | 13 | # Print 14 | file_path = 'inp.txt' 15 | sys.stdout = open(file_path, "w") 16 | 17 | print(nx.number_of_nodes(G), end=" ") 18 | print(nx.number_of_edges(G)) 19 | for line in nx.generate_edgelist(G, data=["weight"]): 20 | print(line) 21 | 22 | #Test With Code 23 | str = 'Kruskal_MST' 24 | #str2= 'Prim_MST' 25 | os.system(f"cd '../Prim-Kruskal-Graph-Implementation/' && g++ {str}.cpp -o {str} && '../Prim-Kruskal-Graph-Implementation/'{str}") 26 | #os.system(f"cd '../Prim-Kruskal-Graph-Implementation/' && g++ {str2}.cpp -o {str2} && '../Prim-Kruskal-Graph-Implementation/'{str2}") 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /G8: Minimum Spanning Tree/Kruskal.java: -------------------------------------------------------------------------------- 1 | package MinimumSpanningTree; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | import java.util.Scanner; 7 | 8 | public class Kruskal { 9 | 10 | static class DSU{ 11 | int[] parent, rank; 12 | 13 | public DSU(int n){ 14 | parent = new int[n]; 15 | rank = new int[n]; 16 | 17 | //parent -1, rank = 1 18 | for(int i=0;i> edgeList; 55 | int V; 56 | 57 | public Graph(int V) { 58 | this.V = V; 59 | edgeList = new ArrayList<>(); 60 | } 61 | 62 | void addEdge(int x,int y,int w){ 63 | ArrayList list = new ArrayList<>(); 64 | list.add(w); 65 | list.add(x); 66 | list.add(y); 67 | edgeList.add(list); 68 | } 69 | 70 | int kruskal_mst(){ 71 | //Main Logic = Easy!!! 72 | //1. Sort all the edges based upon weight 73 | edgeList.sort(new Comparator>() { 74 | @Override 75 | public int compare(ArrayList o1, ArrayList o2) { 76 | return o1.get(0) - o2.get(0); 77 | } 78 | }); 79 | 80 | //Init a DSU 81 | DSU s = new DSU(V); 82 | 83 | int ans = 0; 84 | for(List edge : edgeList){ 85 | 86 | int w = edge.get(0); 87 | int x = edge.get(1); 88 | int y = edge.get(2); 89 | 90 | //take that edge in MST if it doesnt form a cycle 91 | if(s.find(x)!=s.find(y)){ 92 | s.unite(x,y); 93 | ans += w; 94 | } 95 | 96 | } 97 | return ans; 98 | } 99 | 100 | 101 | } 102 | 103 | public static void main(String[] args){ 104 | Scanner scn = new Scanner(System.in); 105 | int n = scn.nextInt(),m = scn.nextInt(); 106 | 107 | 108 | Graph g = new Graph(n); 109 | for(int i=0;i[] l; 19 | int V; 20 | 21 | 22 | public Graph(int n){ 23 | V = n; 24 | l = new ArrayList[n]; 25 | for(int i = 0; i < n; i++){ 26 | l[i] = new ArrayList<>(); 27 | } 28 | } 29 | 30 | void addEdge(int x,int y,int w){ 31 | l[x].add(new Pair(y,w)); 32 | l[y].add(new Pair(x,w)); 33 | } 34 | 35 | int prim_mst(){ 36 | 37 | Queue Q = new PriorityQueue<>(new Comparator() { 38 | @Override 39 | public int compare(Pair o1, Pair o2) { 40 | return o1.first - o2.first; 41 | } 42 | 43 | }); 44 | 45 | // 46 | 47 | //another array 48 | //visited array that denotes whether a node has been included in MST or Not 49 | boolean[] vis = new boolean[V]; 50 | int ans = 0; 51 | 52 | //begin 53 | Q.add(new Pair(0,0)); // weight, node 54 | 55 | while(!Q.isEmpty()){ 56 | //pick out the edge with min weight 57 | Pair best = Q.poll(); 58 | 59 | int to = best.second; 60 | int weight = best.first; 61 | 62 | if(vis[to]){ 63 | //discard the edge, and continue 64 | continue; 65 | } 66 | 67 | //otherwise take the current edge 68 | ans += weight; 69 | vis[to] = true; 70 | 71 | //add the new edges in the queue 72 | for(Pair x:l[to]){ 73 | if(!vis[x.first]){ 74 | Q.add(new Pair(x.second,x.first)); 75 | } 76 | } 77 | } 78 | return ans; 79 | } 80 | 81 | }; 82 | 83 | public static void main(String[] args){ 84 | 85 | Scanner scn = new Scanner(System.in); 86 | int n = scn.nextInt(),m = scn.nextInt(); 87 | 88 | Graph g = new Graph(n); 89 | for(int i=0;i 34 | [Prims Algorithm Result](https://docs.google.com/spreadsheets/d/1o7hJKIJXeZbm71hMhuzeFDwiU1wGHqNCqMy10bQznJA/)
35 | [Kruskal's Algorithm Result](https://docs.google.com/spreadsheets/d/e/2PACX-1vSBgGnrMR5f25MgNgBwxoUJcxA06cJ0cFOT9y0B8amgfgYKW8MNnKi5z6cOrcgmKfIhqCjTamydPXh7/pubchart?oid=33088508&format=interactive)
36 | [Full Result Data Sheet](https://docs.google.com/spreadsheets/d/1o7hJKIJXeZbm71hMhuzeFDwiU1wGHqNCqMy10bQznJA/) 37 | ### Discussion: 38 | Kruskal time complexity worst case is O(E log E),this because we need to sort the edges. Prim time complexity worst case is O(E log V) with priority queue or even better, O(E+V log V) with Heap. We should use Kruskal when the graph is sparse, i.e.small number of edges,like E=O(V),when the edges are already sorted or if we can sort them in linear time. We should use Prim when the graph is dense, i.e number of edges is high , like E=O(V²). 39 | Analzying the runtime of both the algorithm, we can notice heap implementations are way more faster than LinkedList implementation, array implementation is the slowest. We can also notice that, Standard Template Library implementation is not always best in term of time complexity. 40 | -------------------------------------------------------------------------------- /G8: Minimum Spanning Tree/Random_Graph_Generation.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | import sys 3 | import random 4 | import os 5 | 6 | # Generate 7 | nvertex = random.randint(100, 200) 8 | G = nx.erdos_renyi_graph(nvertex, 0.5, seed=123, directed=False) 9 | for (u, v, w) in G.edges(data=True): 10 | w['weight'] = random.randint(0, 10000) 11 | 12 | # Print 13 | file_path = 'input4.txt' 14 | sys.stdout = open(file_path, "w") 15 | 16 | print(nx.number_of_nodes(G), end=" ") 17 | print(nx.number_of_edges(G)) 18 | for line in nx.generate_edgelist(G, data=["weight"]): 19 | print(line) 20 | 21 | # Test With Code 22 | # str = 'Kruskal_MST' 23 | # str2 = 'Prim_MST' 24 | # os.system(f"cd '../Prim-Kruskal-Graph-Implementation/' && g++ {str}.cpp -o {str} && '../Prim-Kruskal-Graph-Implementation/'{str}") 25 | # os.system(f"cd '../Prim-Kruskal-Graph-Implementation/' && g++ {str2}.cpp -o {str2} && '../Prim-Kruskal-Graph-Implementation/'{str2}") 26 | -------------------------------------------------------------------------------- /G9: Shortest Path Algorithm/G9.1: Single Source Shortest Path/743.network-delay-time.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | //Link:https://leetcode.com/problems/network-delay-time/ 4 | class Graph 5 | { 6 | vector> *adjlist; 7 | int nver; 8 | int *dis; 9 | 10 | public: 11 | Graph(int n) 12 | { 13 | this->nver = n; 14 | adjlist =new vector>[n+1]; 15 | } 16 | void addedge(int x, int y, int w) 17 | { 18 | adjlist[x].push_back({y, w}); 19 | } 20 | void dijkastra_STL(int source) 21 | { 22 | dis = new int[nver+1]; 23 | for (int i = 1 ;i<=nver; i++) 24 | { 25 | dis[i] = INT_MAX; 26 | } 27 | dis[source] = 0; 28 | priority_queue, vector>, greater>> pq; 29 | pq.push({0, source}); 30 | while (!pq.empty()) 31 | { 32 | int u = pq.top().second; 33 | pq.pop(); 34 | for (auto x : adjlist[u]) 35 | { 36 | 37 | int v = x.first; 38 | int weight = x.second; 39 | if (dis[v] > dis[u] + weight) 40 | { 41 | dis[v] = dis[u] + weight; 42 | pq.push({dis[v], v}); 43 | } 44 | } 45 | } 46 | } 47 | int solve(int source){ 48 | dijkastra_STL(source); 49 | int ans=INT_MIN; 50 | for (int i = 1; i <= nver; i++){ 51 | ans = max(ans,dis[i]); 52 | } 53 | if(ans==INT_MAX) return -1; 54 | else return ans; 55 | 56 | } 57 | }; 58 | int networkDelayTime(vector> ×, int n, int k) 59 | { 60 | int e = times.size(); 61 | Graph g1 = Graph(n); 62 | for (auto i : times) 63 | { 64 | g1.addedge(i[0], i[1], i[2]); 65 | } 66 | return g1.solve(k); 67 | } 68 | int main() 69 | { 70 | vector> temp ={{1,2,1}}; 71 | cout< 2 | using namespace std; 3 | 4 | struct edge{ 5 | int src,dst,wt; 6 | }; 7 | 8 | 9 | int V,E; 10 | 11 | void bellmanFord(vector& Edges){ 12 | int parent[V]; //Stores Shortest Path Structure 13 | int cost_parent[V]; //Cost of the node to parent edge weight 14 | vector value(V,INT_MAX); //Keeps shortest path values to each vertex from source 15 | 16 | //Assuming start point as Node-0 17 | parent[0] = -1; //Start node has no parent 18 | value[0] = 0; //start node has value=0 to get picked 1st 19 | 20 | //Include (V-1) edges to cover all V-vertices 21 | bool updated; 22 | for(int i=0;iV: "<"<>V>>E; //Enter no of Vertices and Edges 62 | vector Edges(E); 63 | 64 | //Now input all E edges 65 | int src,dst,wt; 66 | for(int i=0;i>src>>dst>>wt; 68 | Edges[i].src = src; 69 | Edges[i].dst = dst; 70 | Edges[i].wt = wt; 71 | } 72 | 73 | bellmanFord(Edges); 74 | return 0; 75 | } 76 | 77 | //TIME COMPLEXITY: O(V.E) -------------------------------------------------------------------------------- /G9: Shortest Path Algorithm/G9.1: Single Source Shortest Path/Floyd_Warshall_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define V 6 //No of vertices 5 | 6 | void floyd_warshall(int graph[V][V]){ 7 | int dist[V][V]; 8 | 9 | //Assign all values of graph to allPairs_SP 10 | for(int i=0;i 4 | using namespace std; 5 | #define MAX 1000 6 | const long long INF = (1LL << 60) - 666; 7 | 8 | struct edge 9 | { 10 | int u, v; 11 | long long w; 12 | edge() {} 13 | edge(int u, int v, long long w) : u(u), v(v), w(w) {} 14 | 15 | void print() 16 | { 17 | cout << "edge " << u << " " << v << " " << w << endl; 18 | } 19 | }; 20 | 21 | bool bellman_ford(int n, int src, vector E, vector &dis) 22 | { 23 | dis[src] = 0; 24 | for (int i = 0; i <= n; i++) 25 | { 26 | int flag = 0; 27 | for (auto e : E) 28 | { 29 | if ((dis[e.u] + e.w) < dis[e.v]) 30 | { 31 | flag = 1; 32 | dis[e.v] = dis[e.u] + e.w; 33 | } 34 | } 35 | if (flag == 0) 36 | return true; 37 | } 38 | return false; 39 | } 40 | 41 | vector dijkstra(int n, int src, vector E, vector potential) 42 | { 43 | set> S; 44 | vector dis(n + 1, INF); 45 | vector temp(n + 1, INF); 46 | vector> adj[n + 1]; 47 | 48 | dis[src] = temp[src] = 0; 49 | S.insert(make_pair(temp[src], src)); 50 | for (auto e : E) 51 | { 52 | adj[e.u].push_back(make_pair(e.v, e.w)); 53 | } 54 | 55 | while (!S.empty()) 56 | { 57 | pair cur = *(S.begin()); 58 | S.erase(cur); 59 | 60 | int u = cur.second; 61 | for (int i = 0; i < adj[u].size(); i++) 62 | { 63 | int v = adj[u][i].first; 64 | long long w = adj[u][i].second; 65 | 66 | if ((temp[u] + w) < temp[v]) 67 | { 68 | S.erase(make_pair(temp[v], v)); 69 | temp[v] = temp[u] + w; 70 | dis[v] = dis[u] + w; 71 | S.insert(make_pair(temp[v], v)); 72 | } 73 | } 74 | } 75 | return dis; 76 | } 77 | 78 | void johnson(int n, long long ar[MAX][MAX], vector E) 79 | { 80 | vector potential(n + 1, INF); 81 | for (int i = 1; i <= n; i++) 82 | E.push_back(edge(0, i, 0)); 83 | 84 | assert(bellman_ford(n, 0, E, potential)); 85 | for (int i = 1; i <= n; i++) 86 | E.pop_back(); 87 | 88 | for (int i = 1; i <= n; i++) 89 | { 90 | vector dis = dijkstra(n, i, E, potential); 91 | for (int j = 1; j <= n; j++) 92 | { 93 | ar[i][j] = dis[j]; 94 | } 95 | } 96 | } 97 | 98 | long long ar[MAX][MAX]; 99 | 100 | int main() 101 | { 102 | vector E; 103 | E.push_back(edge(1, 2, 2)); 104 | E.push_back(edge(2, 3, -15)); 105 | E.push_back(edge(1, 3, -10)); 106 | 107 | int n = 3; 108 | johnson(n, ar, E); 109 | for (int i = 1; i <= n; i++) 110 | { 111 | for (int j = 1; j <= n; j++) 112 | { 113 | printf("%d %d = %lld\n", i, j, ar[i][j]); 114 | } 115 | } 116 | return 0; 117 | } -------------------------------------------------------------------------------- /G9: Shortest Path Algorithm/G9.2: All Pair Shortest Path/output.txt: -------------------------------------------------------------------------------- 1 | Number of Vertices: 4 2 | Number of Edges: 4 3 | Vertex Distance From Source 4 | 0 0 5 | Path(Weigth of Edge): 0 6 | 7 | 1 -1 8 | Path(Weigth of Edge): 1<-(-1)<-0 9 | 10 | 2 -5 11 | Path(Weigth of Edge): 2<-(-4)<-1<-(-1)<-0 12 | 13 | 3 -2 14 | Path(Weigth of Edge): 3<-(3)<-2<-(-4)<-1<-(-1)<-0 15 | 16 | 1 17 | -1 -1 1 2 18 | 3 -1 -1 2 19 | 3 3 -1 -1 20 | -1 0 1 -1 21 | 0 1 2 -------------------------------------------------------------------------------- /Greedy: Huffman Coding/hf1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define EMPTY_STRING "" 5 | struct Node 6 | { 7 | char character;int frequency;Node *left_node, *right_node; 8 | }; 9 | Node* getNode(char character, int frequency, Node* left_node, Node* right_node) 10 | { 11 | Node* nde = new Node(); 12 | nde->character = character;nde->frequency = frequency;nde->left_node = left_node;nde->right_node = right_node; 13 | 14 | return nde; 15 | } 16 | struct compare 17 | { 18 | bool operator()(const Node* l, const Node* r) const 19 | { 20 | return l->frequency > r->frequency; 21 | } 22 | }; 23 | bool isLeaf(Node* root) { 24 | return root->left_node == nullptr && root->right_node == nullptr; 25 | } 26 | void Encoding(Node* root, string str, map &huffmanCode) 27 | { 28 | if (root == nullptr) return; 29 | if (isLeaf(root)) huffmanCode[root->character] = (str != EMPTY_STRING) ? str : "1"; 30 | Encoding(root->left_node, str + "0", huffmanCode);Encoding(root->right_node, str + "1", huffmanCode); 31 | } 32 | void Decoding(Node* root, int &index, string str) 33 | { 34 | if (root == nullptr) { 35 | return; 36 | } 37 | if (isLeaf(root)) 38 | { 39 | cout << root->character; 40 | return; 41 | } 42 | 43 | index++; 44 | 45 | if (str[index] == '0') { 46 | Decoding(root->left_node, index, str); 47 | } 48 | else { 49 | Decoding(root->right_node, index, str); 50 | } 51 | } 52 | void solution() 53 | { 54 | unordered_map frequency; 55 | int n; 56 | cin>>n; 57 | while(n--){ 58 | char c; 59 | int fr; 60 | cin>>c>>fr; 61 | frequency[c]=fr; 62 | } 63 | priority_queue, compare> pq; 64 | for (auto pair: frequency) { 65 | pq.push(getNode(pair.first, pair.second, nullptr, nullptr)); 66 | } 67 | while (pq.size() != 1) 68 | { 69 | 70 | Node* left_node = pq.top(); pq.pop(); 71 | Node* right_node = pq.top(); pq.pop(); 72 | int sum = left_node->frequency + right_node->frequency; 73 | pq.push(getNode('\0', sum, left_node, right_node)); 74 | } 75 | Node* root = pq.top(); 76 | 77 | map huffmanCode; 78 | Encoding(root, EMPTY_STRING, huffmanCode); 79 | for (auto pa: huffmanCode) { 80 | cout << pa.first << " " << pa.second << endl; 81 | } 82 | } 83 | int main() 84 | { 85 | solution(); 86 | return 0; 87 | } -------------------------------------------------------------------------------- /Greedy: Huffman Coding/hf2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | #define EMPTY_STRING "" 8 | struct Nde 9 | { 10 | char character; 11 | int frequency; 12 | Nde *left_child, *right_child; 13 | }; 14 | Nde* getNode(char character, int frequency, Nde* left_child, Nde* right_child) 15 | { 16 | Nde* node = new Nde(); 17 | 18 | node->character = character; 19 | node->frequency = frequency; 20 | node->left_child = left_child; 21 | node->right_child = right_child; 22 | 23 | return node; 24 | } 25 | struct compare 26 | { 27 | bool operator()(const Nde* l, const Nde* r) const 28 | { 29 | return l->frequency > r->frequency; 30 | } 31 | }; 32 | bool LeafNodeorNot(Nde* root) { 33 | return root->left_child == nullptr && root->right_child == nullptr; 34 | } 35 | void Encoding(Nde* root, string string1, unordered_map &huffmanCode) 36 | { 37 | if (root == nullptr) { 38 | return; 39 | } 40 | if (LeafNodeorNot(root)) { 41 | huffmanCode[root->character] = (string1 != EMPTY_STRING) ? string1 : "1"; 42 | } 43 | 44 | Encoding(root->left_child, string1 + "0", huffmanCode); 45 | Encoding(root->right_child, string1 + "1", huffmanCode); 46 | } 47 | void Decoding(Nde* root, int &index, string string1) 48 | { 49 | if (root == nullptr) { 50 | return; 51 | } 52 | if (LeafNodeorNot(root)) 53 | { 54 | cout << root->character; 55 | return; 56 | } 57 | 58 | index++; 59 | 60 | if (string1[index] == '0') { 61 | Decoding(root->left_child, index, string1); 62 | } 63 | else { 64 | Decoding(root->right_child, index, string1); 65 | } 66 | } 67 | void SolutionB(string text) 68 | { 69 | if (text == EMPTY_STRING) { 70 | return; 71 | } 72 | unordered_map frequency; 73 | for (char character: text) { 74 | frequency[character]++; 75 | } 76 | priority_queue, compare> pq; 77 | for (auto pair: frequency) { 78 | pq.push(getNode(pair.first, pair.second, nullptr, nullptr)); 79 | } 80 | while (pq.size() != 1) 81 | { 82 | 83 | Nde* left_child = pq.top(); pq.pop(); 84 | Nde* right_child = pq.top(); pq.pop(); 85 | int sum = left_child->frequency + right_child->frequency; 86 | pq.push(getNode('\0', sum, left_child, right_child)); 87 | } 88 | Nde* root = pq.top(); 89 | unordered_map huffmanCode; 90 | Encoding(root, EMPTY_STRING, huffmanCode); 91 | string string1; 92 | for (char character: text) { 93 | string1 += huffmanCode[character]; 94 | } 95 | cout << string1.length() << endl; 96 | } 97 | int main() 98 | { 99 | char c, inp[1000009]; 100 | string text = ""; 101 | int n; cin>>n;getchar(); 102 | for(int i=0; i 2 | 3 | using namespace std; 4 | 5 | struct Dinic { 6 | // from x to y with residual capacity 7 | struct edge { 8 | int x, y, w; 9 | }; 10 | 11 | vector> gr; 12 | vector edges; 13 | vector level; 14 | vector edge_sz; 15 | 16 | int n, source, sink, ec = 0; 17 | Dinic(int n, int source, int sink) { 18 | this->n = n; 19 | this->source = source; 20 | this->sink = sink; 21 | gr.resize(n); 22 | edge_sz.resize(n); 23 | } 24 | 25 | void add_edge(int x, int y, int w) { 26 | edges.push_back({x, y, w}); 27 | gr[x].push_back(ec++); 28 | edges.push_back({y, x, 0}); 29 | gr[y].push_back(ec++); 30 | } 31 | 32 | bool level_graph() { 33 | level.clear(); level.resize(n, -1); 34 | 35 | queue Q; 36 | Q.push(source); 37 | level[source] = -1; 38 | 39 | while (!Q.empty()) { 40 | int cur = Q.front(); 41 | Q.pop(); 42 | 43 | for (auto xx : gr[cur]) { 44 | int to = edges[xx].y; 45 | int w = edges[xx].w; 46 | 47 | if (w && level[to] == -1) { 48 | level[to] = level[cur] + 1; 49 | Q.push(to); 50 | } 51 | 52 | } 53 | } 54 | 55 | return level[sink] != -1; 56 | } 57 | 58 | int augment(int cur, int flow) { 59 | if (cur == sink) return flow; 60 | 61 | for (int &i = edge_sz[cur]; i >= 0; i--) { 62 | int edge_index = gr[cur][i]; 63 | int w = edges[edge_index].w; 64 | int y = edges[edge_index].y; 65 | 66 | if (w && level[y] == level[cur] + 1) { 67 | int bottleneck_flow = augment(y, min(w, flow)); 68 | 69 | if (bottleneck_flow) { 70 | // forward edge according to current augmented path 71 | edges[edge_index].w -= bottleneck_flow; 72 | // backward edge 73 | edges[edge_index ^ 1].w += bottleneck_flow; 74 | 75 | return bottleneck_flow; 76 | } 77 | 78 | } 79 | } 80 | return 0; 81 | } 82 | 83 | int max_flow() { 84 | int total_flow = 0; 85 | 86 | while (level_graph()) { 87 | // find augmenting paths and update in residual network 88 | for (int i = 0; i < n; i++) edge_sz[i] = gr[i].size() - 1; 89 | while (int flow = augment(0, 1e9)) { 90 | total_flow += flow; 91 | } 92 | } 93 | 94 | return total_flow; 95 | } 96 | 97 | }; 98 | 99 | int main() 100 | { 101 | freopen("input.txt", "r", stdin); 102 | freopen("output.txt", "w", stdout); 103 | 104 | Dinic G(4, 0, 3); 105 | 106 | G.add_edge(0, 1, 5); 107 | G.add_edge(1, 2, 10); 108 | G.add_edge(2, 3, 3); 109 | 110 | cout << G.max_flow(); 111 | 112 | return 0; 113 | } -------------------------------------------------------------------------------- /NF0: Network Flow Basic/dinicsAlgo.java: -------------------------------------------------------------------------------- 1 | package NetworkFlow; 2 | 3 | import java.lang.reflect.Array; 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.LinkedList; 7 | import java.util.Queue; 8 | 9 | public class dinicsAlgo { 10 | 11 | 12 | static class Dinic { 13 | // from x to y with residual capacity 14 | class edge { 15 | int x, y, w; 16 | 17 | edge(int a, int b, int c){ 18 | x = a; 19 | y = b; 20 | w = c; 21 | } 22 | }; 23 | 24 | ArrayList> gr = new ArrayList<>(); 25 | ArrayList edges = new ArrayList<>(); 26 | int[] level; 27 | int[] edge_sz; 28 | 29 | int n, source, sink, ec = 0; 30 | Dinic(int n, int source, int sink) { 31 | this.n = n; 32 | this.source = source; 33 | this.sink = sink; 34 | 35 | for(int i = 0; i < n; i++){ 36 | gr.add(new ArrayList<>()); 37 | 38 | } 39 | edge_sz = new int[n]; 40 | } 41 | 42 | void add_edge(int x, int y, int w) { 43 | edges.add(new edge(x, y, w)); 44 | gr.get(x).add(ec++); 45 | edges.add(new edge(y, x, 0)); 46 | gr.get(y).add(ec++); 47 | } 48 | 49 | boolean level_graph() { 50 | level = new int[n]; 51 | Arrays.fill(level, -1); 52 | 53 | Queue Q = new LinkedList<>(); 54 | Q.add(source); 55 | level[source] = -1; 56 | 57 | while (!Q.isEmpty()) { 58 | int cur = Q.poll(); 59 | 60 | 61 | for (int xx : gr.get(cur)) { 62 | int to = edges.get(xx).y; 63 | int w = edges.get(xx).w; 64 | 65 | if (w != 0 && level[to] == -1) { 66 | level[to] = level[cur] + 1; 67 | Q.add(to); 68 | } 69 | 70 | } 71 | } 72 | 73 | return level[sink] != -1; 74 | } 75 | 76 | int augment(int cur, int flow) { 77 | if (cur == sink) return flow; 78 | 79 | for (int i = edge_sz[cur]; i >= 0; i--) { 80 | int edge_index = gr.get(cur).get(i); 81 | int w = edges.get(edge_index).w; 82 | int y = edges.get(edge_index).y; 83 | 84 | if (w != 0 && level[y] == level[cur] + 1) { 85 | int bottleneck_flow = augment(y, Math.min(w, flow)); 86 | 87 | if (bottleneck_flow != 0) { 88 | // forward edge according to current augmented path 89 | edges.get(edge_index).w -= bottleneck_flow; 90 | // backward edge 91 | edges.get(edge_index ^ 1).w += bottleneck_flow; 92 | 93 | return bottleneck_flow; 94 | } 95 | 96 | } 97 | } 98 | return 0; 99 | } 100 | 101 | int max_flow() { 102 | int total_flow = 0; 103 | 104 | while (level_graph()) { 105 | // find augmenting paths and update in residual network 106 | for (int i = 0; i < n; i++) edge_sz[i] = gr.get(i).size() - 1; 107 | int flow = augment(0, (int) 1e9) ; 108 | while ( flow != 0) { 109 | total_flow += flow; 110 | flow = augment(0, (int) 1e9); 111 | } 112 | } 113 | 114 | return total_flow; 115 | } 116 | 117 | }; 118 | 119 | public static void main(String[] args) { 120 | 121 | 122 | Dinic G = new Dinic(4, 0, 3); 123 | 124 | G.add_edge(0, 1, 5); 125 | G.add_edge(1, 2, 10); 126 | G.add_edge(2, 3, 3); 127 | 128 | System.out.println(G.max_flow()); 129 | 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /NF0: Network Flow Basic/driver.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | //freopen("inp.txt", "r", stdin); 7 | freopen("in.txt", "w", stdout); 8 | srand(time(0)); 9 | 10 | int n = rand() % 100 + 1; 11 | int m = rand() % 500 + 1; 12 | 13 | cout << n << ' ' << m << '\n'; 14 | for (int i = 0; i < m; ++i) { 15 | int u = rand() % n + 1; 16 | int v = rand() % n + 1; 17 | while (u == v) v = rand() % n + 1; 18 | cout << u << ' ' << v << ' '; 19 | cout << rand() % 500 << '\n'; 20 | } 21 | } -------------------------------------------------------------------------------- /NF0: Network Flow Basic/driver2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | //freopen("inp.txt", "r", stdin); 7 | freopen("in.txt", "w", stdout); 8 | srand(time(0)); 9 | 10 | int n = rand() % 100 + 1; 11 | int n2 = rand() % 50 + 1; 12 | int n1 = n-n2 -2; 13 | int m = rand() % 500 + 1; 14 | 15 | cout << n << ' ' < 2 | 3 | using namespace std; 4 | // int max_flow = 0; 5 | int bfs(int source, int sink, int n, vector &parent, vector> &graph) 6 | { 7 | parent.assign(n, -1); 8 | parent[source] = -2; 9 | queue> q; 10 | q.push({source, INT_MAX}); 11 | 12 | while (!q.empty()) 13 | { 14 | int u = q.front().first; 15 | int cap = q.front().second; 16 | q.pop(); 17 | 18 | for (int v = 0; v < n; v++) 19 | { 20 | if (u != v && graph[u][v] != 0 && parent[v] == -1) 21 | { 22 | parent[v] = u; 23 | int min_cap = min(cap, graph[u][v]); 24 | if (v == sink) 25 | return min_cap; 26 | q.push({v, min_cap}); 27 | } 28 | } 29 | } 30 | return 0; 31 | } 32 | 33 | // void dfs_visit(int min_cap, int u, int source, int sink, int n, vector &parent, vector &visited, vector> &graph) 34 | // { 35 | // visited[u] = 1; 36 | // for (int v = 0; v < n; v++) 37 | // { 38 | // if (u != v && graph[u][v] != 0 && parent[v] == -1) 39 | // { 40 | // parent[v] = u; 41 | // min_cap = min(min_cap, graph[u][v]); 42 | // if (v == sink) 43 | // { 44 | // max_flow += min_cap; 45 | // int v = sink; 46 | 47 | // while (v != source) 48 | // { 49 | // visited[v]=0; 50 | // int u = parent[v]; 51 | // graph[u][v] -= min_cap; // forward edge 52 | // graph[v][u] += min_cap; // back edge 53 | // v = u; 54 | // } 55 | // } 56 | // else 57 | // dfs_visit(min_cap,v, source, sink, n, parent, visited, graph); 58 | // } 59 | // } 60 | // } 61 | // void dfs(int source, int sink, int n, vector> &graph) 62 | // { 63 | // vector parent(n, -1); 64 | // parent[source] = -2; 65 | // int min_cap = 0; 66 | // vector visited(n, 0); 67 | // for (int i = 0; i < n; i++) 68 | // { 69 | // if (visited[i] == 0) 70 | // { 71 | // dfs_visit(min_cap, i, source, sink, n, parent, visited, graph); 72 | // } 73 | // } 74 | // } 75 | int Ford_Fulkerson(int source, int sink, int n, vector> &graph) 76 | { 77 | vector parent(n, -1); 78 | int max_flow = 0; 79 | int min_cap = 0; 80 | while (min_cap = bfs(source, sink, n, parent, graph)) 81 | { 82 | max_flow += min_cap; 83 | int v = sink; 84 | 85 | while (v != source) 86 | { 87 | int u = parent[v]; 88 | graph[u][v] -= min_cap; // forward edge 89 | graph[v][u] += min_cap; // back edge 90 | v = u; 91 | } 92 | } 93 | return max_flow; 94 | } 95 | int main() 96 | { 97 | freopen("inp.txt", "r", stdin); 98 | //freopen("output.txt", "w", stdout); 99 | int V, e, a, b, c; 100 | cin >> V >> e; 101 | vector> graph(V, vector(V, 0)); 102 | for (int i = 0; i < e; i++) 103 | { 104 | cin >> a >> b >> c; 105 | graph[a][b] = c; 106 | } 107 | cout << "Maximum Flow Using Ford Fulkerson Algo: " << Ford_Fulkerson(0, 5, V, graph) << endl; 108 | // dfs(0, 5, V, graph); 109 | // cout< 3 | 4 | using namespace std; 5 | 6 | int bfs(int source,int target,int n,vector& parent,vector>& graph){ 7 | //Update the parent vector as each node value to be -1 8 | fill(parent.begin(),parent.end(),-1); 9 | //parent of source node to be -2 10 | parent[source] = -2; 11 | //Initializing queue for storing and min capacity so far 12 | queue> q; 13 | //Source node min capacity to be 1e9 14 | q.push({source,1e9}); 15 | 16 | //Looping while queue is not empty 17 | while(!q.empty()){ 18 | //storing top node and min capacity so far 19 | int u = q.front().first; 20 | int cap = q.front().second; 21 | //Removing top node from queue 22 | q.pop(); 23 | //Looping all edges from u 24 | for(int v=0;v>& graph){ 46 | //Initializing parent vector for finding the path from source to target 47 | //In which we add parent of the node 48 | vector parent(n,-1); 49 | //Initializing maximum flow for storing ans 50 | int max_flow = 0; 51 | int min_cap = 0; //storing minimum capacity in each path 52 | 53 | //looping while minimum capacity become zero 54 | //For finding path and minimum capacity we call function bfs() 55 | while(min_cap = bfs(source,target,n,parent,graph)){ 56 | //Adding the min_cap from this path 57 | max_flow += min_cap; 58 | //storing target node in v 59 | int v = target; 60 | 61 | //while we didn't find the source node 62 | //Looping through path stored in parent 63 | while(v!=source){ 64 | //finding parent of v node 65 | int u = parent[v]; 66 | //Subtracting minimum capacity from u to v 67 | //And adding minimum capacity from v to u 68 | graph[u][v] -= min_cap; 69 | graph[v][u] += min_cap; 70 | //Update the v node to it's parent 71 | v=u; 72 | } 73 | } 74 | //Returning maximum flow in the graph 75 | return max_flow; 76 | } 77 | 78 | void addEdge(vector>& graph, 79 | int u, int v, int w) 80 | { 81 | graph[u][v] = w; 82 | } 83 | 84 | int main() 85 | { 86 | //Intializing the graph in 2d vector 87 | int V = 6; 88 | vector> graph(V, vector (V, 0)); 89 | //Adding edges weight in the graph 90 | addEdge(graph, 0, 1, 4); 91 | addEdge(graph, 0, 3, 3); 92 | addEdge(graph, 1, 2, 4); 93 | addEdge(graph, 2, 3, 3); 94 | addEdge(graph, 2, 5, 2); 95 | addEdge(graph, 3, 4, 6); 96 | addEdge(graph, 4, 5, 6); 97 | 98 | //Printing the maximum flow from the given network Using Ford Fulkerson Method 99 | cout << "Maximum Flow Using Ford Fulkerson Algo: " << Ford_Fulkerson(0,5,V,graph) << endl; 100 | return 0; 101 | } -------------------------------------------------------------------------------- /NF0: Network Flow Basic/inp.txt: -------------------------------------------------------------------------------- 1 | 6 7 2 | 0 1 4 3 | 0 3 3 4 | 1 2 4 5 | 2 3 3 6 | 2 5 2 7 | 3 4 6 8 | 4 5 6 -------------------------------------------------------------------------------- /NF0: Network Flow Basic/showsir.sh: -------------------------------------------------------------------------------- 1 | g++ edmondkarp_fordfulkerson.cpp -o edf 2 | g++ driver.cpp -o geninput 3 | ./geninput && ./edf -------------------------------------------------------------------------------- /NF0: Network Flow Basic/showsir2.sh: -------------------------------------------------------------------------------- 1 | g++ mbm_maxflow.cpp -o mbm 2 | g++ driver2.cpp -o geninput2 3 | ./geninput2 && ./mbm -------------------------------------------------------------------------------- /NF0: Network Flow Basic/sirinput.txt: -------------------------------------------------------------------------------- 1 | 12 4 6 11 2 | 1 5 1 3 | 1 6 1 4 | 1 7 1 5 | 1 8 1 6 | 1 9 1 7 | 1 10 1 8 | 2 6 1 9 | 2 10 1 10 | 3 5 1 11 | 4 6 1 12 | 4 10 1 -------------------------------------------------------------------------------- /NT1: Eucleadian Algorithm GCD/Linear_Diophantine_Equations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Linear Diaphantine Equations: 3 | ============================ 4 | Diophantine Equation: Polynomial equation in two or more unknowns, such that only integral solution 5 | are required. 6 | Problem Statement: 7 | Given three integers of the form ax+by = c. Determine the equation has a solution such that x 8 | and y are both integral solutions 9 | 10 | ax+by =c; 11 | */ 12 | #include 13 | using namespace std; 14 | // a x + b y = gcd(a,b); returns (x), (y) and (gcd of a,b) 15 | vector extended_gcd(int a, int b) 16 | { 17 | if (b == 0) 18 | { 19 | return {1, 0, a}; 20 | } 21 | vector result = extended_gcd(b, a % b); 22 | 23 | // after recursive call is over 24 | int smallx = result[0]; 25 | int smally = result[1]; 26 | int gcd = result[2]; 27 | 28 | int x = smally; 29 | int y = smallx - (a / b) * smally; 30 | 31 | return {x, y, gcd}; 32 | } 33 | vector linear_D_eq(int a, int b, int c) 34 | { 35 | vector result1 = extended_gcd(a, b); 36 | if (c % result1[2] == 0) 37 | { 38 | cout << "Solution Exists" << endl; 39 | int k = c / result1[2]; 40 | int x = result1[0]; 41 | int y = result1[1]; 42 | int g = result1[2]; 43 | // cout << x << " and " << y << " gcd: " << g << endl; 44 | for (int i = 1; i < 10; i++) 45 | { 46 | x = x + (b / g) * i; 47 | y = y - (a / g) * i; 48 | cout << x << " and " << y << endl; 49 | } 50 | return {k * result1[0], k * result1[1], result1[2]}; 51 | } 52 | else 53 | { 54 | cout << "Solution Doesn't Exists" << endl; 55 | return {-1, -1, -1}; 56 | } 57 | } 58 | int gcd(int a, int b, int &x, int &y) 59 | { 60 | if (b == 0) 61 | { 62 | x = 1; 63 | y = 0; 64 | return a; 65 | } 66 | int x1, y1; 67 | int d = gcd(b, a % b, x1, y1); 68 | x = y1; 69 | y = x1 - y1 * (a / b); 70 | return d; 71 | } 72 | 73 | bool find_any_solution(int a, int b, int c, int &x0, int &y0, int &g) 74 | { 75 | g = gcd(abs(a), abs(b), x0, y0); 76 | if (c % g) 77 | { 78 | return false; 79 | } 80 | 81 | x0 *= c / g; 82 | y0 *= c / g; 83 | if (a < 0) 84 | x0 = -x0; 85 | if (b < 0) 86 | y0 = -y0; 87 | return true; 88 | } 89 | int main() 90 | { 91 | int a = 25, b = 15, c = 400; 92 | vector ans = linear_D_eq(a, b, c); 93 | 94 | return 0; 95 | } -------------------------------------------------------------------------------- /NT1: Eucleadian Algorithm GCD/Linear_diaphantine_eqn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbdullahArean/Design-And-Analysis-Of-Algorithm-Data-Structure/b823db9bc7bf953d6e00a82d638b2ba698bf0e4b/NT1: Eucleadian Algorithm GCD/Linear_diaphantine_eqn.png -------------------------------------------------------------------------------- /NT1: Eucleadian Algorithm GCD/Multiplicative_Modulo_Inverse_using_extended_Eucledian.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbdullahArean/Design-And-Analysis-Of-Algorithm-Data-Structure/b823db9bc7bf953d6e00a82d638b2ba698bf0e4b/NT1: Eucleadian Algorithm GCD/Multiplicative_Modulo_Inverse_using_extended_Eucledian.png -------------------------------------------------------------------------------- /NT1: Eucleadian Algorithm GCD/gcd_extended.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int gcd(int a,int b){ 5 | if(b==0){ 6 | return a; 7 | } 8 | return gcd(b,a%b); 9 | 10 | } 11 | //a x + b y = gcd(a,b); returns (x), (y) and (gcd of a,b) 12 | vector extended_gcd(int a, int b){ 13 | if(b==0){ 14 | return {1,0,a}; 15 | } 16 | vectorresult = extended_gcd(b, a%b); 17 | 18 | //after recursive call is over 19 | int smallx = result[0]; 20 | int smally = result[1]; 21 | int gcd = result[2]; 22 | 23 | int x = smally; 24 | int y = smallx - (a/b)*smally; 25 | 26 | return {x,y,gcd}; 27 | } 28 | int main(){ 29 | int a=18, b=30; 30 | //cin>>a>>b; 31 | vector result = extended_gcd(a,b); 32 | cout< 11 | using namespace std; 12 | vector extended_gcd(int a, int b) 13 | { 14 | if (b == 0) 15 | { 16 | return {1, 0, a}; 17 | } 18 | vector result = extended_gcd(b, a % b); 19 | 20 | // after recursive call is over 21 | int smallx = result[0]; 22 | int smally = result[1]; 23 | int gcd = result[2]; 24 | 25 | int x = smally; 26 | int y = smallx - (a / b) * smally; 27 | 28 | return {x, y, gcd}; 29 | } 30 | int modInverse(int a, int m) 31 | { 32 | vector result = extended_gcd(a, m); 33 | int x = result[0]; 34 | int gcd = result[2]; 35 | 36 | if (gcd != 1) 37 | { 38 | cout << "Multiplicative Modulo Inverse doesn't exists"; 39 | return -1; 40 | } 41 | int ans = (x % m + m) % m; // x can be negative also; 42 | return ans; 43 | } 44 | 45 | int main() 46 | { 47 | cout << modInverse(6, 7) << endl; 48 | return 0; 49 | } -------------------------------------------------------------------------------- /Single-Source-Shortest-Path/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void bfs(int s, vector arr[], bool *vis){ 6 | 7 | queue q; 8 | q.push(s); 9 | vis[s] = true; 10 | 11 | 12 | while(!q.empty()){ 13 | 14 | int u = q.front(); q.pop(); 15 | cout<>v>>e; 35 | 36 | vector arr[v]; 37 | bool vis[v]; 38 | 39 | memset(vis,false,sizeof(vis)); 40 | 41 | for(int i=0;i>u>>v; 44 | arr[u].push_back(v); 45 | arr[v].push_back(u); 46 | } 47 | 48 | bfs(0,arr,vis); 49 | cout< 2 | using namespace std; 3 | 4 | struct edge{ 5 | int src,dst,wt; 6 | }; 7 | 8 | 9 | int V,E; 10 | 11 | void bellmanFord(vector& Edges){ 12 | int parent[V]; //Stores Shortest Path Structure 13 | int cost_parent[V]; //Cost of the node to parent edge weight 14 | vector value(V,INT_MAX); //Keeps shortest path values to each vertex from source 15 | 16 | //Assuming start point as Node-0 17 | parent[0] = -1; //Start node has no parent 18 | value[0] = 0; //start node has value=0 to get picked 1st 19 | 20 | //Include (V-1) edges to cover all V-vertices 21 | bool updated; 22 | for(int i=0;iV: "<"<>V>>E; //Enter no of Vertices and Edges 62 | vector Edges(E); 63 | 64 | //Now input all E edges 65 | int src,dst,wt; 66 | for(int i=0;i>src>>dst>>wt; 68 | Edges[i].src = src; 69 | Edges[i].dst = dst; 70 | Edges[i].wt = wt; 71 | } 72 | 73 | bellmanFord(Edges); 74 | return 0; 75 | } 76 | 77 | //TIME COMPLEXITY: O(V.E) -------------------------------------------------------------------------------- /Single-Source-Shortest-Path/DFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void dfs(int s, vector arr[], bool *vis){ 6 | vis[s] = true; 7 | cout<>v>>e; 21 | 22 | vector arr[v]; 23 | bool vis[v]; 24 | 25 | memset(vis,false,sizeof(vis)); 26 | 27 | for(int i=0;i>u>>v; 30 | arr[u].push_back(v); 31 | arr[v].push_back(u); 32 | } 33 | 34 | dfs(0,arr,vis); 35 | cout< 3 | using namespace std; 4 | 5 | // Class for an undirected graph 6 | class Graph 7 | { 8 | 9 | // No. of vertices 10 | int V; 11 | 12 | // Pointer to an array 13 | // containing adjacency lists 14 | list *adj; 15 | 16 | // A recursive function that 17 | // uses visited[] and parent to detect 18 | // cycle in subgraph reachable 19 | // from vertex v. 20 | bool isCyclicUtil(int v, bool visited[], int parent) 21 | { 22 | 23 | // Mark the current node as visited 24 | visited[v] = true; 25 | 26 | // Recur for all the vertices 27 | // adjacent to this vertex 28 | list::iterator i; 29 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 30 | { 31 | 32 | // If an adjacent vertex is not visited, 33 | // then recur for that adjacent 34 | if (!visited[*i]) 35 | { 36 | if (isCyclicUtil(*i, visited, v)) 37 | return true; 38 | } 39 | 40 | // If an adjacent vertex is visited and 41 | // is not parent of current vertex, 42 | // then there exists a cycle in the graph. 43 | else if (*i != parent) 44 | return true; 45 | } 46 | return false; 47 | } 48 | 49 | public: 50 | // Constructor 51 | Graph(int V) 52 | { 53 | this->V = V; 54 | adj = new list[V]; 55 | } 56 | 57 | // To add an edge to graph 58 | void addEdge(int v, int w) 59 | { 60 | adj[v].push_back(w); 61 | adj[w].push_back(v); 62 | } 63 | 64 | // Returns true if the graph contains 65 | // a cycle, else false. 66 | bool isCyclic() 67 | { 68 | 69 | // Mark all the vertices as not 70 | // visited and not part of recursion 71 | // stack 72 | bool *visited = new bool[V]; 73 | for (int i = 0; i < V; i++) 74 | visited[i] = false; 75 | 76 | // Call the recursive helper 77 | // function to detect cycle in different 78 | // DFS trees 79 | for (int u = 0; u < V; u++) 80 | { 81 | 82 | // Don't recur for u if 83 | // it is already visited 84 | if (!visited[u]) 85 | if (isCyclicUtil(u, visited, -1)) 86 | return true; 87 | } 88 | return false; 89 | } 90 | }; 91 | 92 | // Driver program to test above functions 93 | int main(){ 94 | 95 | freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); 96 | int v,e; 97 | cin>>v>>e; 98 | 99 | Graph g(v); 100 | 101 | for(int i=0;i>u>>v; 103 | g.addEdge(u,v); 104 | } 105 | g.isCyclic() ? cout << "Graph contains cycle\n" 106 | : cout << "Graph doesn't contain cycle\n"; 107 | 108 | Graph g1(5); 109 | g1.addEdge(1, 0); 110 | g1.addEdge(0, 2); 111 | g1.addEdge(2, 1); 112 | g1.addEdge(0, 3); 113 | g1.addEdge(3, 4); 114 | g1.isCyclic() ? cout << "Graph contains cycle\n" 115 | : cout << "Graph doesn't contain cycle\n"; 116 | 117 | Graph g2(3); 118 | g2.addEdge(0, 1); 119 | g2.addEdge(1, 2); 120 | g2.isCyclic() ? cout << "Graph contains cycle\n" 121 | : cout << "Graph doesn't contain cycle\n"; 122 | 123 | return 0; 124 | } 125 | -------------------------------------------------------------------------------- /Single-Source-Shortest-Path/DetectingCycleDirectedGraph.cpp: -------------------------------------------------------------------------------- 1 | // A C++ Program to detect cycle in a graph 2 | #include 3 | using namespace std; 4 | 5 | class Graph 6 | { 7 | int V; // No. of vertices 8 | list *adj; // Pointer to an array containing adjacency lists 9 | bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic() 10 | public: 11 | Graph(int V); // Constructor 12 | void addEdge(int v, int w); // to add an edge to graph 13 | bool isCyclic(); // returns true if there is a cycle in this graph 14 | }; 15 | 16 | Graph::Graph(int V) 17 | { 18 | this->V = V; 19 | adj = new list[V]; 20 | } 21 | 22 | void Graph::addEdge(int v, int w) 23 | { 24 | adj[v].push_back(w); // Add w to v’s list. 25 | } 26 | 27 | 28 | bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack) 29 | { 30 | if(visited[v] == false) 31 | { 32 | // Mark the current node as visited and part of recursion stack 33 | visited[v] = true; 34 | recStack[v] = true; 35 | 36 | // Recur for all the vertices adjacent to this vertex 37 | list::iterator i; 38 | for(i = adj[v].begin(); i != adj[v].end(); ++i) 39 | { 40 | if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) ) 41 | return true; 42 | else if (recStack[*i]) 43 | return true; 44 | } 45 | 46 | } 47 | recStack[v] = false; // remove the vertex from recursion stack 48 | return false; 49 | } 50 | 51 | // Returns true if the graph contains a cycle, else false. 52 | // This function is a variation of DFS() in 53 | bool Graph::isCyclic() 54 | { 55 | // Mark all the vertices as not visited and not part of recursion 56 | // stack 57 | bool *visited = new bool[V]; 58 | bool *recStack = new bool[V]; 59 | for(int i = 0; i < V; i++) 60 | { 61 | visited[i] = false; 62 | recStack[i] = false; 63 | } 64 | 65 | // Call the recursive helper function to detect cycle in different 66 | // DFS trees 67 | for(int i = 0; i < V; i++) 68 | if ( !visited[i] && isCyclicUtil(i, visited, recStack)) 69 | return true; 70 | 71 | return false; 72 | } 73 | 74 | int main(){ 75 | 76 | freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); 77 | int v,e; 78 | cin>>v>>e; 79 | 80 | Graph g1(v); 81 | 82 | for(int i=0;i>u>>v; 84 | g1.addEdge(u,v); 85 | } 86 | g1.isCyclic() ? cout << "Graph contains cycle\n" 87 | : cout << "Graph doesn't contain cycle\n"; 88 | 89 | Graph g(4); 90 | g.addEdge(0, 1); 91 | g.addEdge(0, 2); 92 | g.addEdge(1, 2); 93 | g.addEdge(2, 0); 94 | g.addEdge(2, 3); 95 | g.addEdge(3, 3); 96 | 97 | if(g.isCyclic()) 98 | cout << "Graph contains cycle"; 99 | else 100 | cout << "Graph doesn't contain cycle"; 101 | return 0; 102 | } 103 | -------------------------------------------------------------------------------- /Single-Source-Shortest-Path/Floyd_Warshall_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define V 6 //No of vertices 5 | 6 | void floyd_warshall(int graph[V][V]){ 7 | int dist[V][V]; 8 | 9 | //Assign all values of graph to allPairs_SP 10 | for(int i=0;i 8 | using namespace std; 9 | const int MAXN = 1e5; 10 | #define vi vector 11 | #define pii pair 12 | #define vii vector 13 | #define rep(i,a,b) for(int i=a; i a 17 | #define pqmini(a) priority_queue> a 18 | long long int merge(int arr[], int start, int mid, int end) 19 | { 20 | long long int inv=0; 21 | int len1 = mid - start + 1; 22 | int len2 = end - mid; 23 | 24 | int leftArr[len1], rightArr[len2]; 25 | 26 | for (int i = 0; i < len1; i++) 27 | leftArr[i] = arr[start + i]; 28 | for (int j = 0; j < len2; j++) 29 | rightArr[j] = arr[mid + 1 + j]; 30 | 31 | int i, j, k; 32 | i = 0; 33 | j = 0; 34 | k = start; 35 | 36 | while (i < len1 && j < len2) 37 | { 38 | if (leftArr[i] <= rightArr[j]) 39 | { 40 | arr[k] = leftArr[i]; 41 | i++; 42 | } 43 | else 44 | { 45 | arr[k] = rightArr[j]; 46 | inv+=len1-i; 47 | j++; 48 | } 49 | k++; 50 | } 51 | 52 | while (i < len1) 53 | { 54 | arr[k] = leftArr[i]; 55 | i++; 56 | k++; 57 | } 58 | 59 | while (j < len2) 60 | { 61 | arr[k] = rightArr[j]; 62 | j++; 63 | k++; 64 | } 65 | return inv; 66 | } 67 | long long int mergeSort(int arr[], int start, int end) 68 | { 69 | long long int inv =0; 70 | if (start < end) 71 | { 72 | 73 | int mid = start + (end - start) / 2; 74 | inv+=mergeSort(arr, start, mid); 75 | inv+=mergeSort(arr, mid + 1, end); 76 | inv+=merge(arr, start, mid, end); 77 | } 78 | return inv; 79 | } 80 | 81 | bool Solution(){ 82 | int n; 83 | cin>>n; 84 | int arr[100]; 85 | long long int localinv=0; 86 | for(int i=0 ; i0 && arr[i-1]>arr[i]) localinv++; 89 | } 90 | if(localinv==mergeSort(arr,0,n-1))return true; 91 | else return false; 92 | 93 | 94 | } 95 | int main(){ 96 | ios_base::sync_with_stdio(false); 97 | cin.tie(NULL); 98 | freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); 99 | Solution(); 100 | return 0; 101 | } -------------------------------------------------------------------------------- /T1: Segment Tree/FLIPCOIN-codechef.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | #include 3 | #include 4 | using namespace std; 5 | //Link: https://www.codechef.com/problems/FLIPCOIN 6 | // summation 7 | struct segmenttree { 8 | int n; 9 | vector st, lazy; 10 | 11 | void init(int _n) { 12 | this->n = _n; 13 | st.resize(4 * n, 0); 14 | lazy.resize(4 * n, 0); 15 | } 16 | int query(int start, int ending, int l, int r, int node) { 17 | 18 | // lazy propagation / clear the lazy update 19 | if (lazy[node] ) { 20 | // pending updates 21 | // update the segment tree node 22 | st[node]=(ending - start + 1)-st[node]; 23 | if (start != ending) { 24 | // propagate the updated value 25 | lazy[2 * node + 1] = !lazy[2 * node + 1]; 26 | lazy[2 * node + 2] = !lazy[2 * node + 2]; 27 | } 28 | lazy[node] = 0; 29 | } 30 | // non overlapping case 31 | if (start > r || ending < l) { 32 | return 0; 33 | } 34 | 35 | // complete overlap 36 | if (start >= l && ending <= r) { 37 | return st[node]; 38 | } 39 | 40 | // partial case 41 | int mid = (start + ending) / 2; 42 | 43 | int q1 = query(start, mid, l, r, 2 * node + 1); 44 | int q2 = query(mid + 1, ending, l, r, 2 * node + 2); 45 | 46 | return q1 + q2; 47 | } 48 | 49 | void update(int start, int ending, int node, int l, int r, int value) { 50 | 51 | // lazy propagation / clear the lazy update 52 | if (lazy[node]) { 53 | // pending updates 54 | // update the segment tree node 55 | st[node]=(ending - start + 1)-st[node]; 56 | if (start != ending) { 57 | // propagate the updated value 58 | lazy[2 * node + 1] = !lazy[2 * node + 1]; 59 | lazy[2 * node + 2] = !lazy[2 * node + 2]; 60 | } 61 | lazy[node] = 0; 62 | } 63 | // non overlapping case 64 | if (start > r || ending < l) { 65 | return ; 66 | } 67 | 68 | // complete overlap 69 | if (start >= l && ending <= r) { 70 | if (start != ending) { 71 | lazy[2 * node + 1] = !lazy[2 * node + 1]; 72 | lazy[2 * node + 2] = !lazy[2 * node + 2]; 73 | } 74 | st[node] = (ending - start + 1)-st[node]; 75 | return; 76 | } 77 | 78 | // partial case 79 | int mid = (start + ending) / 2; 80 | 81 | update(start, mid, 2 * node + 1, l, r, value); 82 | 83 | update(mid + 1, ending, 2 * node + 2, l, r, value); 84 | 85 | st[node] = st[node * 2 + 1] + st[node * 2 + 2]; 86 | 87 | return; 88 | } 89 | int query(int l, int r) { 90 | return query(0, n - 1, l, r, 0); 91 | } 92 | 93 | void update(int l, int r, int x) { 94 | update(0, n - 1, 0, l, r, x); 95 | } 96 | }; 97 | void solve() { 98 | int n, q, a, l, r; 99 | cin>>n>>q; 100 | segmenttree tree; 101 | tree.init(n); 102 | while(q--){ 103 | cin>>a>>l>>r; 104 | if(a==0){ 105 | tree.update(l,r,1); 106 | 107 | } 108 | if(a==1){ 109 | cout< 2 | 3 | using namespace std; 4 | 5 | // summation 6 | struct segmenttree { 7 | int n; 8 | vector st, lazy; 9 | 10 | void init(int _n) { 11 | this->n = _n; 12 | st.resize(4 * n, 0); 13 | lazy.resize(4 * n, 0); 14 | } 15 | 16 | void build(int start, int ending, int node, vector &v) { 17 | // leaf node base case 18 | if (start == ending) { 19 | st[node] = v[start]; 20 | return; 21 | } 22 | 23 | int mid = (start + ending) / 2; 24 | 25 | // left subtree is (start,mid) 26 | build(start, mid, 2 * node + 1, v); 27 | 28 | // right subtree is (mid+1,ending) 29 | build(mid + 1, ending, 2 * node + 2, v); 30 | 31 | st[node] = st[node * 2 + 1] + st[node * 2 + 2]; 32 | } 33 | 34 | int query(int start, int ending, int l, int r, int node) { 35 | // non overlapping case 36 | if (start > r || ending < l) { 37 | return 0; 38 | } 39 | 40 | // lazy propagation / clear the lazy update 41 | if (lazy[node] != 0) { 42 | // pending updates 43 | // update the segment tree node 44 | st[node] = lazy[node] * (ending - start + 1); 45 | if (start != ending) { 46 | // propagate the updated value 47 | lazy[2 * node + 1] += lazy[node]; 48 | lazy[2 * node + 2] += lazy[node]; 49 | } 50 | lazy[node] = 0; 51 | } 52 | 53 | // complete overlap 54 | if (start >= l && ending <= r) { 55 | return st[node]; 56 | } 57 | 58 | // partial case 59 | int mid = (start + ending) / 2; 60 | 61 | int q1 = query(start, mid, l, r, 2 * node + 1); 62 | int q2 = query(mid + 1, ending, l, r, 2 * node + 2); 63 | 64 | return q1 + q2; 65 | } 66 | 67 | void update(int start, int ending, int node, int l, int r, int value) { 68 | // non overlapping case 69 | if (start > r || ending < l) { 70 | return ; 71 | } 72 | 73 | // lazy propagation / clear the lazy update 74 | if (lazy[node] != 0) { 75 | // pending updates 76 | // update the segment tree node 77 | st[node] += lazy[node] * (ending - start + 1); 78 | if (start != ending) { 79 | // propagate the updated value 80 | lazy[2 * node + 1] += lazy[node]; 81 | lazy[2 * node + 2] += lazy[node]; 82 | } 83 | lazy[node] = 0; 84 | } 85 | 86 | // complete overlap 87 | if (start >= l && ending <= r) { 88 | st[node] += value * (ending - start + 1); 89 | if (start != ending) { 90 | lazy[2 * node + 1] += value; 91 | lazy[2 * node + 2] += value; 92 | } 93 | return; 94 | } 95 | 96 | // partial case 97 | int mid = (start + ending) / 2; 98 | 99 | update(start, mid, 2 * node + 1, l, r, value); 100 | 101 | update(mid + 1, ending, 2 * node + 2, l, r, value); 102 | 103 | st[node] = st[node * 2 + 1] + st[node * 2 + 2]; 104 | 105 | return; 106 | } 107 | 108 | void build(vector &v) { 109 | build(0, n - 1, 0, v); 110 | } 111 | 112 | int query(int l, int r) { 113 | return query(0, n - 1, l, r, 0); 114 | } 115 | 116 | void update(int l, int r, int x) { 117 | update(0, n - 1, 0, l, r, x); 118 | } 119 | }; 120 | 121 | int main() 122 | { 123 | freopen("input.txt", "r", stdin); 124 | freopen("output.txt", "w", stdout); 125 | 126 | vector v = {1, 2, 3, 4, 5, 6, 7, 8}; 127 | // cout << v.size(); 128 | 129 | segmenttree tree; 130 | 131 | tree.init(v.size()); 132 | 133 | tree.build(v); 134 | 135 | cout << tree.query(0, 4) << '\n'; 136 | 137 | tree.update(0, 1, 10); 138 | 139 | cout << tree.query(0, 4) << '\n'; 140 | 141 | return 0; 142 | } --------------------------------------------------------------------------------