Repository: srbcheema1/Algo_Ds Branch: master Commit: d69ddbb67cd8 Files: 253 Total size: 367.4 KB Directory structure: gitextract_r3ies5y1/ ├── .gitignore ├── BST/ │ ├── BinarySearchTree.java │ ├── Delete.c │ ├── Height.c │ ├── Insert & Search.cpp │ ├── MinMax_8.c │ ├── checkbst │ ├── createBST.cpp │ ├── lca.cpp │ └── spiraltransversal.c ├── Backtrack/ │ ├── NQueen.cpp │ ├── Rat_Maze_Recurssion_Backtracking.c │ ├── nqueen_allsol.py │ └── permutations_of_string.cpp ├── CONTRIBUTING.md ├── Competitive Programming Challenges/ │ └── C:C++/ │ ├── HackerEarth:CodeForces/ │ │ ├── buy_max_with_given_money.cpp │ │ ├── median searching efficientalgo.cpp │ │ ├── ques/ │ │ │ └── volcano.cpp │ │ ├── ques-beat_the_clock/ │ │ │ └── spiral_matrix.cpp │ │ ├── ques-l1/ │ │ │ ├── codeforces_426_2.cpp │ │ │ ├── positions.cpp │ │ │ └── snake/ │ │ │ ├── snake.cpp │ │ │ └── wrong_snake.cpp │ │ └── searchmat.cpp │ └── Patterns/ │ ├── pattern1.cpp │ ├── pattern2.cpp │ ├── pattern3.cpp │ ├── pattern4.cpp │ ├── pattern6.cpp │ └── pattern7.cpp ├── Conversions/ │ └── C:C++/ │ └── binary2octal.c ├── Data Structures/ │ ├── C:C++/ │ │ ├── Applications/ │ │ │ ├── Evaluating Postfix Expression.c │ │ │ ├── Infix to Postfix.c │ │ │ ├── balance parenthesis.cpp │ │ │ └── stack_and_its_implementation.c │ │ ├── Graph/ │ │ │ ├── FloydWarshall.cpp │ │ │ ├── adjacency_list.hpp │ │ │ ├── adjacency_matrix.hpp │ │ │ ├── bfs_dfs/ │ │ │ │ ├── bfs/ │ │ │ │ │ ├── BFS.java │ │ │ │ │ └── bfs.Py │ │ │ │ └── ques/ │ │ │ │ ├── graph_connected_components.cpp │ │ │ │ └── tbbfs.cpp │ │ │ ├── dijakstra/ │ │ │ │ ├── Dijkstra.java │ │ │ │ ├── dist_from_source.cpp │ │ │ │ ├── dist_from_source_oops.cpp │ │ │ │ └── ques/ │ │ │ │ ├── min_path.cpp │ │ │ │ └── qgrid_11.cpp │ │ │ ├── shortest_paths.hpp │ │ │ ├── topological_sort.hpp │ │ │ └── tree/ │ │ │ └── binarySearchTree/ │ │ │ └── bsTree.cpp │ │ ├── Linked List/ │ │ │ ├── Circular_LL.c │ │ │ ├── Circular_ll.cpp │ │ │ ├── Doubly LL.c │ │ │ ├── Insertion_Deletion_SinglyLL.c │ │ │ ├── Queue using LinkedList.cpp │ │ │ ├── Queue_using_linkedlist.c │ │ │ ├── Reverse_SinglyLL.c │ │ │ ├── all_operations_of_Doubly_ll.cpp │ │ │ ├── concatinate.c │ │ │ ├── doubly circular.c │ │ │ ├── doubly linked list.c │ │ │ ├── linked_list.c │ │ │ ├── ordered_linked.c │ │ │ ├── reverse.cpp │ │ │ ├── stackLinkedList.cpp │ │ │ └── stack_Linked_List.c │ │ ├── Stack/ │ │ │ ├── Balanced_Brackets.cpp │ │ │ ├── Reverse_Queue.cpp │ │ │ ├── Stack_as_linked_list.cpp │ │ │ ├── largestRectangleHistogram.cpp │ │ │ ├── nextgreaterelement │ │ │ └── stack.hpp │ │ ├── Trees/ │ │ │ ├── segment_tree/ │ │ │ │ ├── segment_tree.cpp │ │ │ │ └── segment_trees_lazy.cpp.cpp │ │ │ └── tree/ │ │ │ ├── Fenwick_tree.cpp │ │ │ ├── bst.hpp │ │ │ ├── segment_tree.hpp │ │ │ ├── tree.hpp │ │ │ └── trie.cpp │ │ └── queue/ │ │ └── queue.hpp │ ├── Java/ │ │ └── Stack/ │ │ └── Stack.java │ └── Python/ │ ├── Graphs/ │ │ ├── Graph.py │ │ └── dfs.py │ ├── Linked List/ │ │ └── singly_linked_list.py │ ├── Queue/ │ │ └── Queue.py │ ├── Stack/ │ │ └── stack.py │ └── Trees/ │ └── m-coloring-problem.py ├── Dynamic Programing/ │ ├── Dynamic_fibonacci.py │ ├── Edit Distance.Py │ ├── Knapsack.py │ ├── Memoized Cut Rod.Py │ ├── Word_Wrap.Py │ └── longest_increasing_subsequence.cpp ├── Mathematical Challenges/ │ ├── C:C++/ │ │ ├── Fibonacci/ │ │ │ └── Fibonacci Test.cpp │ │ ├── Square Root Decomposition/ │ │ │ └── MO's Algorithm/ │ │ │ └── MOAlgo.cpp │ │ ├── armstrong_number/ │ │ │ ├── C/ │ │ │ │ └── armstrong.c │ │ │ └── README.md │ │ ├── convexHull/ │ │ │ └── ConvexHullScan.cpp │ │ ├── factorial/ │ │ │ └── factorial.c │ │ ├── fibbinacci/ │ │ │ └── fibbinacci.c │ │ ├── gcd/ │ │ │ ├── extended_gcd.cpp │ │ │ ├── gcd.cpp │ │ │ └── mod_inverse.cpp │ │ ├── largestoutof3/ │ │ │ └── largestoutof3.c │ │ ├── mathpuzzle.c/ │ │ │ └── matchstick game │ │ ├── multiplication/ │ │ │ └── multiply 2 numbers greater than 10^6.cpp │ │ ├── power/ │ │ │ ├── modular_exponention.cpp │ │ │ ├── ques/ │ │ │ │ └── summation.cpp │ │ │ └── two_pow.cpp │ │ ├── powerset/ │ │ │ └── PowerSet.java │ │ ├── prime/ │ │ │ ├── PrimeCheck.py │ │ │ ├── PrimeToNumber.py │ │ │ ├── prime.c │ │ │ └── sieveOferatosthenes.cpp │ │ ├── prime number tricks/ │ │ │ └── List all primes.cpp │ │ └── ques/ │ │ └── cpcrc1c.cpp │ └── python/ │ ├── pernicious_prime/ │ │ └── pernicious.py │ └── sieve_of_eratoshthenes.py ├── Patterns/ │ ├── pattern10.cpp │ ├── pattern11.cpp │ ├── pattern12.cpp │ ├── pattern13.cpp │ ├── pattern14.cpp │ ├── pattern15.cpp │ ├── pattern16.cpp │ ├── pattern8.cpp │ └── pattern9.cpp ├── README.md ├── STL C++/ │ ├── STACK_with_Application/ │ │ ├── Evaluating Postfix Expression.c │ │ ├── Infix to Postfix.c │ │ ├── balance parenthesis.cpp │ │ └── stack_and_its_implementation.c │ ├── sorting_a_vector.cpp │ ├── stack/ │ │ ├── Stack.java │ │ ├── largestRectangleHistogram.cpp │ │ └── stack.hpp │ ├── using_map.cpp │ └── using_set.cpp ├── STRUCTURE.md ├── Searching Algorithms/ │ ├── Bogo_sort.cpp │ ├── C:C++/ │ │ ├── Binary_Search.cpp │ │ ├── Binary_search.cpp │ │ ├── Interpolation Search │ │ ├── Interpolation_search.cpp │ │ ├── Jump_Search.cpp │ │ ├── Liear_search.cpp │ │ ├── MEDIAN_SEARCH.cpp │ │ ├── Selection_sort.cpp │ │ ├── Ternary_search.cpp │ │ ├── b_search.cpp │ │ ├── fibonacci_search.cpp │ │ ├── seaching algorithms [rename]/ │ │ │ ├── binary_search.cpp │ │ │ ├── binary_search_extras/ │ │ │ │ ├── position_in_sorted_array/ │ │ │ │ │ ├── eq_less_than.cpp │ │ │ │ │ ├── first_occurance.cpp │ │ │ │ │ ├── just_less_than_num.cpp │ │ │ │ │ └── position_in_sorted_array.cpp │ │ │ │ └── ques/ │ │ │ │ └── aggrcow.cpp │ │ │ ├── jump_search.cpp │ │ │ └── linear.cpp │ │ ├── ternarySearch.cpp │ │ └── ternary_search.c │ ├── Java/ │ │ ├── TODO │ │ ├── algos/ │ │ │ ├── BinarySearch.java │ │ │ └── LinearSearch.java │ │ └── driving.java │ └── Python/ │ ├── binarysearch.py │ └── bst.py ├── Segment Trees/ │ ├── ADA/ │ │ ├── README.md │ │ └── segmentree.adb │ ├── C++/ │ │ ├── RangeMinimumQuery.cpp │ │ └── SumInGivenRange.cpp │ └── Java/ │ ├── SegementTree.java │ └── SegementTreeLazyPropagation.java ├── Sorting Algorithms/ │ ├── C:C++/ │ │ ├── Counting_Sort.cpp │ │ ├── Insertion_sort.cpp │ │ ├── Merge_sort.cpp │ │ ├── QuickSort.c │ │ ├── Quick_sort.cpp │ │ ├── Radix_sort.cpp │ │ ├── bubblesort.c │ │ ├── bubblesort.cpp │ │ ├── bucketsort.c │ │ ├── heapSort.c │ │ ├── insertion.hpp │ │ ├── merge.hpp │ │ ├── quick.hpp │ │ ├── quick_sort.c │ │ ├── radix.hpp │ │ ├── selectionsort.c │ │ ├── shell_sort.h │ │ ├── slow.cpp │ │ └── sorting_a_vector.cpp │ ├── Java/ │ │ ├── Countsort.java │ │ ├── HeapSort.java │ │ └── MergeSort.java │ ├── Javascript/ │ │ └── bubblesort.js │ ├── Python/ │ │ ├── QuickSort.py │ │ ├── bogosort.py │ │ ├── bubblesort.py │ │ ├── cocktailsort.py │ │ ├── insertionsort.py │ │ ├── mergesort.py │ │ ├── quicksort.py │ │ └── topological_sort.py │ └── sleep sort.c ├── String Manipulation/ │ ├── C:C++/ │ │ ├── String_algo/ │ │ │ ├── KMP.cpp │ │ │ ├── SUFFIX-ARRAY.cpp │ │ │ └── z_algorithm.cpp │ │ └── tokens/ │ │ ├── token_break.cpp │ │ └── word_break.cpp │ └── Python/ │ └── LCS.py ├── backtrack/ │ └── sudoku/ │ ├── code2.cpp │ └── sudoku.cpp ├── binary_tree/ │ └── binarytree.java ├── btree.cpp ├── cryptography/ │ ├── Python/ │ │ └── porta.py │ └── des/ │ └── java/ │ ├── Converter.java │ ├── DES.java │ ├── IO.java │ └── Main.java ├── dfs.cpp ├── disjoint_set/ │ └── disjoint_set.hpp ├── divide_and_conquer/ │ ├── maximum_sub_array.cpp │ └── strassen.cpp ├── dp/ │ ├── 0-1knapsack.cpp │ ├── Digit_dp.cpp │ ├── coinchange.cpp │ ├── editDistance.cpp │ ├── eggdropping.cpp │ ├── kadane.cpp │ ├── lcs.cpp │ ├── lis.cpp │ └── mcm.cpp ├── euler_totent_function ├── genome_sort.py ├── graph/ │ ├── Kosaraju_algorithm │ └── bfs_dfs/ │ ├── bfs/ │ │ ├── BFS.cpp │ │ ├── BFS.py │ │ └── bfs.cpp │ └── dfs/ │ ├── DFS.cpp │ └── DFS.java ├── heap/ │ ├── heap.hpp │ └── min_heap.cpp ├── os/ │ └── scheduling/ │ ├── fcfs.cpp │ ├── os_priority.cpp │ ├── os_roundrobin.cpp │ ├── os_sjf.cpp │ ├── os_srtf.cpp │ └── readme.txt ├── shellsort.c ├── sieve_of_eratoshthenes.cpp ├── square_root_decomposition └── travelling_salesman_problem ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ build*/ # ----------- C++ ------------------ # Prerequisites *.d # Compiled Object files *.slo *.lo *.o *.obj # Precompiled Headers *.gch *.pch # Compiled Dynamic libraries *.so *.dylib *.dll # Fortran module files *.mod *.smod # Compiled Static libraries *.lai *.la *.a *.lib # Executables *.exe *.out *.app # ----------- CMake ------------------ CMakeCache.txt CMakeFiles CMakeScripts Testing Makefile cmake_install.cmake install_manifest.txt compile_commands.json CTestTestfile.cmake # files to check the functionality check_*.cpp .DS_STORE ================================================ FILE: BST/BinarySearchTree.java ================================================ /* * @author Nikunj Khokhar */ public class BinarySearchTree { class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } } Node root; BinarySearchTree() { this.root = null; } void insert(int key) { root = insertRec(root, key); } Node insertRec(Node root, int key) { if (root == null) { root = new Node(key); return root; } if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); return root; } void inorder() { inorderRec(root); } void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.println(root.key); inorderRec(root.right); } } void preorder() { preorderRec(root); } void preorderRec(Node root) { if (root != null) { System.out.println(root.key); preorderRec(root.left); preorderRec(root.right); } } void postorder() { postorderRec(root); } void postorderRec(Node root) { if (root != null) { postorderRec(root.left); postorderRec(root.right); System.out.println(root.key); } } } public class Main { public static void main(String args[]) { BinarySearchTree tree = new BinarySearchTree(); tree.insert(50); tree.insert( 30); tree.insert( 20); tree.insert( 40); tree.insert( 70); tree.insert( 60); tree.insert(80); System.out.println("Inorder traversal of the given tree : "); tree.inorder(); System.out.print("\n\n"); System.out.println("Postorder traversal of the given tree : "); tree.postorder(); System.out.print("\n\n"); System.out.println("Preorder traversal of the given tree : "); tree.preorder(); } } ================================================ FILE: BST/Delete.c ================================================ #include #include struct tree{ int data; struct tree *left; struct tree *right; }*root=NULL,*newn; struct tree* create(int n) { newn=(struct tree*)malloc(sizeof(struct tree)); newn->data=n; newn->left=NULL; newn->right=NULL; return newn; } struct tree* ins(struct tree*r,int dat) { if(r==NULL) return create(dat); if(dat < r->data) r->left=ins(r->left,dat); else if(dat > r->data) r->right=ins(r->right,dat); return r; } int max=-10000,min=10000; void preorder(struct tree* n) { if(n==NULL) return; else { preorder(n->left); preorder(n->right); printf("Deleting Node:%d\n",n->data); free(n); } } int flag=0; void main() { int choice=1,t,ne, exit; printf("Enter Root Node:\n"); scanf("%d",&ne); root=ins(root,ne); while(choice!=0) { printf("Enter Value:\n"); scanf("%d",&t); ins(root,t); printf("Want to Continue the tree:1 or 0...?\n"); scanf("%d",&choice); } preorder(root); scanf("%d", exit); } ================================================ FILE: BST/Height.c ================================================ #include #include struct tree{ int data; struct tree* left; struct tree* right; }; struct tree* create(int dat) { struct tree* n=(struct tree*)malloc(sizeof(struct tree)); n->data=dat; n->left=NULL; n->right=NULL; return n; } int height(struct tree* n) { int l,r; if(n==NULL) return 0; else { l=height(n->left); r=height(n->right); if(l>r) return(l+1); else return (r+1); } } int count=0; int node(struct tree* n) { if(n==NULL) return count; else { node(n->left); node(n->right); count++; } } void main() { struct tree* root; int ans, exit; root=create(30); ans=height(root); printf("Height of tree after first insertion: %d\n",ans); root->left=create(20); root->right=create(40); root->left->left=create(60); ans=height(root); printf("Height of given tree: %d\n",ans); ans=node(root); printf("No. of nodes: %d\n",ans); scanf("%d", exit); } ================================================ FILE: BST/Insert & Search.cpp ================================================ /****************************************** * AUTHOR : VIVEK SHAH * * INSTITUTION : NIT SURAT * ******************************************/ #include #define boost ios_base::sync_with_stdio(false);cin.tie(NULL) #define ll long long int #define mod 1000000007 #define rep(i,a,b) for (ll i = a; idata = data; tmp->left = NULL; tmp->right = NULL; return tmp; } struct node* insert(struct node* root,int data){ if (root==NULL) { root = getNode(data); } else if (data <= root->data) { root->left = insert(root->left,data); } else{ root->right = insert(root->right,data); } return root; } int search(struct node* root, int data){ if (root==NULL) { return 0; } else if (root->data = data) { return 1; } else if (data<=root->data) { return search(root->left,data); } else{ return search(root->right,data); } } int main() { boost; struct node* root = NULL; root = insert(root,15); root = insert(root,10); root = insert(root,20); if(search(root,15)){ cout<<"Found"; } else cout<<"Not Found"; return 0; } ================================================ FILE: BST/MinMax_8.c ================================================ #include #include struct tree{ int data; struct tree *left; struct tree *right; }*root=NULL,*newn; struct tree* create(int n) { newn=(struct tree*)malloc(sizeof(struct tree)); newn->data=n; newn->left=NULL; newn->right=NULL; return newn; } struct tree* ins(struct tree*r,int dat) { if(r==NULL) return create(dat); if(dat < r->data) r->left=ins(r->left,dat); else if(dat > r->data) r->right=ins(r->right,dat); return r; } int max=-10000,min=10000; void Preo(struct tree* n) { if(n==NULL) return; if(n->data>max) max=n->data; if(n->datadata; //printf("%d ",n->data); Preo(n->left); Preo(n->right); } void main() { int choice=1,t,ne, exit; printf("Enter Root Node:\n"); scanf("%d",&ne); root=ins(root,ne); while(choice!=0) { printf("Enter Data:\n"); scanf("%d",&t); ins(root,t); printf("Want to Continue the tree:1 or 0...?\n"); scanf("%d",&choice); } Preo(root); printf("Minimum:%d\n",min); printf("Maximum:%d\n",max); scanf("%d", exit); } ================================================ FILE: BST/checkbst ================================================ / C++ program to check if a given tree is BST. #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left, *right; }; // Returns true if given tree is BST. bool isBST(Node* root, Node* l=NULL, Node* r=NULL) { // Base condition if (root == NULL) return true; // if left node exist that check it has // correct data or not if (l != NULL and root->data < l->data) return false; // if right node exist that check it has // correct data or not if (r != NULL and root->data > r->data) return false; // check recursively for every node. return isBST(root->left, l, root) and isBST(root->right, root, r); } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } /* Driver program to test above functions*/ int main() { struct Node *root = newNode(3); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(1); root->left->right = newNode(4); if (isBST(root)) cout << "Is BST"; else cout << "Not a BST"; return 0; } ================================================ FILE: BST/createBST.cpp ================================================ #include #include typedef struct BST { int data; struct BST *left; struct BST *right; }node; node *create(); void insert(node *,node *); void preorder(node *); int main() { char ch; node *root=NULL,*temp; do { temp=create(); if(root==NULL) root=temp; else insert(root,temp); printf("nDo you want to enter more(y/n)?"); getchar(); scanf("%c",&ch); }while(ch=='y'|ch=='Y'); printf("nPreorder Traversal: "); preorder(root); return 0; } node *create() { node *temp; printf("nEnter data:"); temp=(node*)malloc(sizeof(node)); scanf("%d",&temp->data); temp->left=temp->right=NULL; return temp; } void insert(node *root,node *temp) { if(temp->datadata) { if(root->left!=NULL) insert(root->left,temp); else root->left=temp; } if(temp->data>root->data) { if(root->right!=NULL) insert(root->right,temp); else root->right=temp; } } void preorder(node *root) { if(root!=NULL) { printf("%d ",root->data); preorder(root->left); preorder(root->right); } } ================================================ FILE: BST/lca.cpp ================================================ /* Author: Pritish Thakkar Codechef : joe001 Blog : http://sleepincode.blogspot.com */ /// SUMMARY: /// The lowest common ancestor between two nodes n1 /// and n2 is defined as the lowest node in BST that /// has both n1 and n2 as descendants (where we allow /// a node to be a descendant of itself). // This contains almost all headers required during // competitive programming contests, and that's why used // by every best coder out there.. #include using namespace std; // Structure if a node in BST struct node{ int data; struct node* left; struct node* right; }; // Returns a new whenever required struct node* getNode(int data){ struct node* tmp = new node(); tmp->data = data; tmp->left = NULL; tmp->right = NULL; return tmp; } // Function to insert the elements in a BST struct node* insert(struct node* root,int data){ if (root==NULL) { root = getNode(data); } else if (data <= root->data) { root->left = insert(root->left,data); } else{ root->right = insert(root->right,data); } return root; } // Returns the value of LCA node. int lca(node* root, int val1, int val2){ // If boths values are smaller than current node value // it means LCA is present in left subtree. if(root->data > val1 && root->data > val2){ return lca(root->left, val1, val2); } // If boths values are greater than current node value // it means LCA is present in right subtree. if(root->data < val1 && root->data < val2){ return lca(root->right, val1, val2); } // Now, one is in left subtree and other in right subtree // return current node value. return root->data; } int main(){ struct node* root = NULL; // Inserting the values in the BST root = insert(root,15); root = insert(root,10); root = insert(root,20); root = insert(root,16); root = insert(root,17); root = insert(root,12); cout << lca(root, 12, 17) << endl; // OUTPUT : 15 } ================================================ FILE: BST/spiraltransversal.c ================================================ #include #include #include #include //structure of node struct node{ int data; struct node* left; struct node* right; }; struct node* root; //insertion into bst struct node* insert(struct node *rootptr,int data) { if(rootptr==NULL) { rootptr=(struct node*)malloc(sizeof(struct node)); rootptr->data=data; rootptr->left=NULL; rootptr->right=NULL; return; } else if(data<=rootptr->data) { rootptr->left=insert(rootptr->left,data); } else if(data>= rootptr->data) { rootptr->right=insert(rootptr->right,data); } return rootptr; } //inorder transversal of tree void inorder(struct node* rootptr) { if(rootptr==NULL) return; inorder(rootptr->left); printf("%d ",rootptr->data); inorder(rootptr->right); } //to print a level of tree void printGivenLevel(struct node* root, int level, int ltr) { if(root == NULL) return; if(level == 1) printf("%d ", root->data); else if (level > 1) { if(ltr) { printGivenLevel(root->left, level-1, ltr); printGivenLevel(root->right, level-1, ltr); } else { printGivenLevel(root->right, level-1, ltr); printGivenLevel(root->left, level-1, ltr); } } } //to find height of tree int height(struct node* node) { if (node==NULL) return 0; else { int lheight = height(node->left);//to find height of left subtree int rheight = height(node->right);//to find height of right subtree if (lheight > rheight) return(lheight+1); else return(rheight+1); } } //for spiral transversal of tree void printSpiral(struct node* root) { int h = height(root); int i; /*ltr -> Left to Right. If this variable is set, then the given level is traverseed from left to right. */ bool ltr = false; for(i=1; i<=h; i++) { printGivenLevel(root, i, ltr); /*Revert ltr to traverse next level in opposite order*/ ltr = !ltr; } } main() { root=NULL; int n,data; while(1) { printf("1.insert\n2.display\n3.Spiral Order traversal\n4.exit\nenter choice\n"); scanf("%d",&n); switch(n) { case 1: printf("enter data"); scanf("%d",&data); root=insert(root,data); break; case 2:inorder(root); break; case 3:printf("Spiral Order traversal of binary tree is \n"); printSpiral(root); case 4:return; } } } ================================================ FILE: Backtrack/NQueen.cpp ================================================ #include using namespace std; bool isSafe(char board[][100], int row, int column, int n){ //check that whole row should not have a queen for(int i=0; i=0 && q>=0){ if(board[p][q] == 'Q') return false; p--; q--; } //check that right diagonal to the current cell should not have queen p=row; q=column; while(p>=0 && q<=n-1){ if(board[p][q] == 'Q') return false; p--; q++; } return true; } bool nqueen(char board[][100], int n, int i=0){ if(i == n){ //board is filled with the n-queens, just print the board for(int i=0; i> n; char board[100][100]; for(int i=0; i #define N 4 void display(int sol[N][N]) { int i,j; for(i=0;i=0 && x<4) && (y>=0 && y<3) && maze[x][y]==1) return 1; else return 0; } int solvemaze(int maze[N][N],int x,int y,int sol[N][N]) { if(x==N-1 && y==N-1) { sol[x][y]=1; return 1; } if(issafe(maze,x,y)==1) { sol[x][y]=1; if(solvemaze(maze,x+1,y,sol)==1) return 1; if(solvemaze(maze,x,y+1,sol)==1) return 1; sol[x][y]=0; return 0; } return 0; } void solve(int maze[N][N]) { int sol[N][N]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; if(solvemaze(maze,0,0,sol)==0) { printf("No Solution possible\n"); } else { display(sol); } } void main() { int maze[N][N]={{1,0,0,0},{1,1,0,1},{0,1,0,0},{1,1,1,1}}; solve(maze); } ================================================ FILE: Backtrack/nqueen_allsol.py ================================================ def initialize(board,n): keys=['queen','row','col','pdiag','sdiag'] for i in keys: board[i]={} for i in range(n): board['queen'][i]=-1 board['row'][i]=0 board['col'][i]=0 for i in range(-(n-1),n): board['pdiag'][i]=0 for i in range(0,2*n-1): board['sdiag'][i]=0 def placequeen(r,board,n): return True def printboard(board,n): for row in board['queen'].keys(): print('(',row,',',board['queen'][row],')',end=' ') print('') def isfree(i,j,board): return (board['row'][i]==0 and board['col'][j]==0 and board['pdiag'][j-i]==0 and board['sdiag'][j+i]==0) def addqueen(i,j,board): board['queen'][i]=j board['row'][i]=1 board['col'][j]=1 board['pdiag'][j-i]=1 board['sdiag'][j+i]=1 def undoqueen(i,j,board): board['queen'][i]=-1 board['row'][i]=0 board['col'][j]=0 board['pdiag'][j-i]=0 board['sdiag'][j+i]=0 def placequeen(i,board,n): for j in range(n): if isfree(i,j,board): addqueen(i,j,board) if i==n-1: printboard(board,n) else: extend=placequeen(i+1,board,n) undoqueen(i,j,board) #main n=int(input('Enter the number of queens:')) board={} initialize(board,n) placequeen(0,board,n) ================================================ FILE: Backtrack/permutations_of_string.cpp ================================================ // Solution for printing all the permutations of a string. #include /* Function to swap values at two pointers */ void swap(char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } /* Function to print permutations of string This function takes three parameters: 1. String 2. Starting index of the string 3. Ending index of the string. */ void permute(char *a, int l, int r) { int i; if (l == r) cout<Contributing Guidelines for Algo_Ds

Thanks for taking the time to contribute to this project. Before making PRs, please note the following:

A few norms you should follow

  • Proper intendation is must!
  • Include ample comments so that code is understandable and easy to follow.
  • Mention the complexity of a function in a comment.
    • Time complexity :
    • Space complexity :
  • Place your code in right directory.
  • Give your files names that are relevant and meaningful.

You may add your solved questions on spoj, codechef, interviewbit, hackerearth, hackerrank and codeforces.

  • First line of your code must begin with a comment mentioning the link of the question
  • Place the solutions in seperate folder "ques" in relevant directory

DESCRIPTION.md

If not already present, you are free to create a DESCRIPTION.md file in a folder:

  • Please write a brief description of your algorithm in DESCRIPTION.md file
  • Suggestions of things to include in DESCRIPTION.md file:
    • Description of algorithm
    • Time and space complexity of algorithm
    • Links to your favourite online questions solvable by that algorithm
    • You may also provide solution to related questions in "ques" folder in the same directory.
    • Also, mention link of solution (if available) along with the question link.

Best Practices for opening a Pull Request

  • Give the PR a meaningful name.
  • For e.g. 'Fixes #(issue-number): PR name, fixing the particular bug' (without commas)
  • There should be always 1 commit for 1 PR.
  • If there are more than 1 commit in a PR, squash them.
  • Pull Request details should be descriptive.
  • Commit message should meaningful.

please have a look at STRUCTURE.md for file structure

================================================ FILE: Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/buy_max_with_given_money.cpp ================================================ //https://www.hackerrank.com/contests/gs-codesprint/challenges/buy-maximum-stock////i///////i/s #include #define F0(i,t) for(int i=0; i mp; int debugg = 0; bool sort_fxn(mp a,mp b){ return a.second < b.second; } /* * return maximum number of elements we can buy... * we can buy max i elements at i day * vector a is 0 based * a[i] contains price of that elem * k = max amount to be spent */ ulli buyMaximumProducts(ulli n, ulli k, vector a) { vector vec(n); for(int i=0;i amount) break; } return bought; } int main() { ulli n,k; cin >> n; vector arr(n); for(ulli i = 0; i < n; i++) cin >> arr[i]; ulli k; cin >> k; ulli result = buyMaximumProducts(n, k, arr); cout << result << endl; } // a code by srbcheema1 ================================================ FILE: Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/median searching efficientalgo.cpp ================================================ #include #include #include #include using namespace std; int median(int *a,int s,int r,int k); int pivot(int *a,int s,int r); int main() { int *a; int n; cin>>n; a=new int[n]; for(int i=0;i>a[i]; } int k; cin>>k; int x=median(a,0,n-1,k); cout<<"kth smallest element is\n"<k) { median(v1,s,s1-1,k); } else if(s1+s2>k) { return p; } else{ median(v3,s1+s2-1,r,k-s1-s2); } } int pivot(int *a,int s,int r) { int t; if((r+1)%5==0) { t=(r+1)/5; } else{ t=((r+1)/5)+1; } int b[t][5]; int p; int k=0; for(int i=0;i #define F0(i,t) for(int i=0; i mp; typedef vector > matrix; struct elem{ int x; int y; int w; elem(int x,int y,int w){ this->x = x; this->y = y; this->w = w; } }; int debugg = 0; void fill(int x,int y,int w,int n,matrix& mat,matrix& filled){ queue q; q.push(elem(x,y,w)); while(!q.empty()){ elem temp = q.front(); x = temp.x; y = temp.y; w = temp.w; q.pop(); if(x<0 || y<0 || x>=n || y>=n || w<=0 )continue; if(filled[x][y]==1) continue; filled[x][y]=1; mat[x][y] += w; q.push(elem(x+1,y,w-1)); q.push(elem(x,y+1,w-1)); q.push(elem(x-1,y,w-1)); q.push(elem(x,y-1,w-1)); q.push(elem(x-1,y+1,w-1)); q.push(elem(x-1,y-1,w-1)); q.push(elem(x+1,y+1,w-1)); q.push(elem(x+1,y-1,w-1)); } } int main(){ int t=1; ios_base::sync_with_stdio(0);cin.tie(0); while(t--){ int n,m,x,y,w,maxx=0; cin>>n>>m; matrix mat(n,vector(n,0)); while(m--){ cin>>x>>y>>w; matrix filled(n,vector(n,0)); fill(x,y,w,n,mat,filled); } for(int i=0;imaxx){ maxx=mat[i][j]; } } } cout< #define F0(i,t) for(int i=0; i mp; int debugg = 0; /* * func to return matrix in a vector such that it is unfolded * vec is vector of vectors containing the matrix * m and n are dimentions */ vector func(vector > vec,int m,int n){ vector ans; int l=0,r=n-1,u=0,d=m-1; int row=0;int col=0; while(true){ if(l>r || u>d) break; for(int i=l;i<=r;i++){// >>> dout<<"> "; ans.push_back(vec[row][i]); } col = r; u = u+1; if(l>r || u>d) break; for(int i=u;i<=d;i++){// V dout<<"V "; ans.push_back(vec[i][col]); } row = d; r = r-1; if(l>r || u>d) break; for(int i=r;i>=l;i--){// <<< dout<<"< "; ans.push_back(vec[row][i]); } col=l; d = d-1; if(l>r || u>d) break; for(int i=d;i>=u;i--){// ^ dout<<"^ "; ans.push_back(vec[i][col]); } row = u; l = l+1; if(l>r || u>d) break; } return ans; } int main(){ int t=1,n,m,temp; ios_base::sync_with_stdio(0);cin.tie(0); cin>>t; while(t--){ cin>>m>>n; vector > vec(m); for(int i=0;i>temp; vec[i].push_back(temp); } vector ans = func(vec,m,n); for(int i=0;i using namespace std; int main(){ int g,k; int start[27]; int last[27]; cin>>g>>k; string str; cin>>str; int alot=0,free=0,gate=0; memset(start,-1,sizeof(start)); memset(last,-1,sizeof(last)); for(int i=0;ik) cout<<"YES"< using namespace std; int main(){ int n; long long int sum; ios_base::sync_with_stdio(false); cin.tie(NULL); cin>>n; int arr1[n],arr2[n]; for(int i=0;i>arr1[i]; for(int i=0;i>arr2[i]; sort(arr1,arr1+n); sort(arr2,arr2+n); sum=0; for(int i=0;i #define F0(i,t) for(int i=0; i mp; typedef vector > matrix; int debugg = 0; void fill(matrix& mat,int x,int y,int d,int n){ int num=1; if(d==1){//^ while(true){ mat[x][y]=num; num++; if(x-1>=0 && mat[x-1][y]==0){ x = x-1; } else if(y-1>=0 && mat[x][y-1]==0){ y=y-1; } else if(y+1=0 && mat[x][y-1]==0){ y=y-1; } else if(y+1=0 && mat[x-1][y]==0){ x=x-1; } else{ break; } } } if(d==3){//> while(true){ mat[x][y]=num; num++; if(y+1=0 && mat[x-1][y]==0){ x = x-1; } else if(x+1=0 && mat[x][y-1]==0){ y=y-1; } else{ break; } } } if(d==4){//< while(true){ mat[x][y]=num; num++; if(y-1>=0 && mat[x][y-1]==0){ y=y-1; } else if(x-1>=0 && mat[x-1][y]==0){ x = x-1; } else if(x+1>n; string dir; cin>>dir>>x>>y; if(dir[0]=='n')d=1;//^ if(dir[0]=='s')d=2;//v if(dir[0]=='e')d=3;//> if(dir[0]=='w')d=4;//< matrix mat(n,vector(n,0)); fill(mat,x,y,d,n); for(int i=0;i #define F0(i,t) for(int i=0; i mp; typedef vector > matrix; int debugg = 0; void movehu(matrix& mat,int x,int y,int num,int n){ if(y==0) for(int i=n-1;i>=0;i--){ for(int j=0;j=0;j--){ mat[i][j]=num; num++; } } else for(int i=n-1;i>=0;i--){ for(int j=n-1;j>=0;j--){ mat[i][j]=num; num++; } i--; if(i<0)break; for(int j=0;j=n)break; for(int j=n-1;j>=0;j--){ mat[i][j]=num; num++; } } else for(int i=0;i=0;j--){ mat[i][j]=num; num++; } i++; if(i>=n)break; for(int j=0;j=0;j--){ for(int i=0;i=0;i--){ mat[i][j]=num; num++; } } else for(int j=n-1;j>=0;j--){ for(int i=n-1;i>=0;i--){ mat[i][j]=num; num++; } j--; if(j<0)break; for(int i=0;i=n)break; for(int i=n-1;i>=0;i--){ mat[i][j]=num; num++; } } else for(int j=0;j=0;i--){ mat[i][j]=num; num++; } j++; if(j>=n)break; for(int i=0;i>n; string dir; cin>>dir>>x>>y; if(dir[0]=='n')d=1;//^ if(dir[0]=='s')d=2;//v if(dir[0]=='e')d=3;//> if(dir[0]=='w')d=4;//< matrix mat(n,vector(n,0)); fill(mat,x,y,d,n); for(int i=0;i using namespace std; int main(){ // Number of test cases int test; cin >> test; while(test--){ // Number of rows and coloumns in the matrix int a, b; cin >> a >> b; int ar[a][b]; // Array of arrays to store the values of 2D-Matrix for (int i = 0; i < a * b; ++i) { cin >> ar[i % a][i % b]; } // Number to be searched for int x; cin >> x; // Start from top right int i = 0, j = b - 1; while(1){ // Problem solved if element is found if(ar[i][j] == x){ cout << 1; break; } // Move down if element is less than key else if(ar[i][j]x){ j--; } // If element is not found return 0 // as we reach the bottom-left of the matrix // The element was not present if(i >= a || j <0){ cout << 0 << endl; break; } } } return 0; } // Sample test case: // 1 // 3 3 // 2 6 8 // 3 9 12 // 4 10 13 // 9 ================================================ FILE: Competitive Programming Challenges/C:C++/Patterns/pattern1.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; for( int i = 0; i < n; i++ ){ for( int j = 0; j < n; j++ ){ cout << "*"; } cout << endl; } return 0; } /* 5 ***** ***** ***** ***** */ ================================================ FILE: Competitive Programming Challenges/C:C++/Patterns/pattern2.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; for( int i = 0; i < n; i++ ){ for( int j = 0; j <= i; j++ ){ cout << "*"; } cout << endl; } return 0; } /* 5 * ** *** **** ***** */ ================================================ FILE: Competitive Programming Challenges/C:C++/Patterns/pattern3.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; for( int i = n; i > 0; i-- ){ for( int j = 0; j < i; j++ ){ cout << "*"; } cout << endl; } return 0; } /* 5 ***** **** *** ** * */ ================================================ FILE: Competitive Programming Challenges/C:C++/Patterns/pattern4.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; for( int i = 0; i < n; i++ ){ for( int j = 0; j <= i; j++ ){ cout << "*"; } cout << endl; } for( int i = n-1; i > 0; i-- ){ for( int j = 0; j < i; j++ ){ cout << "*"; } cout << endl; } return 0; } /* 5 * ** *** **** ***** **** *** ** * */ ================================================ FILE: Competitive Programming Challenges/C:C++/Patterns/pattern6.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; for( int i = 1; i <= n; i++ ){ for( int j = 1; j <= i; j++ ){ cout << i; } cout << endl; } return 0; } /* 5 1 22 333 4444 55555 */ ================================================ FILE: Competitive Programming Challenges/C:C++/Patterns/pattern7.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; int count = 1; for( int i = 0; i < n; i++ ){ for( int j = 0; j <= i; j++ ){ cout << count << " "; count++; } cout << endl; } return 0; } /* 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */ ================================================ FILE: Conversions/C:C++/binary2octal.c ================================================ // Binary number to octal number conversion #include //Function that returns the last three digits int three_digits(int n) { int r, d = 0, p=1; for(int i=0; i<3; i++) { r = n%10; d = d + r * p; p = p * 10; n = n / 10; } return d; } int main(void) { int binary_num, d=0, base=1, remainder, td, res=0, ord=1; printf("Enter the binary no: "); scanf("%d", &binary_num); while(binary_num > 0) { if(binary_num > 111) //Checking if binary number is greater than three digits td = three_digits(binary_num); else td = binary_num; binary_num = binary_num / 1000; d = 0, base =1; // Converting the last three digits to decimal while(td > 0) { remainder = td % 10; td = td / 10; d = d + (base * remainder); base = base * 2; } res = res + d * ord; // Calculating the octal value ord = ord * 10; } printf("\nOctal equivalent is: %d", res); return 0; } ================================================ FILE: Data Structures/C:C++/Applications/Evaluating Postfix Expression.c ================================================ #include #include #define MAX 200 int isoperator(char c){ return (c=='*' || c=='/' || c=='+' || c=='-'); } struct stack { int top; double a[MAX]; }s; void push(double c){ s.a[++s.top]=c; } double pop(){ return s.a[s.top--]; } double perform(double a, double b, char c){ if (c=='*') { return a*b; } else if (c=='+') { return a+b; } else if (c=='/') { return a/b; } else return a-b; } void post_infix(char a[],int l){ int i; for(i=0;i int j; struct temp{ char a[200]; int top; }; struct temp s; void push(char item){ s.a[++s.top]=item; } int isempty(){ return s.top==-1; } char pop(){ if(!isempty())return s.a[s.top--]; } int isoperator(char c){ if(c=='*'||c=='/'|| c=='+'|| c=='-')return 1; return 0; } int precedence(char c){ if(c=='+' || c=='-')return 1; else if(c=='*' || c=='/')return 2; else if(c=='^')return 3; return 0; } char *infix_postfix(char *p){ int i; j=0; char *p1 = (char *)malloc(100*sizeof(char)); for(i=0;p[i]!='\0';i++){ //printf("%d\n",j); if(isalpha(p[i]) || isdigit(p[i])){ p1[j++]=p[i]; } else if(isoperator(p[i])){//printf("%c\n",p[i]); while(!isempty() && /*s.a[s.top]!='(' &&*/ (precedence(p[i]) <= precedence(s.a[s.top]))){ p1[j++] = s.a[s.top]; pop(); } push(p[i]); } else if(p[i]=='(')push(p[i]); else if(p[i]==')'){ while(!isempty() && s.a[s.top]!='('){ p1[j++]=s.a[s.top]; pop(); } pop(); } } while(!isempty()){ //printf("%c ",s.a[s.top]); p1[j++]=s.a[s.top]; pop(); } //for(i=0;i #include #include #include using namespace std; int main(){ string str; printf("Enter a String"); cin>>str; int l = str.length(); stack s; for(int i=0;i struct stack{ char book_name[200][200]; int book_id[20]; int book_price[20]; int top; }; struct stack *p; int size; void push(){ if((p->top)==size-1){ printf("Overflow"); return; } p->top = p->top +1; //printf("p->top = %d",p->top); printf("\nEnter elements to be pushed : "); printf("\nEnter book name:"); scanf("%s",p->book_name[p->top]); printf("\nEnter book id:"); scanf("%d",&p->book_id[p->top]); printf("\nEnter book price:"); scanf("%d",&p->book_price[p->top]); } void pop(){ if(p->top==-1){ printf("Underflow\n"); } else{ p->top = p->top - 1; } } void peep(){ int i= p->top; printf("\nBook Name : %s",p->book_name[i]); printf("\nBook ID : %d",p->book_id[i]); printf("\nBook Price : %d",p->book_price[i]); printf("\n"); } void print(){ int x = p->top; if(x==-1){ printf("Nothing to be displayed\n"); } int i; for(i=0;i<=x;i++){ printf("\nBook Name : %s",p->book_name[i]); printf("\nBook ID : %d",p->book_id[i]); printf("\nBook Price : %d",p->book_price[i]); printf("\n"); } } int main(){ printf("********************************\t\n"); printf("Enter stack size : "); scanf("%d",&size); p = (struct stack*)malloc(sizeof(struct stack)); p->top = -1; while(1){ printf("\n1.Push\n2.Pop\n3.Peep\n4.Display all elements\n5.Exit\n"); int ch; scanf("%d",&ch); if(ch==1){ //p->top = p->top + 1; push(); } else if(ch==2){ pop(); } else if(ch==3){ peep(); } else if(ch==4){ print(); } else{ break; } } } ================================================ FILE: Data Structures/C:C++/Graph/FloydWarshall.cpp ================================================ //Floyd Warshall Algorithm for All Pair Shortest Path Problem #include #define FOR(i,n) for(size_t i=0;i>v>>e; FOR(i,v){ FOR(j,v) { if(i!=j) floyd_warshall[i][j] = 99999999; else floyd_warshall[i][j] = 0; } } FOR(i,e){ cin>>a>>b>>weight; floyd_warshall[a][b] = weight; } FOR(k,v){ FOR(i,v){ FOR(j,v){ temp = floyd_warshall[i][k] + floyd_warshall[k][j]; if(temp < floyd_warshall[i][j]) floyd_warshall[i][j] = temp; } } } cout< #include #include "../queue/queue.hpp" using namespace std; template class graph_al { private: int count; map< int, vector > connections; vector vertices; bool *visited; public: graph_al(T vertices[], int count) : count(count), visited(new bool[count]) { for(int i=0;ivertices.push_back(vertices[i]); } } void connect(int i, int j){ connections[i].push_back(j); } void connect_both_sides(int i, int j){ connect(i, j); connect(j, i); } bool contains(vector v, int n){ return find(v.begin(), v.end(), n) != v.end(); } bool bfs(int i, int j){ queuemp *q = new queuemp(); // else, try seraching though the connections for(int w=0;wcount;w++) visited[w] = false; q->push(i); visited[i] = true; while(q->size){ int v = q->pop(); for(int w = 0; w < connections[v].size();w++){ if(!visited[connections[v][w]]){ if(connections[v][w] == j) return true; q->push(connections[v][w]); visited[connections[v][w]] = true; } } } return false; } void dfs(int i){ for(int j=0;j v = connections[i]; cout << "vertices connected to " << i << ":" << endl; for(int j=0;j #include "../queue/queue.hpp" using namespace std; template class graph_am { private: int count; bool **connections; T *vertices; bool *visited; public: graph_am(T vertices[], int count) : count(count), vertices(new T[count]), visited(new bool[count]) { connections = new bool*[count]; for(int i=0;ivertices[i] = vertices[i]; for(int j=0;j *q = new queuemp(); if(connections[i][j]) return true; // else, try seraching though the connections for(int w=0;wcount;w++) visited[w] = false; q->push(i); visited[i] = true; while(q->size){ int v = q->pop(); for(int w = 0; w < this->count; w++){ if(!visited[w] && connections[v][w]){ if(w == j) return true; q->push(w); visited[w] = true; } } } return false; } void dfs(int i){ for(int j=0;j 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 * */ import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.*; class BFS { private static final String INPUT_FILE_PATH = "input.txt"; private static final String OUTPUT_FILE_PATH = "output.txt"; private static final int INF = Integer.MAX_VALUE / 2; private static int begin; public static void main(String[] args) { int[][] matrix = readMatrixFromFile(); List way = bfs(matrix); printSolution(way); } private static int[][] readMatrixFromFile() { int[][] matrix = null; try (Scanner scanner = new Scanner(new FileInputStream(INPUT_FILE_PATH))) { int matrixSize = Integer.parseInt(scanner.nextLine()); matrix = new int[matrixSize][matrixSize]; for (int row = 0; row < matrixSize; row++) { String[] numbers = scanner.nextLine().split(" "); for (int col = 0; col < matrixSize; col++) { if (numbers[col].equals("INF")) { matrix[row][col] = INF; } else { matrix[row][col] = Integer.parseInt(numbers[col]); } } } begin = scanner.nextInt() - 1; } catch (IOException e) { e.printStackTrace(); } return matrix; } private static List bfs(int[][] matrix) { boolean[] used = new boolean[matrix.length]; List way = new ArrayList<>(); Queue queue = new LinkedList<>(); queue.offer(begin); while (!queue.isEmpty()) { int v = queue.poll(); used[v] = true; way.add(v + 1); for (int nv = 0; nv < matrix.length; nv++) { if (!used[nv] && matrix[v][nv] != INF) { queue.offer(nv); } } } return way; } private static void printSolution(List way) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH))) { writer.write(Integer.toString(way.get(0))); for (int i = 1; i < way.size(); i++) { writer.write(" -> " + way.get(i)); } } catch (IOException e) { e.printStackTrace(); } } } ================================================ FILE: Data Structures/C:C++/Graph/bfs_dfs/bfs/bfs.Py ================================================ # Program to print BFS traversal from a given source # vertex. BFS(int s) traverses vertices reachable # from s. from collections import defaultdict # This class represents a directed graph using adjacency # list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False]*(len(self.graph)) # Create a queue for BFS queue = [] # Mark the source node as visited and enqueue it queue.append(s) visited[s] = True while queue: # Dequeue a vertex from queue and print it s = queue.pop(0) print s, # Get all adjacent vertices of the dequeued # vertex s. If a adjacent has not been visited, # then mark it visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True # Driver code # Create a graph given in the above diagram g = Graph() g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 2) g.addEdge(2, 0) g.addEdge(2, 3) g.addEdge(3, 3) print "Following is Breadth First Traversal (starting from vertex 2)" g.BFS(2) # contributed by drunk-maester ================================================ FILE: Data Structures/C:C++/Graph/bfs_dfs/ques/graph_connected_components.cpp ================================================ #include #include using namespace std; vector adj[12]; bool visited[12]; void dfs(int s) { visited[s] = true; for(int i = 0;i < adj[s].size();++i) { if(visited[adj[s][i]] == false) dfs(adj[s][i]); } } void initialize() { for(int i = 0;i < 10;++i) visited[i] = false; } int main() { int nodes, edges, x, y, connectedComponents = 0; cin >> nodes; cin >> edges; for(int i = 0;i < edges;++i) { cin >> x >> y; adj[x].push_back(y); adj[y].push_back(x); } initialize(); for(int i = 1;i <= nodes;++i) { if(visited[i] == false) { dfs(i); connectedComponents++; } } cout << "Number of connected components: " << connectedComponents << endl; return 0; } ================================================ FILE: Data Structures/C:C++/Graph/bfs_dfs/ques/tbbfs.cpp ================================================ //http://www.spoj.com/problems/TDBFS/ #include #define dout if(debugg) cout<<" " using namespace std; int debugg = 1; class Node{ public: vector adj; int visited; Node(){ clear(); } void clear(){ visited = 0; adj.clear(); } }; void dfs_rec(vector &node,int a){ cout< &node,int a){ for(auto &i : node){ i.visited=0; } node[a].visited=1; dfs_rec(node,a); cout< &node,int a){ for(auto &i : node) i.visited=0; queue q; q.push(a); node[a].visited=1; while(!q.empty()){ int temp = q.front(); for(auto i : node[temp].adj){ if(node[i].visited==0){ node[i].visited=1; q.push(i); } } q.pop(); cout<>t; for(int x=1; x<=t; x++){ int n; cin>>n; vector node(n+1); for(int i=1; i<=n; i++){//insert adj nodes int m,faltu; cin>>faltu>>m; while(m--){ cin>>temp; node[i].adj.push_back(temp); } } cout<<"graph "<>a>>type; if(a==0)break; if(type) bfs(node,a); else dfs(node,a); } } } ================================================ FILE: Data Structures/C:C++/Graph/dijakstra/Dijkstra.java ================================================ import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Scanner; import java.util.Stack; /** * Input file example: * * 6 * INF 7 9 INF INF 14 * 7 INF 10 15 INF INF * 9 10 INF 11 INF 2 * INF 15 11 INF 6 INF * INF INF INF 6 INF 9 * 14 INF 2 INF 9 INF * 5 1 * * First line is number of elements inn graph * Next n-lines is graph * Last line is begin and end point * * Output file: * Way from 5 to 1: * 5 -> 6 -> 3 -> 1 * Length: 20 * */ public class Dijkstra { private static final String INPUT_FILE_PATH = "input.txt"; private static final String OUTPUT_FILE_PATH = "output.txt"; private static final int INF = Integer.MAX_VALUE / 2; private static int begin; private static int end; public static void main(String[] args) { int[][] matrix = readMatrixFromFile(); dijkstra(matrix); } private static int[][] readMatrixFromFile() { int[][] matrix = null; try (Scanner scanner = new Scanner(new FileInputStream(INPUT_FILE_PATH))) { int matrixSize = Integer.parseInt(scanner.nextLine()); matrix = new int[matrixSize][matrixSize]; for (int row = 0; row < matrixSize; row++) { String[] numbers = scanner.nextLine().split(" "); for (int col = 0; col < matrixSize; col++) { if (numbers[col].equals("INF")) { matrix[row][col] = INF; } else { matrix[row][col] = Integer.parseInt(numbers[col]); } } } begin = scanner.nextInt(); end = scanner.nextInt(); } catch (IOException e) { e.printStackTrace(); } return matrix; } private static void dijkstra(int[][] matrix) { boolean[] used = new boolean[matrix.length]; int[] dist = new int[matrix.length]; int[] way = new int[matrix.length]; begin -= 1; end -= 1; Arrays.fill(dist, INF); Arrays.fill(way, 0); dist[begin] = 0; while (true) { int v = -1; for (int nv = 0; nv < matrix.length; nv++) { if (!used[nv] && (v == -1 || dist[nv] < dist[v])) { v = nv; } } if (v == -1) { break; } used[v] = true; for (int nv = 0; nv < matrix.length; nv++) { if (!used[nv] && matrix[v][nv] + dist[v] < dist[nv]) { dist[nv] = matrix[v][nv] + dist[v]; way[nv] = v; } } } printSolution(way, dist); } private static void printSolution(int[] trip, int[] dist) { Stack stack = new Stack<>(); StringBuilder answer = new StringBuilder(); answer.append(String.format("Way from %d to %d:\n", begin + 1, end + 1)); int lastPoint = end; while (lastPoint != begin) { stack.push(lastPoint); lastPoint = trip[lastPoint]; } answer.append(begin + 1); while (!stack.isEmpty()) { answer.append(" -> ").append(stack.pop() + 1); } answer.append(String.format("\nLength: %d\n", dist[end])); try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH))) { writer.write(answer.toString()); } catch (IOException e) { e.printStackTrace(); } } } ================================================ FILE: Data Structures/C:C++/Graph/dijakstra/dist_from_source.cpp ================================================ //https://www.codechef.com/problems/BUG2K17B #include #define mp pair using namespace std; int debugg=0; class Node{ public: int dist; vector > next;//first contains city index .. second contains distance void clear(){ dist=INT_MAX; next.clear(); } } node[100002]; struct priority_fxn{ bool operator() (int a,int b){ return node[a].dist > node[b].dist; } }; void dijakstra(int source){ int n,d,temp; priority_queue,priority_fxn> q; //init queue node[source].dist=0; q.push(source); while(!q.empty()){ temp=q.top(); for(auto elem : node[temp].next){ n=elem.first; d=elem.second; if(node[n].dist > node[temp].dist + d){ node[n].dist = node[temp].dist + d; q.push(n); } } q.pop(); } } int main(){ int t,a,b,c,n,p; cin>>t; while(t--){ cin>>n>>p; for(int i=1;i<=n;i++) node[i].clear(); while(p--){ cin>>a>>b>>c; node[a].next.push_back(mp(b,c)); node[b].next.push_back(mp(a,c)); } dijakstra(1); if(node[n].dist==INT_MAX)cout<<"NONE"< #define ulli long long int #define ui unsigned int using namespace std; class Road{ public: int dist; int left; int right; Road(int l,int r,int d){ left=l; right=r; dist=d; } }; class Node{ public: ulli dist; vector linked; Node(){ dist=LLONG_MAX; } }; typedef pair&> node_info;//stores node index and vector reference struct priority_fxn{ bool operator() (node_info a,node_info b){ return a.second[a.first].dist > b.second[b.first].dist; } }; /* * set value of dist in each node relative to root * ct ==> vector of Nodes * root ==> source node */ void dijakstra(vector &ct,int root){ priority_queue,priority_fxn> pq;//priority queue int ind;//contains index ulli temp_dist; ct[root].dist=0; pq.push(node_info(root,ct)); while(!pq.empty()){ root = pq.top().first; pq.pop(); for(auto elem : ct[root].linked){ ind = elem.left==root ? elem.right : elem.left;//select other than root temp_dist = ct[root].dist + (ulli)elem.dist;//calculate temp_dist if(temp_dist < ct[ind].dist){ ct[ind].dist=temp_dist; pq.push(node_info(ind,ct)); } } } } int main() { int t=1,n,r,s,a,b; ulli d; cin>>t; while(t--) { cin>>n>>r>>s;//num of cities , roads , source vector city(n+1,Node()); for(int i=1;i<=r;i++){ cin>>a>>b>>d; city[a].linked.push_back(Road(a,b,d)); city[b].linked.push_back(Road(a,b,d)); } dijakstra(city,s); for(int i=1;i<=n;i++){ cout< #define ulli long long int #define dout if(debugg)cout<<" " using namespace std; typedef pair mp; typedef pair mpp; int debugg=0; class Node{ public: ulli dist; ulli weight; ulli parentx,parenty; vector > next; void clear(){ weight=0; dist=LONG_MAX; next.clear(); } Node(){ clear(); } void setparent(ulli px,ulli py){ parentx=px; parenty=py; } } node[5][100009]; struct priority_fxn{ bool operator() (mp a,mp b){ return node[a.first][a.second].dist > node[b.first][b.second].dist; } }; void dijakstra(ulli sx,ulli sy,ulli ex,ulli ey,ulli update){ priority_queue,priority_fxn> q; queue dist_sett;//so that i can again set dist as intmax; ulli d,n1,n2; mp temp; node[sx][sy].dist=0; node[sx][sy].setparent(sx,sy); q.push(mp(sx,sy)); dist_sett.push(mp(sx,sy)); while(!q.empty()){ n1=q.top().first; n2=q.top().second; if(n1==ex && n2==ey)break;//reached the point for(ulli i=0;i node[n1][n2].dist + d){ node[temp.first][temp.second].dist = node[n1][n2].dist + d; node[temp.first][temp.second].setparent(n1,n2); dist_sett.push(temp); q.push(temp); } } q.pop(); }//end while loop //set dist back to INT_MAX while(!dist_sett.empty()){ mp elem = dist_sett.front(); node[elem.first][elem.second].dist=LONG_MAX; dist_sett.pop(); } int n1_; while(n1!=sx || n2!=sy){ node[n1][n2].weight+=update; n1_=node[n1][n2].parentx; n2=node[n1][n2].parenty; n1=n1_; dout<>m>>n>>q; for(ulli i=1;i>d; node[i][j].next.push_back(mpp(mp(i+1,j),d)); node[i+1][j].next.push_back(mpp(mp(i,j),d)); } } for(ulli i=1;i<=m;i++){ for(ulli j=1;j>d; node[i][j].next.push_back(mpp(mp(i,j+1),d)); node[i][j+1].next.push_back(mpp(mp(i,j),d)); } } ulli sx,sy,ex,ey,update; while(q--){ cin>>type; if(type==1){ cin>>sx>>sy>>ex>>ey>>update; dijakstra(sx,sy,ex,ey,update); } else{ cin>>sx>>sy; cout< #define ulli long long int using namespace std; typedef pair mp; typedef pair mpp; class Node{ public: ulli dist; ulli weight; ulli parentx,parenty; vector > next; void clear(){ weight=0; dist=LONG_MAX; next.clear(); } Node(){ clear(); } void setparent(ulli px,ulli py){ parentx=px; parenty=py; } } node[5][100009]; struct priority_fxn{ bool operator() (mp a,mp b){ return node[a.first][a.second].dist > node[b.first][b.second].dist; } }; void update_weight(ulli l,ulli r,ulli update){ ulli a = min(r,l); ulli b = max(r,l); for(ulli i=a;i<=b;i++){ node[1][i].weight+=update; } } void dijakstra(ulli sx,ulli sy,ulli ex,ulli ey,ulli update){ priority_queue,priority_fxn> q; queue dist_sett;//so that i can again set dist as intmax; ulli d,n1,n2; mp temp; node[sx][sy].dist=0; node[sx][sy].setparent(sx,sy); q.push(mp(sx,sy)); dist_sett.push(mp(sx,sy)); while(!q.empty()){ n1=q.top().first; n2=q.top().second; if(n1==ex && n2==ey)break;//reached the point for(ulli i=0;i node[n1][n2].dist + d){ node[temp.first][temp.second].dist = node[n1][n2].dist + d; node[temp.first][temp.second].setparent(n1,n2); dist_sett.push(temp); q.push(temp); } } q.pop(); }//end while loop //set dist back to INT_MAX while(!dist_sett.empty()){ mp elem = dist_sett.front(); node[elem.first][elem.second].dist=LONG_MAX; dist_sett.pop(); } int n1_; while(n1!=sx || n2!=sy){ node[n1][n2].weight+=update; n1_=node[n1][n2].parentx; n2=node[n1][n2].parenty; n1=n1_; } node[n1][n2].weight+=update; } int main(){ ulli m,n,q,d,type; cin>>m>>n>>q; //make graph for(ulli i=1;i>d; node[i][j].next.push_back(mpp(mp(i+1,j),d)); node[i+1][j].next.push_back(mpp(mp(i,j),d)); } } for(ulli i=1;i<=m;i++){ for(ulli j=1;j>d; node[i][j].next.push_back(mpp(mp(i,j+1),d)); node[i][j+1].next.push_back(mpp(mp(i,j),d)); } } //querries ulli sx,sy,ex,ey,update; while(q--){ cin>>type; if(type==1){ cin>>sx>>sy>>ex>>ey>>update; if(m==1) update_weight(sy,ey,update); else dijakstra(sx,sy,ex,ey,update); } else{ cin>>sx>>sy; cout< #include #include // for pair, make_pair etc using namespace std; /* * Shortest path in Unweighted graph */ pair< vector, vector > unweighted_shortest_path(vector< vector > graph, int s){ vector distance(graph.size(), -1); vector path(graph.size()); queue q; int v, w; q.push(s); distance[s] = 0; while(!q.empty()) { v = q.front(); q.pop(); for(int k = 0; k < graph[v].size(); k++){ w = graph[v][k]; if(distance[w] == -1){ distance[w] = distance[v] + 1; path[w] = v; q.push(w); } } } return make_pair(distance, path); } ================================================ FILE: Data Structures/C:C++/Graph/topological_sort.hpp ================================================ #include #include #include using namespace std; // util function void _ts(int v, bool visited[], stack *st, vector< vector > graph){ visited[v] = true; // go to all verices adjacent to this one for(int w=0;wpush(v); } stack topological_sort(vector< vector > graph){ int vertices = graph.size(); stack st; // mark all vertices as not visited bool *visited = new bool[vertices]; for(int i=0;i st2; st2 = st; cout << "Printing graph after topological sort: " << endl; while(!st.empty()){ cout << st.top() << " "; st.pop(); } cout << endl; return st2; } ================================================ FILE: Data Structures/C:C++/Graph/tree/binarySearchTree/bsTree.cpp ================================================ // This a program to demonstrate insert in a binary tree through recursion it also keeps count of all child of a node and also deletes nodes by recursion. It is basically a spoj question orderset. #include using namespace std; #define mp make_pair #define FOR(i,n) for(int i=0;i=0; i--) #define lli long long int #define ulli unsigned long long int #define dout if(debug)cout<<" " int debug = 0; struct tree{ int data; int childcnt; tree *left; tree *right; }; tree *root = NULL; //This is the void insert(tree *curr, tree *node){ int sum = 0; if(node->data < curr->data){ if(curr -> left == NULL){ curr -> left = node; sum++; } else{ insert(curr -> left, node); sum += curr -> left -> childcnt + 1; } if(curr -> right != NULL){ sum += curr -> right -> childcnt + 1; } curr -> childcnt = sum; return; } else if(node->data > curr->data){ if(curr -> right == NULL){ curr -> right = node; sum++; } else{ insert(curr -> right, node); sum += curr -> right -> childcnt + 1; } if(curr -> left != NULL){ sum += curr -> left -> childcnt + 1; } curr -> childcnt = sum; return ; } } tree * minValueNode( tree *curr){ tree *current= curr; while(current -> left != NULL) current = current -> left; return current; } tree* deleteNode(tree *root, int key){ root -> childcnt--; if (root == NULL) return root; if (key < root -> data){ root -> left = deleteNode(root -> left, key); } else if (key > root -> data){ root -> right = deleteNode( root -> right, key); } else{ if (root -> left == NULL){ tree *temp = root -> right; free(root); return temp; } else if (root -> right == NULL){ tree *temp = root -> left; free(root); return temp; } tree *temp = minValueNode(root -> right); root -> data =temp -> data; root -> right = deleteNode(root -> right, temp -> data); } return root; } int Kpify(tree *curr, int pos, int target){ int count = pos + 1; if( curr -> left != NULL){ count += curr -> left -> childcnt + 1; if (target < count){ return Kpify(curr -> left, pos, target); } } if ( target == count ) { return curr -> data; } else if (target > count ) { return Kpify(curr -> right, count, target); } } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int Q; cin >> Q; set myset; while (Q--){ char type; cin >> type; int num; set :: iterator its; if (type == 'I'){ cin >> num; if (myset.find(num) == myset.end()) myset.insert(num); tree *n =new tree; n->left = NULL; n->right = NULL; n->data = num; n->childcnt = 0; if ( root == NULL){ root = n; } else{ insert(root, n); } } if (type == 'D'){ cin >> num; its = myset.find(num); if (its != myset.end()){ myset.erase(num); root = deleteNode(root, num); } } if (type == 'C'){ cin >> num; its = myset.lower_bound(num); cout << distance(myset.begin(), its) << endl; } if (type == 'K'){ cin >> num; if (num <= myset.size() ){ cout << Kpify(root, 0, num) << endl; } else cout << "invalid" << endl; } } return 0; } ================================================ FILE: Data Structures/C:C++/Linked List/Circular_LL.c ================================================ /* *********************** Author : Vivek Shah Question : Circular LL *********************** */ #include #include #include struct node { char name[100]; int roll; float cgpa; struct node* next; }; struct node* head; void display(); struct node* getNode(){ char name[100]; int roll; float cgpa; printf("Enter name to be inserted\n"); printf("Enter Roll to be inserted\n"); printf("Enter CGPA to be inserted\n"); scanf("%s",name); scanf("%d",&roll); scanf("%f",&cgpa); struct node* temp = (struct node*)malloc(sizeof(struct node)) ; strcpy(temp->name,name); temp->roll=roll; temp->cgpa=cgpa; temp->next=NULL; return temp; } int countNode(){ struct node* temp = head; int c = 0; if (head==NULL) { return 0; } do{ c++; temp = temp->next; }while(temp!=head); return c; } void insert_beg(){ struct node* temp = getNode(); temp->next = head; if (head==NULL) temp->next = temp; else{ struct node* tm = head; do{ tm = tm->next; }while(tm->next!=head); //traverse through entire list tm->next = temp; } head = temp; display(); } void insert_btw(){ printf("Enter the Node no. after wise Node is to be inserted\n"); int ch; scanf("%d",&ch); int count = 0; if (ch<=0 || ch>countNode()) { printf("INVALID NODE No.\n"); return; } else{ struct node* temp = getNode(); struct node* tempor = head; do{ count++; tempor = tempor->next; }while(tempor->next!=head && ch!=count); temp->next = tempor->next; tempor->next = temp; display(); } } void insert_end(){ struct node* temp = getNode(); if (head == NULL) { temp->next = temp; head = temp; } else{ struct node* t = head; do{ t = t->next; }while(t->next!=head); t->next = temp; } temp->next = head; display(); } void delete_beg(){ if (head==NULL) { printf("Nothing to Delete\n"); } else{ struct node* temp = head; do{ temp = temp->next; }while(temp->next!=head); head = head->next; temp->next = head; } } void delete_btw(){ printf("Enter the Node no. to be deleted\n"); int ch; scanf("%d",&ch); int count = 0; if (ch<=0 || ch>countNode()) { printf("INVALID NODE No.\n"); return; } else{ int c=0; struct node* tempor = head; do{ c++; tempor = tempor->next; }while(tempor->next!=head && c==ch-1); if (tempor->next==head && ch==countNode()) { tempor->next=head; } else{ tempor->next = tempor->next->next; } } } void delete_end(){ if (head==NULL)printf("Nothing to Delete\n"); else if(head->next==NULL)head=NULL; else{ struct node* temp = head; do{ temp = temp->next; }while(temp->next->next!=head); temp->next = head; } } void search(){ int sc; printf("Enter a roll no to be Searched\n"); scanf("%d",&sc); if (head==NULL) { printf("No data to search\n"); return; } else{ struct node* temp = head; int f=0; do{ if(temp->roll==sc){f=1;break;} temp = temp->next; }while(temp!=head); if(f==0)printf("No data found\n"); else{ printf("FOUND THE DATA\n"); printf("\n%s\n%d\n%f\n",temp->name,temp->roll,temp->cgpa); } } } void display(){ if(head==NULL){printf("Nothing to display\n");return;} struct node* temp = head; do{ printf("\n************************************************\n"); printf("Name : %s\n",temp->name); printf("Roll No : %d\n",temp->roll); printf("CGPA : %f\n",temp->cgpa); temp = temp->next; }while(temp!=head); printf("\n************************************************\n\n"); } int main() { head = NULL; int i,ch; while(1){ printf("1.Insert\n2.Delete\n3.Search\n4.Display\n"); scanf("%d",&i); if (i==1) { printf("1.Insert Begin\n2.Insert Between\n3.Insert End\n"); scanf("%d",&ch); if (ch==1) insert_beg(); else if (ch==2) insert_btw(); else if(ch==3) insert_end(); else printf("Invalid Choice\n"); } else if (i==2) { printf("1.Delete Begin\n2.Delete Between\n3.Delete End\n"); scanf("%d",&ch); if (ch==1) delete_beg(); else if (ch==2) delete_btw(); else if(ch==3) delete_end(); else printf("Invalid Choice\n"); } else if(i==3){ search(); } else if(i==4){ display(); } else printf("Invalid Choice\n"); } return 0; } ================================================ FILE: Data Structures/C:C++/Linked List/Circular_ll.cpp ================================================ /* * C++ Program to Implement Circular Linked List */ #include #include #include using namespace std; /* * Node Declaration */ struct node { int info; struct node *next; }*last; /* * Class Declaration */ class circular_llist { public: void create_node(int value); void add_begin(int value); void add_after(int value, int position); void delete_element(int value); void search_element(int value); void display_list(); void update(); void sort(); circular_llist() { last = NULL; } }; /* * Main :contains menu */ int main() { int choice, element, position; circular_llist cl; while (1) { cout<>choice; switch(choice) { case 1: cout<<"Enter the element: "; cin>>element; cl.create_node(element); cout<>element; cl.add_begin(element); cout<>element; cout<<"Insert element after position: "; cin>>position; cl.add_after(element, position); cout<>element; cl.delete_element(element); cout<>element; cl.search_element(element); cout<info = value; if (last == NULL) { last = temp; temp->next = last; } else { temp->next = last->next; last->next = temp; last = temp; } } /* * Insertion of element at beginning */ void circular_llist::add_begin(int value) { if (last == NULL) { cout<<"First Create the list."<info = value; temp->next = last->next; last->next = temp; } /* * Insertion of element at a particular place */ void circular_llist::add_after(int value, int pos) { if (last == NULL) { cout<<"First Create the list."<next; for (int i = 0;i < pos-1;i++) { s = s->next; if (s == last->next) { cout<<"There are less than "; cout<next = s->next; temp->info = value; s->next = temp; /*Element inserted at the end*/ if (s == last) { last=temp; } } /* * Deletion of element from the list */ void circular_llist::delete_element(int value) { struct node *temp, *s; s = last->next; /* If List has only one element*/ if (last->next == last && last->info == value) { temp = last; last = NULL; free(temp); return; } if (s->info == value) /*First Element Deletion*/ { temp = s; last->next = s->next; free(temp); return; } while (s->next != last) { /*Deletion of Element in between*/ if (s->next->info == value) { temp = s->next; s->next = temp->next; free(temp); cout<<"Element "<next; } /*Deletion of last element*/ if (s->next->info == value) { temp = s->next; s->next = last->next; free(temp); last = s; return; } cout<<"Element "<next; while (s != last) { counter++; if (s->info == value) { cout<<"Element "<next; } if (s->info == value) { counter++; cout<<"Element "<next; cout<<"Circular Link List: "<info<<"->"; s = s->next; } cout<info<>pos; cout<<"Enter the new value: "; cin>>value; struct node *s; s = last->next; for (i = 0;i < pos - 1;i++) { if (s == last) { cout<<"There are less than "<next; } s->info = value; cout<<"Node Updated"<next; while (s != last) { ptr = s->next; while (ptr != last->next) { if (ptr != last->next) { if (s->info > ptr->info) { temp = s->info; s->info = ptr->info; ptr->info = temp; } } else { break; } ptr = ptr->next; } s = s->next; } } ================================================ FILE: Data Structures/C:C++/Linked List/Doubly LL.c ================================================ /* *********************** Author : Vivek Shah Question : Doubly LL *********************** */ #include #include #include struct node { char name[100]; int roll; float cgpa; struct node* next; struct node* pre; }; struct node* head; void display(); struct node* getNode(){ char name[100]; int roll; float cgpa; printf("Enter name to be inserted\n"); printf("Enter Roll to be inserted\n"); printf("Enter CGPA to be inserted\n"); scanf("%s",name); scanf("%d",&roll); scanf("%f",&cgpa); struct node* temp = (struct node*)malloc(sizeof(struct node)) ; strcpy(temp->name,name); temp->roll=roll; temp->cgpa=cgpa; temp->next = NULL; temp->pre = NULL; return temp; } int countNode(){ struct node* temp = head; int c = 0; if (head==NULL) { return 0; } while(temp!=NULL){ c++; temp = temp->next; } return c; } void insert_beg(){ struct node* temp = getNode(); temp->next = head; if(head!=NULL){ head->pre = temp; } head = temp; display(); } void insert_btw(){ printf("Enter the Node no. after wise Node is to be inserted\n"); int ch; scanf("%d",&ch); int count = 0; if (ch<=0 || ch>countNode()) { printf("INVALID NODE No.\n"); return; } else{ struct node* temp = getNode(); struct node* t = head; while(t!=NULL && t!=ch){ t=t->next; } temp->pre = t; temp->next = t->next; t->pre->next = temp; if(t->next!=NULL)t->next->pre = temp; display(); } } void insert_end(){ struct node* temp = getNode(); if (head == NULL) head = temp; else{ struct node* t = head; while(t->next!=NULL) t = t->next; t->next = temp; temp->pre = NULL; } display(); } void delete_beg(){ if (head==NULL) { printf("Nothing to Delete\n"); } else{ head=head->next; head->pre=NULL; } } void delete_btw(){ printf("Enter the Node no. to be deleted\n"); int ch; scanf("%d",&ch); int count = 0; if (ch<=0 || ch>countNode()) { printf("INVALID NODE No.\n"); return; } else{ if(ch==1){ head=NULL; return; } int c=0; struct node* t = head; int f=0; while(t!=NULL){ c++; if (c==ch) { f=1; break; } t = t->next; } if (f==0) { printf("NOT FOUND\n"); } else if (t->next!=NULL) { t->pre->next = t->next; t->next->pre = t->pre; } else{ t->pre->next = NULL; } } } void delete_end(){ if (head==NULL)printf("Nothing to Delete\n"); else if(head->next==NULL)head=NULL; else{ struct node* t = head; while(t->next->next!=NULL) t = t->next; t->next=NULL; } } void search(){ int sc; printf("Enter a roll no to be Searched\n"); scanf("%d",&sc); if (head==NULL) { printf("No data to search\n"); return; } else{ struct node* temp = head; int f=0; while(temp!=NULL){ if(temp->roll==sc){f=1;break;} temp = temp->next; } if(f==0)printf("No data found\n"); else{ printf("FOUND THE DATA\n"); printf("\n%s\n%d\n%f\n",temp->name,temp->roll,temp->cgpa); } } } void display(){ if(head==NULL){printf("Nothing to display\n");return;} struct node* temp = head; while(temp!=NULL){ printf("\n************************************************\n"); printf("Name : %s\n",temp->name); printf("Roll No : %d\n",temp->roll); printf("CGPA : %f\n",temp->cgpa); temp = temp->next; } printf("\n************************************************\n\n"); } int main() { head = NULL; int i,ch; while(1){ printf("1.Insert\n2.Delete\n3.Search\n4.Display\n"); scanf("%d",&i); if (i==1) { printf("1.Insert Begin\n2.Insert Between\n3.Insert End\n"); scanf("%d",&ch); if (ch==1) insert_beg(); else if (ch==2) insert_btw(); else if(ch==3) insert_end(); else printf("Invalid Choice\n"); } else if (i==2) { printf("1.Delete Begin\n2.Delete Between\n3.Delete End\n"); scanf("%d",&ch); if (ch==1) delete_beg(); else if (ch==2) delete_btw(); else if(ch==3) delete_end(); else printf("Invalid Choice\n"); } else if(i==3){ search(); } else if(i==4){ display(); } else printf("Invalid Choice\n"); } return 0; } ================================================ FILE: Data Structures/C:C++/Linked List/Insertion_Deletion_SinglyLL.c ================================================ #include struct node{ int item; struct node* next; }; struct node* head; void Insert(){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); int x; printf("\nEnter element to be inserted : "); scanf("%d",&x); printf("\n"); temp->item = x; temp->next = NULL; temp->next = head; head = temp; } void delete(){ int x; if(head==NULL){ printf("Nothing to be deleted\n"); return; } printf("Enter the position to be deleted : "); scanf("%d",&x);printf("\n"); if(head->next==NULL){//only a single element is present head=NULL; return; } struct node* temp; temp = head; int i; for(i=0;inext; }//came to n-1th node temp = temp->next->next; temp->next = NULL; } void Print(){ struct node* temp = head; while(temp!=NULL){ printf("%d ",temp->item); temp = temp->next; } printf("\n"); } int main(){ head = NULL; printf("Enter number of Items : "); int n; scanf("%d",&n); printf("\n"); int i; for(i=0;i #include struct Node { int data; struct Node* next; }; // Two glboal variables to store address of front and rear nodes. struct Node* front = NULL; struct Node* rear = NULL; // To Enqueue an integer void Enqueue(int x) { struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data =x; temp->next = NULL; if(front == NULL && rear == NULL){ front = rear = temp; return; } rear->next = temp; rear = temp; } // To Dequeue an integer. void Dequeue() { struct Node* temp = front; if(front == NULL) { printf("Queue is Empty\n"); return; } if(front == rear) { front = rear = NULL; } else { front = front->next; } free(temp); } int Front() { if(front == NULL) { printf("Queue is empty\n"); return; } return front->data; } void Print() { struct Node* temp = front; while(temp != NULL) { printf("%d ",temp->data); temp = temp->next; } printf("\n"); } int main(){ /* Drive code to test the implementation. */ // Printing elements in Queue after each Enqueue or Dequeue Enqueue(2); Print(); Enqueue(4); Print(); Enqueue(6); Print(); Dequeue(); Print(); Enqueue(8); Print(); } ================================================ FILE: Data Structures/C:C++/Linked List/Queue_using_linkedlist.c ================================================ #include //insert at beginning and remove at the end struct node{ int item; struct node* next; }; struct node* head; void push(){//insert at the beginning struct node* ptr = (struct node*)malloc(sizeof(struct node)); printf("Enter element to be inserted : "); scanf("%d",&ptr->item); ptr->next = NULL; if(head == NULL){ head = ptr; return; } ptr->next = head; head = ptr; } void pop(){ struct node* temp = head; if(head == NULL){ printf("Nothing to Pop\n"); return; } else if(head->next == NULL){ head = NULL; return; } while(temp->next->next!=NULL){ temp = temp->next; } temp->next = NULL; } void display(){ struct node* temp = head; if(temp==NULL){ printf("Nothing to display\n"); } while(temp!=NULL){ printf("%d ",temp->item); temp = temp->next; } printf("\n"); } int main(){ head = NULL; while(1){ printf("\n1.Push\n2.Pop\n3.Display\nAny other number to Exit\n\n"); printf("Enter your choice : "); int ch; scanf("%d",&ch); printf("\n"); if(ch==1){ push(); } else if(ch==2){ pop(); } else if(ch==3){ display(); } else{ break; } } } ================================================ FILE: Data Structures/C:C++/Linked List/Reverse_SinglyLL.c ================================================ #include struct node{ int item; struct node* next; }; struct node* head; struct node* reverse(){ struct node* pre; struct node* current; struct node* post; current = head; pre = NULL; while(current!=NULL){ post = current->next; current->next = pre; pre = current; current = post; } head = pre; return head; } void insert(int item,int n){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); temp->item = item; temp->next = NULL; if(n==1){ temp->next = head; head = temp; return; } struct node* temp1; temp1 = head; int i; for( i = 0;inext; } temp->next = temp1->next; temp1->next = temp; } void print(){ struct node* temp = head; while(temp!=NULL){ printf("%d ",temp->item); temp = temp->next; } printf("\n"); } int main(){ head = NULL; insert(8,1); insert(51,2); insert(21,3); print(); reverse(); print(); } ================================================ FILE: Data Structures/C:C++/Linked List/all_operations_of_Doubly_ll.cpp ================================================ /* * C++ Program to Implement Doubly Linked List */ #include #include #include /* * Node Declaration */ using namespace std; struct node { int info; struct node *next; struct node *prev; }*start; /* Class Declaration */ class double_llist { public: void create_list(int value); void add_begin(int value); void add_after(int value, int position); void delete_element(int value); void search_element(int value); void display_dlist(); void count(); void reverse(); double_llist() { start = NULL; } }; /* * Main: Conatins Menu */ int main() { int choice, element, position; double_llist dl; while (1) { cout<>choice; switch ( choice ) { case 1: cout<<"Enter the element: "; cin>>element; dl.create_list(element); cout<>element; dl.add_begin(element); cout<>element; cout<<"Insert Element after postion: "; cin>>position; dl.add_after(element, position); cout<>element; dl.delete_element(element); cout<info = value; temp->next = NULL; if (start == NULL) { temp->prev = NULL; start = temp; } else { s = start; while (s->next != NULL) s = s->next; s->next = temp; temp->prev = s; } } /* * Insertion at the beginning */ void double_llist::add_begin(int value) { if (start == NULL) { cout<<"First Create the list."<prev = NULL; temp->info = value; temp->next = start; start->prev = temp; start = temp; cout<<"Element Inserted"<next; if (q == NULL) { cout<<"There are less than "; cout<info = value; if (q->next == NULL) { q->next = tmp; tmp->next = NULL; tmp->prev = q; } else { tmp->next = q->next; tmp->next->prev = tmp; q->next = tmp; tmp->prev = q; } cout<<"Element Inserted"<info == value) { tmp = start; start = start->next; start->prev = NULL; cout<<"Element Deleted"<next->next != NULL) { /*Element deleted in between*/ if (q->next->info == value) { tmp = q->next; q->next = tmp->next; tmp->next->prev = q; cout<<"Element Deleted"<next; } /*last element deleted*/ if (q->next->info == value) { tmp = q->next; free(tmp); q->next = NULL; cout<<"Element Deleted"<info<<" <-> "; q = q->next; } cout<<"NULL"<next; cnt++; } cout<<"Number of elements are: "<next; p1->next = NULL; p1->prev = p2; while (p2 != NULL) { p2->prev = p2->next; p2->next = p1; p1 = p2; p2 = p2->prev; } start = p1; cout<<"List Reversed"< #include #include struct node { int data; struct node *next; }; struct node*p=NULL; struct node*q=NULL; int j=0,k=0; struct node* create(struct node*current) { struct node *new_node; new_node=(struct node *)malloc(sizeof(struct node)); printf("\nEnter the data : "); scanf("%d",&new_node->data); new_node->next=NULL; j=j+1; if(p==NULL) { p=new_node; current=new_node; } else { current->next=new_node; current=new_node; } return current; } struct node* create2(struct node*current) { struct node *new_node; new_node=(struct node *)malloc(sizeof(struct node)); printf("\nEnter the data : "); scanf("%d",&new_node->data); new_node->next=NULL; k=k+1; if(q==NULL) { q=new_node; current=new_node; } else { current->next=new_node; current=new_node; } return current; } void display(struct node*start) { struct node *new_node; printf("\nThe Linked List : \n"); new_node=start; while(new_node!=NULL) { printf("%d--->",new_node->data); new_node=new_node->next; } printf("NULL"); } struct node* sort(struct node*s) { int i; struct node *temp; for(i=0;inext!=NULL) { if(s->data>s->next->data) { temp->data=s->data; s->data=s->next->data; s->next->data=temp->data; } s=s->next; } } } void con(struct node*p,struct node*q) { while(p->next!=NULL) p=p->next; p->next=q; } main() { int n; struct node* current1,*current2; current1=NULL; current2=NULL; while(1) { printf("1.insert list 1\n2.insert list 2\n3.display list 1\n4.display list 2\n5.sort\n6.display final list\n7.concatinate\n8.exit \nenter choice\n"); scanf("%d",&n); switch(n){ case 1: current1=create(current1); //p=current; break; case 2: current2=create2(current2); //q=current; break; case 3: display(p); break; case 4:display(q); break; case 5:sort(p); break; case 6: display(p); break; case 7:con(p,q); break; case 8: return; } } } ================================================ FILE: Data Structures/C:C++/Linked List/doubly circular.c ================================================ /* *********************** Author : Vivek Shah Question : Doubly Circular LL *********************** */ #include #include #include struct node { char name[100]; int roll; float cgpa; struct node* next; struct node* pre; }; struct node* head; struct node* last; void display(); struct node* getNode(){ char name[100]; int roll; float cgpa; printf("Enter name to be inserted\n"); printf("Enter Roll to be inserted\n"); printf("Enter CGPA to be inserted\n"); scanf("%s",name); scanf("%d",&roll); scanf("%f",&cgpa); struct node* temp = (struct node*)malloc(sizeof(struct node)) ; strcpy(temp->name,name); temp->roll=roll; temp->cgpa=cgpa; temp->next = NULL; temp->pre = NULL; return temp; } int countNode(){ struct node* temp = head; int c = 0; if (head==NULL) { return 0; } do{ c++; temp = temp->next; }while(temp!=head); return c; } void insert_beg(){ struct node* temp = getNode(); if (head==NULL) { temp->next=temp; temp->pre=temp; } else{ temp->next=head; head->pre = temp; temp->pre = last; last->next=temp; } head = temp; last = head->pre; /*struct node* temp = getNode(); temp->next = head; struct node* last = head->pre; struct node* new_node = getNode(); new_node->next = head; new_node->pre = last; last->next = head->pre = new_node; head = new_node;*/ display(); } void insert_btw(){//problem hai... printf("Enter the Node no. after wise Node is to be inserted\n"); int ch; scanf("%d",&ch); printf("The total count of nodes is %d",countNode()); int count = 0; if (ch<=0 || ch>countNode()) { printf("INVALID NODE No.\n"); return; } struct node* temp = getNode(); struct node* t = head; do{ count++; t=t->next; }while(t!=head || count!=ch-1); /* printf("The value of count is %d",count); printf("\n************************************************\n"); printf("Name : %s\n",t->name); printf("Roll No : %d\n",t->roll); printf("CGPA : %f\n",t->cgpa); */ temp->pre = t; temp->next = t->next; if(t==last){ temp->next=head; last=temp; } else t->next->pre = temp; t->next = temp; display(); } void insert_end(){ struct node* temp = getNode(); if (head == NULL){ temp->next=temp; temp->pre=temp; head = temp; last = head->pre; } else{ temp->next=last->next; temp->pre = last; last->next = temp; last = temp; last->next = head; } display(); } void delete_beg(){ if (head==NULL) { printf("Nothing to Delete\n"); } else if (head==last) { head=NULL; last=NULL; } else{ head=head->next; head->pre=NULL; last->next=head; } display(); } void delete_btw(){ printf("Enter the Node no. to be deleted\n"); int ch; scanf("%d",&ch); int count = 0; if (ch<=0 || ch>countNode()) { printf("INVALID NODE No.\n"); return; } else{ if(ch==1){ head=NULL; last=NULL; return; } int c=0; struct node* t = head; int f=0; while(t!=NULL){ c++; if (c==ch) { f=1; break; } t = t->next; } if (f==0) { printf("NOT FOUND\n"); } if (t==last) { last = last->pre; last->next=head; } else { t->pre->next = t->next; t->next->pre = t->pre; } } display(); } void delete_end(){ if (last==NULL)printf("Nothing to Delete\n"); else if(head==last){ head=NULL; last=NULL; } else{ last = last->pre; last->next = head; } display(); } void search(){ int sc; printf("Enter a roll no to be Searched\n"); scanf("%d",&sc); if (head==NULL) { printf("No data to search\n"); return; } else{ struct node* temp = head; int f=0; do{ if(temp->roll==sc){f=1;break;} temp = temp->next; }while(temp!=head); if(f==0)printf("No data found\n"); else{ printf("FOUND THE DATA\n"); printf("\n%s\n%d\n%f\n",temp->name,temp->roll,temp->cgpa); } } } void display(){ if(head==NULL){printf("Nothing to display\n");return;} struct node* temp = head; do{ printf("\n************************************************\n"); printf("Name : %s\n",temp->name); printf("Roll No : %d\n",temp->roll); printf("CGPA : %f\n",temp->cgpa); temp = temp->next; }while(temp!=head); printf("\n************************************************\n\n"); } int main() { head = NULL; last = NULL; int i,ch; while(1){ printf("1.Insert\n2.Delete\n3.Search\n4.Display\n"); scanf("%d",&i); if (i==1) { printf("1.Insert Begin\n2.Insert Between\n3.Insert End\n"); scanf("%d",&ch); if (ch==1) insert_beg(); else if (ch==2) insert_btw(); else if(ch==3) insert_end(); else printf("Invalid Choice\n"); } else if (i==2) { printf("1.Delete Begin\n2.Delete Between\n3.Delete End\n"); scanf("%d",&ch); if (ch==1) delete_beg(); else if (ch==2) delete_btw(); else if(ch==3) delete_end(); else printf("Invalid Choice\n"); } else if(i==3){ search(); } else if(i==4){ display(); } else printf("Invalid Choice\n"); } return 0; } ================================================ FILE: Data Structures/C:C++/Linked List/doubly linked list.c ================================================ #include struct node{ int item; struct node* pre; struct node* next; }; struct node *head, *ptr; struct node* getNode(){ ptr = (struct node*)malloc(sizeof(struct node)); printf("Enter element to be inserted in Doubly Linked List : "); int x; scanf("%d",&x); ptr->item = x; ptr->pre = NULL; ptr->next = NULL; return ptr; } void insert(){ struct node* ptr = getNode(); ptr->next = head; if(head == NULL){ head = ptr; return; } head->pre = ptr; head = ptr; } void insert1(){ struct node* ptr = getNode(); if(head==NULL){ head = ptr; return; } struct node* temp; temp=head; while(temp->next!=NULL){ temp = temp->next; }//temp is last element temp->next = ptr; ptr->pre = temp; ptr->next = NULL; } void print(){ struct node* temp; temp = head; while(temp!=NULL){ printf("%d ",temp->item); temp = temp->next; } } int main(){ head = NULL; insert();//insert inserts at beginning insert(); insert1();//insert1 inserts at end insert1(); print(); } ================================================ FILE: Data Structures/C:C++/Linked List/linked_list.c ================================================ #include #include #include struct node { int roll; char name[100]; float cgpa; struct node* next; }; struct node* head; struct node* getNode(int roll1,char name1[], float cgpa1){ struct node* p = (struct node*)malloc(sizeof(struct node)); p->roll=roll1; strcpy(p->name,name1); p->cgpa=cgpa1; return p; } struct node* getLastNode(){ struct node* temp = head; while(temp->next!=NULL) temp=temp->next; return temp; } int countNode(){ struct node* temp = head; int count=0; while(temp!=NULL){ count++; temp = temp->next; } return count; } void ins_beg(int roll,char name[], float cgpa){ struct node* p =getNode(roll,name,cgpa); p->next = head; head = p; } void ins_btw(int roll,char name[], float cgpa,int pos){ if (pos>0 && pos<=countNode()) { struct node* temp = head; int count=0; while(count!=(pos-1)){ temp = temp->next; } struct node* p = getNode(roll,name,cgpa); p->next = temp->next; temp->next=p; } else{ printf("INVALID POSITIONS\n"); } } void ins_end(int roll,char name[], float cgpa){ struct node* p =getNode(roll,name,cgpa); if (head==NULL)//list is empty { head=p; } else{ struct node* temp = head; while(temp->next!=NULL) temp=temp->next; temp->next = p; } } void del_beg(){ if(head==NULL)printf("NOTHING TO BE DELETED\n"); else{ head = head->next; } } void del_btw(int pos){ if (pos>0 && pos<=countNode()) { struct node* temp = head; int count=0; while(count!=(pos-1)){ temp = temp->next; } temp->next=temp->next->next; } else{ printf("INVALID POSITIONS\n"); } } void del_end(){ if(head==NULL)printf("NOTHING TO BE DELETED\n"); else if(head->next==NULL)head=NULL; else{ struct node* temp = head; while(temp->next->next!=NULL)temp = temp->next; temp->next = NULL; } } void search(int roll){ struct node* temp = head; int count=1,flag=0; while(temp!=NULL){ if(temp->roll==roll){ printf("POSITION at %d\n",count); printf("FOLLOWING DATA OF ROLL NO. :\n"); printf("ROLL NO. : %d\nNAME : %s\nCGPA : %f\n\n",temp->roll,temp->name,temp->cgpa); flag=1; break; } ++count; temp = temp->next; } if(flag==0)printf("NOT FOUND\n"); } void DISPLAY(){ struct node* temp = head; if(temp==NULL)printf("NOTHING TO DISPLAY\n"); else{ while(temp!=NULL){ printf("ROLL NO: %d\nNAME: %s\nCGPA:%f\n\n",temp->roll,temp->name,temp->cgpa); temp=temp->next; } } } int main() { head = NULL; while(1){ printf("1.INSERT : \n2.DELETE : \n3.SEARCH : \n4.DISPLAY : \n"); int ch; scanf("%d",&ch); if (ch==1) { int ch1; printf("1.INSERT at BEGINNING: \n2.INSERT at END: \n3.INSERT at BETWEEN:\n"); scanf("%d",&ch1); int roll; char name[100]; float cgpa; printf("Enter UNIQUE ROLL NO. to be inserted\n"); scanf("%d",&roll); printf("Enter NAME to be inserted\n"); gets(name); printf("Enter CGPA to be inerted\n"); scanf("%f",&cgpa); if (ch1==1) { ins_beg(roll,name,cgpa); } else if (ch1==2) { ins_end(roll,name,cgpa); } else if (ch1==3) { printf("Enter the POSITION where node is to be inserted\n"); int k; scanf("%d",&k); ins_btw(roll,name,cgpa,k); } else printf("INVALID INPUT\n"); } else if(ch==2){ int ch1; printf("1.DELETE at BEGINNING: \n2.DELETE at END: \n3.DELETE at BETWEEN:\n"); scanf("%d",&ch1); if(ch1==1){ del_beg(); } else if(ch1==2){ del_end(); } else if(ch1==3){ printf("Enter the POSITION at which node is to be DELETED\n"); int k; del_btw(scanf("%d",&k)); } else printf("INVALID POSITION"); } else if(ch==3){ int roll; printf("Enter UNIQUE ROLL NO. to be searched\n"); scanf("%d",&roll); search(roll); } else if(ch==4)DISPLAY(); else {printf("INVALID INPUT\n");break;} } return 0; } ================================================ FILE: Data Structures/C:C++/Linked List/ordered_linked.c ================================================ #include #include #include struct node { int roll; char name[100]; float cgpa; struct node* next; }; struct node* head; struct node* getNode(int roll1,char name1[], float cgpa1){ struct node* p = (struct node*)malloc(sizeof(struct node)); p->roll=roll1; strcpy(p->name,name1); p->cgpa=cgpa1; p->next=NULL; return p; } struct node* getLastNode(){ struct node* temp = head; while(temp->next!=NULL) temp=temp->next; return temp; } int countNode(){ struct node* temp = head; int count=0; while(temp!=NULL){ count++; temp = temp->next; } return count; } void insert(int roll,char name[], float cgpa){ struct node* p =getNode(roll,name,cgpa); if(head==NULL){ head = p; } else if(head->roll > roll){ p->next=head; head=p; } else{ struct node* temp = head; struct node* pre = NULL; while(temp->roll < roll && temp!=NULL){ pre = temp; temp=temp->next; } p->next = temp; pre->next = p; } } /*void ins_beg(int roll,char name[], float cgpa){ struct node* p =getNode(roll,name,cgpa); p->next = head; head = p; } void ins_btw(int roll,char name[], float cgpa,int pos){ if (pos>0 && pos<=countNode()) { struct node* temp = head; int count=0; while(count!=(pos-1)){ temp = temp->next; } struct node* p = getNode(roll,name,cgpa); p->next = temp->next; temp->next=p; } else{ printf("INVALID POSITIONS\n"); } } void ins_end(int roll,char name[], float cgpa){ struct node* p =getNode(roll,name,cgpa); if (head==NULL)//list is empty { head=p; } else{ struct node* temp = head; while(temp->next!=NULL) temp=temp->next; temp->next = p; } }*/ void del_beg(){ if(head==NULL)printf("NOTHING TO BE DELETED\n"); else head = head->next; } void del_btw(int pos){ if (pos>0 && pos<=countNode()) { struct node* temp = head; int count=0; while(count!=(pos-1)){ temp = temp->next; } temp->next=temp->next->next; } else printf("INVALID POSITIONS\n"); } void del_end(){ if(head==NULL)printf("NOTHING TO BE DELETED\n"); else if(head->next==NULL)head=NULL; else{ struct node* temp = head; while(temp->next->next!=NULL)temp = temp->next; temp->next = NULL; } } void search(int roll){ struct node* temp = head; int count=1,flag=0; while(temp!=NULL){ if(temp->roll==roll){ printf("POSITION at %d\n",count); printf("FOLLOWING DATA OF ROLL NO. :\n"); printf("ROLL NO. : %d\nNAME : %s\nCGPA : %f\n\n",temp->roll,temp->name,temp->cgpa); flag=1; break; } temp = temp->next; ++count; } if(flag==0)printf("NOT FOUND\n"); } void DISPLAY(){ struct node* temp = head; if(temp==NULL)printf("NOTHING TO DISPLAY\n"); else{ while(temp!=NULL){ printf("ROLL NO: %d\nNAME: %s\nCGPA:%f\n\n",temp->roll,temp->name,temp->cgpa); temp=temp->next; } } } int main() { head = NULL; while(1){ printf("1.INSERT : \n2.DELETE : \n3.SEARCH : \n4.DISPLAY : \n"); int ch; scanf("%d",&ch); if (ch==1) { int roll; char name[100]; float cgpa; printf("Enter ROLL NO. to be inserted\n"); scanf("%d",&roll); printf("Enter NAME to be inserted\n"); gets(name); printf("Enter CGPA to be inerted\n"); scanf("%f",&cgpa); insert(roll,name,cgpa); } else if(ch==2){ int ch1; printf("1.DELETE at BEGINNING: \n2.DELETE at END: \n3.DELETE at BETWEEN:\n"); scanf("%d",&ch1); if(ch1==1){ del_beg(); } else if(ch1==2){ del_end(); } else if(ch1==3){ printf("Enter the POSITION at which node is to be DELETED\n"); int k; del_btw(scanf("%d",&k)); } else printf("INVALID INPUT"); } else if(ch==3){ int roll; printf("Enter ROLL NO. to be searched\n"); scanf("%d",&roll); search(roll); } else if(ch==4)DISPLAY(); else {printf("INVALID INPUT\n");break;} } return 0; } ================================================ FILE: Data Structures/C:C++/Linked List/reverse.cpp ================================================ #include #include using namespace std; //structure of node struct node { int data; struct node *next; }*start=NULL; //function to create linked list struct node* create(struct node*current) { struct node *new_node;//pointer to node new_node=(struct node *)malloc(sizeof(struct node)); cout<<"\nEnter the data : "; cin>>new_node->data; new_node->next=NULL; if(start==NULL)//to check if the root node is null or not { start=new_node; current=new_node; } else { current->next=new_node; current=new_node; } return current; } //function to display linked list void display() { struct node *new_node; cout<<"\nThe Linked List : "<data<<"--->"; new_node=new_node->next; } cout<<"NULL"<next; curr->next=prev; prev=curr; curr=nextt; } start=prev; display(); } int main() { int n; struct node*current; current=NULL; while(1) { cout<<"1.to insert\n2.display\n3.reverse\n4.exit\nenter choice"<>n; switch(n) { case 1: current=create(current);//passing current pointer to create function break; case 2: display(); break; case 3:reverse(); break; case 4: return 0; } } return 0; } ================================================ FILE: Data Structures/C:C++/Linked List/stackLinkedList.cpp ================================================ #include struct node{ int item; struct node* next; }; struct node* head; int size; void insertathead(){ struct node* ptr; ptr = (struct node*)malloc(sizeof(struct node)); printf("Enter data : "); scanf("%d",&ptr->item); printf("\n"); ptr->next = NULL; if(head == NULL){ head = ptr; return; } ptr->next = head; head = ptr; } void pop(){ if(head==NULL){ printf("UnderFlow\n"); return; } if(head->next == NULL){ head=NULL; return; } struct node* temp; temp = head; head = head->next; temp->next = NULL; } void print(){ struct node* temp; temp = head; printf("List : "); while(temp!=NULL){ printf("%d ",temp->item); temp = temp->next; } printf("\n"); } int main(){ head=NULL; printf("Enter the size of array\n"); scanf("%d",&size); while(1){ printf("Enter choice\n1.Insert\n2.Pop\n3.Print\n"); int ch; scanf("%d",&ch); if(ch==1){ insertathead(); } else if(ch==2){ pop(); } else if(ch==3){ print(); } } } ================================================ FILE: Data Structures/C:C++/Linked List/stack_Linked_List.c ================================================ /*Implementation of stack using linked list */ /*Stack is a LIFO (Last In Fast Out Data Structure */ /* * push operation O(1) * pop operation O(1) * top operation O(1) * isEmpty operation O(1) */ #include #include struct node{ int item; struct node* next; }; struct stack{ struct node *tos; }; typedef struct node node; typedef struct stack stack; /*Function to create stack*/ stack* createStack(){ stack *temp=(stack*)malloc(sizeof(stack)); temp->tos=NULL; return temp; } /*Function to push in a stack */ void push(stack *s,int data){ node *temp=(node*)malloc(sizeof(node)); /*checking if the memory was allocated to temp*/ if(temp==NULL){ printf("OVERFLOW\n"); exit(0); } temp->item=data; if(s->tos==NULL){ s->tos=temp; temp->next=NULL; return; } else{ temp->next=s->tos; s->tos=temp; return; } } /*Function to pop an element from a stack */ int pop(stack *s){ node *temp; int valueToReturn; if(s->tos==NULL){ printf("UNDERFLOW\n"); exit(0); } else{ temp=s->tos; s->tos=temp->next; valueToReturn=temp->item; free(temp); return valueToReturn; } } /*function to check wheather the stack is empty */ int isEmpty(stack *s){ return s->tos==NULL; } /*Functiont that returns the top of the stack */ int top(stack *s){ if(!isEmpty(s)) return s->tos->item; else return -1; } int main(){ stack *s=createStack(); int temp,ch,cont; do{ printf("Enter choice\t1.Push\t2.Pop\t3.top :"); scanf("%d",&ch); switch(ch){ case 1: printf("Enter value :"); scanf("%d",&temp); push(s,temp); break; case 2: printf("%d popped \n",pop(s)); break; case 3: printf("top : %d\n",top(s)); break; } printf("\nContinue (1/0)\n"); scanf("%d",&cont); }while(cont != 0); return 0; } ================================================ FILE: Data Structures/C:C++/Stack/Balanced_Brackets.cpp ================================================ /*This program checks whether an entered string is Bracket Balanced ot not.By Bracket balanced we mean a opening bracket ('(','{','[') to be complemented by a closing bracket (')','}',']'). Time Complexity :O(n) Auxiliary Space :O(n) Similar quesion(s) for practice :https://www.hackerrank.com/challenges/balanced-brackets/problem */ #include using namespace std; int main() { string str; getline(cin,str); stack s; char a,b,c; int flag=1; for(int i=0;i */ using namespace std; void Print(queue& Queue) { while (!Queue.empty()) { cout << Queue.front() << " "; Queue.pop(); } } // Function to reverse the queue void reverseQueue(queue& Queue) { stack Stack; while (!Queue.empty()) { Stack.push(Queue.front()); Queue.pop(); } while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); } } // Main Function int main() { queue Queue; Queue.push(1); Queue.push(2); Queue.push(3); Queue.push(4); Queue.push(5); Queue.push(6); Queue.push(7); Queue.push(8); Queue.push(9); Queue.push(10); reverseQueue(Queue); Print(Queue); } ================================================ FILE: Data Structures/C:C++/Stack/Stack_as_linked_list.cpp ================================================ C++ Program to implement Stack using Linked List: #include using namespace std; // Creating a NODE Structure struct node { int data; struct node *next; }; // Creating a class STACK class stack { struct node *top; public: stack() // constructure { top=NULL; } void push(); // to insert an element void pop(); // to delete an element void show(); // to show the stack }; // PUSH Operation void stack::push() { int value; struct node *ptr; cout<<"\nPUSH Operationn"; cout<<"Enter a number to insert: "; cin>>value; ptr=new node; ptr->data=value; ptr->next=NULL; if(top!=NULL) ptr->next=top; top=ptr; cout<<"\nNew item is inserted to the stack!!!"; } // POP Operation void stack::pop() { struct node *temp; if(top==NULL) { cout<<"\nThe stack is empty!!!"; } temp=top; top=top->next; cout<<"\nPOP Operation........\nPoped value is "<data; delete temp; } // Show stack void stack::show() { struct node *ptr1=top; cout<<"\nThe stack is\n"; while(ptr1!=NULL) { cout<data<<" ->"; ptr1=ptr1->next; } cout<<"NULL\n"; } // Main function int main() { stack s; int choice; while(1) { cout<<"\n-----------------------------------------------------------"; cout<<"\n\t\tSTACK USING LINKED LIST\n\n"; cout<<"1:PUSH\n2:POP\n3:DISPLAY STACK\n4:EXIT"; cout<<"\nEnter your choice(1-4): "; cin>>choice; switch(choice) { case 1: s.push(); break; case 2: s.pop(); break; case 3: s.show(); break; case 4: return 0; break; default: cout<<"\nPlease enter correct choice(1-4)!!"; break; } } return 0; } ================================================ FILE: Data Structures/C:C++/Stack/largestRectangleHistogram.cpp ================================================ #include #include #include using namespace std; int main() { int n; int a[]={6,2,5,4,5,1,6}; //input array n = sizeof(a)/sizeof(a[0]); int i,q; stack s; // stack to calculate max area i=0; int area,maxarea=INT_MIN; while(i using namespace std; int main(){ int n; cin>>n; int a[n]; int ans[n]; for(int i=0;i>a[i]; } stack s; for(int i=0;ia[s.top()]){ ans[s.top()]=a[i]; s.pop(); } s.push(i); } for(int i=0;i #include "../linked_list/ll.hpp" using namespace std; template struct stackmp{ ll_node *top; int capacity; // number of elements the stack can contain int size; // number of elements in the stack stackmp(int cap) : capacity(cap),size(0) {} void push(T new_data){ if(size == capacity){ cout << "Stack is full! Cannot push new element" << endl; return; } ll_node *new_node = create_node(new_data); ll_node *temp_node = this->top; new_node->next = temp_node; this->top = new_node; // here "this" pointer is used to access the current class's object's parameters size++; } void print(){ ll_node *temp_node = this->top; if(size == 0){ cout << "Stack is empty" << endl; return; } cout << "Printing stack:" << endl; for(int i=0;isize;i++){ cout << temp_node->data << ' '; temp_node = temp_node->next; } cout << endl; } T pop(){ if(size == 0){ cout << "Stack is empty, can't pop" << endl; return '\0'; } T data = this->top->data; this->top = this->top->next; size--; return data; } T peek(){ return this->top->data; } }; template int get_size(stackmp *s){ return s->size; } template int get_capacity(stackmp *s){ return s->capacity; } ================================================ FILE: Data Structures/C:C++/Trees/segment_tree/segment_tree.cpp ================================================ #include using namespace std; void createMinSegmentTree(int arr[],int sg[],int index,int begin,int end){ //create the segment tree. if(begin == end){ sg[index] = arr[begin]; return; } int mid = (begin+end)/2; createMinSegmentTree(arr,sg,2*index,begin,mid); createMinSegmentTree(arr,sg,2*index+1,mid+1,end); sg[index] = min(sg[2*index],sg[2*index+1]); return; } int queryMinSegmentTree(int sg[],int l,int r,int index,int begin,int end){ //querying the segment tree //complete overlap if(l <= begin && r >= end){ return sg[index]; } //no overlap else if(r end){ return INT_MAX; } //partial overlap else{ int mid = (begin+end)/2; return min(queryMinSegmentTree(sg,l,r,2*index,begin,mid),queryMinSegmentTree(sg,l,r,2*index+1,mid+1,end)); } } void updateMinSegmentTree(int sg[],int l,int r,int index,int begin,int end,int update){ if(begin == end && begin>=l && begin<=r){ sg[index]+=update; return; } if(l>end || r> n; int arr[n]; for(int i=0;i> q; int l,r,option; while(q--){ cin >> option; //option 1 to query the segment tree with range [l,r]. if(option == 1){ cin >> l >> r; cout << queryMinSegmentTree(sg,l,r,1,0,n-1)<> l >> r >> update; updateMinSegmentTree(sg,l,r,1,0,n-1,update); } } return 0; } ================================================ FILE: Data Structures/C:C++/Trees/segment_tree/segment_trees_lazy.cpp.cpp ================================================ /** * In this code we have a very large array called arr, and very large set of operations * Operation #1: Increment the elements within range [i, j] with value val * Operation #2: Get max element within range [i, j] * Build tree: build_tree(1, 0, N-1) * Update tree: update_tree(1, 0, N-1, i, j, value) * Query tree: query_tree(1, 0, N-1, i, j) * Actual space required by the tree = 2*2^ceil(log_2(n)) - 1 */ #include #include using namespace std; #include #include #define N 20 #define MAX (1+(1<<6)) // Why? :D #define inf 0x7fffffff int arr[N]; int tree[MAX]; int lazy[MAX]; /** * Build and init tree */ void build_tree(int node, int a, int b) { if(a > b) return; // Out of range if(a == b) { // Leaf node tree[node] = arr[a]; // Init value return; } build_tree(node*2, a, (a+b)/2); // Init left child build_tree(node*2+1, 1+(a+b)/2, b); // Init right child tree[node] = max(tree[node*2], tree[node*2+1]); // Init root value } /** * Increment elements within range [i, j] with value value */ void update_tree(int node, int a, int b, int i, int j, int value) { if(lazy[node] != 0) { // This node needs to be updated tree[node] += lazy[node]; // Update it if(a != b) { lazy[node*2] += lazy[node]; // Mark child as lazy lazy[node*2+1] += lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } if(a > b || a > j || b < i) // Current segment is not within range [i, j] return; if(a >= i && b <= j) { // Segment is fully within range tree[node] += value; if(a != b) { // Not leaf node lazy[node*2] += value; lazy[node*2+1] += value; } return; } update_tree(node*2, a, (a+b)/2, i, j, value); // Updating left child update_tree(1+node*2, 1+(a+b)/2, b, i, j, value); // Updating right child tree[node] = max(tree[node*2], tree[node*2+1]); // Updating root with max value } /** * Query tree to get max element value within range [i, j] */ int query_tree(int node, int a, int b, int i, int j) { if(a > b || a > j || b < i) return -inf; // Out of range if(lazy[node] != 0) { // This node needs to be updated tree[node] += lazy[node]; // Update it if(a != b) { lazy[node*2] += lazy[node]; // Mark child as lazy lazy[node*2+1] += lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } if(a >= i && b <= j) // Current segment is totally within range [i, j] return tree[node]; int q1 = query_tree(node*2, a, (a+b)/2, i, j); // Query left child int q2 = query_tree(1+node*2, 1+(a+b)/2, b, i, j); // Query right child int res = max(q1, q2); // Return final result return res; } int main() { for(int i = 0; i < N; i++) arr[i] = 1; build_tree(1, 0, N-1); memset(lazy, 0, sizeof lazy); update_tree(1, 0, N-1, 0, 6, 5); // Increment range [0, 6] by 5. here 0, N-1 represent the current range. update_tree(1, 0, N-1, 7, 10, 12); // Incremenet range [7, 10] by 12. here 0, N-1 represent the current range. update_tree(1, 0, N-1, 10, N-1, 100); // Increment range [10, N-1] by 100. here 0, N-1 represent the current range. cout << query_tree(1, 0, N-1, 0, N-1) << endl; // Get max element in range [0, N-1] } ================================================ FILE: Data Structures/C:C++/Trees/tree/Fenwick_tree.cpp ================================================ #include using namespace std; int BIT[1000], arr[1000],l,r,n,s; void update(int x, int delta) { for( ;x<=n;x+=x&-x) BIT[x]+=delta; } int query(int x) { int sum=0; for(;x>0;x-=x&-x) sum+=BIT[x]; return sum; } int main() { cin>>n; cout<<"Enter "<>arr[i]; update(i,arr[i]); } cout<<"Give the number of elemets you want sum for\n"; cin>>s; cout<<"Sum of first "< #include "../queue/queue.hpp" using namespace std; template struct bst_node{ T data; bst_node *left_child; bst_node *right_child; bst_node(T new_data) : data(new_data), left_child(NULL), right_child(NULL) {}; }; template class BST{ private: bst_node *node; // helper functions int _get_length(bst_node *node){ if(node == NULL) return 0; return 1 + max(_get_length(node->left_child), _get_length(node->right_child)); } void _insert(bst_node *node, T new_data){ // if node exists if(node->data > new_data){ // go left if(node->left_child){ _insert(node->left_child, new_data); }else{ node->left_child = new bst_node(new_data); } }else{ // right if(node->right_child){ _insert(node->right_child, new_data); }else{ node->right_child = new bst_node(new_data); } } } void _print(bst_node *node){ if(!node) return; _print(node->left_child); cout << node->data << " "; _print(node->right_child); } void _print_post_order(bst_node *node){ if(!node) return; _print_post_order(node->left_child); _print_post_order(node->right_child); cout << node->data << " "; } void _print_pre_order(bst_node *node){ if(!node) return; cout << node->data << " "; _print_pre_order(node->left_child); _print_pre_order(node->right_child); } int _count_nodes(bst_node *node){ if(!node) return 0; return 1 + _count_nodes(node->left_child) + _count_nodes(node->right_child); } bool _find(bst_node *node, T data){ if(node){ if(node->data == data){ return true; } if(node->data > data){ // go left return _find(node->left_child, data); }else{ return _find(node->right_child, data); } } return false; } void _print_max_path(bst_node *node){ if(!node) return; cout << node->data << ' '; if(_get_length(node->left_child)){ _print_max_path(node->left_child); }else{ _print_max_path(node->right_child); } } T _get_max(bst_node *node){ if(node == NULL) return '\0'; bst_node *temp_node = node; while(temp_node->right_child){ temp_node = temp_node->right_child; } return temp_node->data; } T _get_min(bst_node *node){ if(node == NULL) return '\0'; bst_node *temp_node = node; while(temp_node->left_child){ temp_node = temp_node->left_child; } return temp_node->data; } bst_node *_get_min_node(bst_node *node){ if(node == NULL) return NULL; bst_node *temp_node = node; while(temp_node->left_child){ temp_node = temp_node->left_child; } return temp_node; } bst_node *_delete_value(bst_node *root, T del_data){ if(root == NULL) return root; if(del_data < root->data){ root->left_child = _delete_value(root->left_child, del_data); }else if(del_data > root->data){ root->right_child = _delete_value(root->right_child, del_data); }else{ // check if one child is NULL if(root->left_child == NULL){ bst_node *temp_node = root->right_child; delete root; return temp_node; }else if(root->right_child == NULL){ bst_node *temp_node = root->left_child; delete root; return temp_node; } // if the node has both the bst_node *temp_node = _get_min_node(root->right_child); cout << "min node " << temp_node->data << endl; root->data = temp_node->data; root->right_child = _delete_value(root->right_child, temp_node->data); } return root; } int _get_count(bst_node *node){ if(node == NULL) return 0; return 1 + _get_count(node->left_child) + _get_count(node->right_child); } void _level_order(bst_node *node){ if(node == NULL) return; cout << "Level order traversal:" << endl; queuemp *> *q = new queuemp *>(); q->push(node); while(q->size){ bst_node *temp = q->pop(); if(temp->left_child) q->push(temp->left_child); if(temp->right_child) q->push(temp->right_child); cout << temp->data << " "; } cout << endl; delete q; } public: BST() : node(NULL) {} BST(T new_data) : node(new bst_node(new_data)) {} ~BST(); T data(){ return this->node->data; } void insert(T new_data){ bst_node *new_node = new bst_node(new_data); if(node == NULL){ node = new bst_node(new_data); return; } _insert(node, new_data); } int get_length(){ return _get_length(node); } void print(){ cout << "Printing BST (in order):" << endl; _print(node); cout << endl; } void print_post_order(){ cout << "Printing BST (post order):" << endl; _print_post_order(node); cout << endl; } void print_pre_order(){ cout << "Printing BST (pre order):" << endl; _print_pre_order(node); cout << endl; } T get_max(){ return _get_max(node); } T get_min(){ return _get_min(node); } int count_nodes(){ return _count_nodes(node); } bool find(T data){ return _find(node, data); } void print_max_path(){ cout << "Max path:" << endl; _print_max_path(node); cout << endl; } void delete_value(T del_data){ this->node = _delete_value(this->node, del_data); } int get_count(){ return _get_count(this->node); } void level_order(){ _level_order(this->node); } }; ================================================ FILE: Data Structures/C:C++/Trees/tree/segment_tree.hpp ================================================ #include #include class segment_tree{ private: int *st; int *ar; int len; int sz; //size of segment tree // function to get middle of a segment int _get_mid(int start, int end){ return start + (end - start) / 2; } // util function to contruct segment tree int _construct(int *v, int start, int end, int current){ // if there is 1 element in stray, store in current // node and return if(start == end){ st[current] = v[start]; return v[start]; } // for more elements, recur for left & right subtrees // store the sum for values in this node int mid = _get_mid(start, end); st[current] = _construct(v, start, mid, current*2 + 1) + _construct(v, mid + 1, end, current*2 + 2); return st[current]; } // utility to update a value in segment tree void _update_value(int start, int end, int i, int difference, int current){ if(iend) return; st[current] = st[current] + difference; if(end != start){ int mid = _get_mid(start, end); _update_value(start, mid, i, difference, 2*current+1); _update_value(mid+1, end, i, difference, 2*current+2); } } int _get_sum(int start, int end, int q_start, int q_end, int current){ if(q_start <= start && q_end >= end) return st[current]; // outside range if(end < q_start || start > q_end) return 0; int mid = _get_mid(start, end); return _get_sum(start, mid, q_start, q_end, 2*current+1) + _get_sum(mid+1, end, q_start, q_end, 2*current+2); } public: segment_tree(int *v, int n){ ar = new int[n]; this->len = n; for(int i=0;isz = 0; int h = (int)ceil(log2(n)); int max_size = 2 * (int)pow(2, h) - 1; this->sz = max_size; // allocate memory st = new int[max_size]; _construct(v, 0, n-1, 0); } // update value in void update(int i, int new_val){ if(i<0 || i>this->len-1) return; int difference = new_val - ar[i]; ar[i] = new_val; // update segment tree _update_value(0, this->len-1, i, difference, 0); } //get sum of range int get_sum(int start, int end){ if(start < 0 || end > this->len-1 || start > end) return -1; return _get_sum(0, this->len-1, start, end, 0); } int get(int n){ return st[n]; } void print(){ cout << "Printing segment tree" << endl; int n = this->sz; for(int i=0;i using namespace std; template struct tree_node{ T data; tree_node *left_child; tree_node *right_child; tree_node(T new_data) : data(new_data), left_child(NULL), right_child(NULL) {}; void insert_left(T new_data){ tree_node *new_node = new tree_node(new_data); this->left_child = new_node; } void insert_right(T new_data){ tree_node *new_node = new tree_node(new_data); this->right_child = new_node; } }; template int get_length(tree_node *top){ if(top == NULL) return 0; return 1 + max(get_length(top->left_child), get_length(top->right_child)); } ================================================ FILE: Data Structures/C:C++/Trees/tree/trie.cpp ================================================ #include using namespace std; typedef long long int ll; int ii,i,at; struct no{ no* nxt[26]; no *root; ll fim,qtdNo; inline no(char k){ for(ii=0;ii<26;ii++) nxt[ii] = NULL; root = this; fim = qtdNo = 0; } inline bool insert(const string s, ll i){ if(i == s.size()){ fim = 1; return false; } at = s[i] - 'a'; if(!nxt[at]){ nxt[at] = new no(s[i]); nxt[at] -> root = root; root -> qtdNo++; } else if(nxt[at] -> fim) return true; return nxt[at] -> insert(s,i+1); } }; main(){} ================================================ FILE: Data Structures/C:C++/queue/queue.hpp ================================================ #include #include "../linked_list/ll.hpp" using namespace std; template struct queuemp{ ll_node *head; int size; // number of elements in the queue queuemp() : size(0) {} void push(T new_data){ ll_node *new_node = create_node(new_data); ll_node *temp_node = this->head; new_node->next = temp_node; this->head = new_node; this->size++; } void print(){ if(this->size == 0){ cout << "queue is empty" << endl; return; } ll_node *temp_node = this->head; cout << "Printing queue:" << endl; for(int i=0;isize;i++){ cout << temp_node->data << " "; temp_node = temp_node->next; } cout << endl; } T pop(){ if(this->size == 0){ cout << "queue is empty, can't pop" << endl; return '\0'; } if(this->size == 1){ T data = this->head->data; this->head = NULL; this->size = 0; return data; } ll_node *new_node = this->head; // move to second last element for(int i=0;isize-2;i++) new_node = new_node->next; //cout << new_node->data << endl; T data = new_node->next->data; new_node->next = NULL; this->size--; return data; } T peek(){ return this->head->data; } }; template int get_size(queuemp *s){ return s->size; } ================================================ FILE: Data Structures/Java/Stack/Stack.java ================================================ import java.lang.IndexOutOfBoundsException; import java.util.Arrays; public class Stack { private int max; private int top; private Object[] list; public Stack() { max = 512; top = 0; list = new Object[max]; } public Stack(int size) { max = size; top = 0; list = new Object[max]; } @SuppressWarnings("unchecked") public boolean isEmpty() { for(E t : (E[]) list) { if(t != null) { return false; } } return true; } @SuppressWarnings("unchecked") public E peek() { return (E) list[top]; } @SuppressWarnings("unchecked") public int size() { if(top == 0) { return 0; } int count = 0; for(E t : (E[]) list) { if(t != null) { count++; } } return count; } @SuppressWarnings("unchecked") public E pop() { if(isEmpty()) { throw new IndexOutOfBoundsException("This stack is empty; nothing to pop."); } E data = (E) list[top]; top = (top == 0 ? 0 : top - 1); return data; } public void push(E data) { if(top == max - 1) { list = Arrays.copyOf(list, list.length * 2); } top++; list[top] = data; } } ================================================ FILE: Data Structures/Python/Graphs/Graph.py ================================================ from collections import defaultdict class Graph(object): def __init__(self, connections, directed=False):#undirected by default self._graph = defaultdict(set) self._directed = directed self.add_connections(connections) def add_connections(self, connections): """ Add connections (list of tuple pairs) to graph """ for node1, node2 in connections: self.add(node1, node2) def add(self, node1, node2): """ Add connection between node1 and node2 """ self._graph[node1].add(node2) if not self._directed: self._graph[node2].add(node1) def remove(self, node): """ Remove all references to node """ for n, cxns in self._graph.iteritems(): try: cxns.remove(node) except KeyError: pass try: del self._graph[node] except KeyError: pass def is_connected(self, node1, node2): """ Is node1 directly connected to node2 """ return node1 in self._graph and node2 in self._graph[node1] def find_path(self, node1, node2, path=[]): """ Find any path between node1 and node2 (may not be shortest) """ path = path + [node1] if node1 == node2: return path if node1 not in self._graph: return None for node in self._graph[node1]: if node not in path: new_path = self.find_path(node, node2, path) if new_path: return new_path return None def __str__(self): return '{}({})'.format(self.__class__.__name__, dict(self._graph)) ================================================ FILE: Data Structures/Python/Graphs/dfs.py ================================================ import collections class Graph: def __init__(self): self.adjList = collections.defaultdict(set) def addEdge(self, node1, node2): self.adjList[node1].add(node2) self.adjList[node2].add(node1) def dfsHelper(current, graph, visited, visitFunc): if (visited[current]): return visited[current] = True; visitFunc(current) for neighbor in graph.adjList[current]: dfsHelper(neighbor, graph, visited, visitFunc) def dfs(current, graph, visitFunc): visited = collections.defaultdict(bool) dfsHelper(current, graph, visited, visitFunc) def visitPrint(i): print(i) # Testing the depth first search implementation if __name__ == "__main__": # Testing on this tree # 1 # / \ # / \ # 2 3 # / \ / \ # 4 5 6 7 g = Graph() g.addEdge(1, 2) g.addEdge(1, 3) g.addEdge(2, 4) g.addEdge(2, 5) g.addEdge(3, 6) g.addEdge(3, 7) print("Test 1:") dfs(1, g, visitPrint) print("\nTest2:") dfs(2, g, visitPrint) ================================================ FILE: Data Structures/Python/Linked List/singly_linked_list.py ================================================ class Node(object): def __init__(self, data, next): self.data = data self.next = next class SingleList(object): head = None tail = None def show(self): print "Showing list data:" current_node = self.head while current_node is not None: print current_node.data, " -> ", current_node = current_node.next print None def append(self, data): node = Node(data, None) if self.head is None: self.head = self.tail = node else: self.tail.next = node self.tail = node def remove(self, node_value): current_node = self.head previous_node = None while current_node is not None: if current_node.data == node_value: # if this is the first node (head) if previous_node is not None: previous_node.next = current_node.next else: self.head = current_node.next # needed for the next iteration previous_node = current_node current_node = current_node.next s = SingleList() s.append(31) s.append(2) s.append(3) s.append(4) s.show() s.remove(31) s.remove(3) s.remove(2) s.show() ================================================ FILE: Data Structures/Python/Queue/Queue.py ================================================ #List Based Implementation Of Queue in Python. #Defining a python Class named Queue. # isEmpty -> Returns True or False. # enqueue -> Enter the element in Queue. # dequeue -> Remove the element from Queue. # size -> Returns the size of Queue class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) q=Queue() #Create an object of Class Queue #Calling the functions q.enqueue(4) q.enqueue('dog') q.enqueue(True) print(q.size()) ================================================ FILE: Data Structures/Python/Stack/stack.py ================================================ #Make a class Stack class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.insert(0,item) def pop(self): return self.items.pop(0) def peek(self): return self.items[0] def size(self): return len(self.items) #Calling Object of class Stack s = Stack() #Calling the function s.push('hello') s.push('true') print(s.pop()) ================================================ FILE: Data Structures/Python/Trees/m-coloring-problem.py ================================================ class Graph: def __init__(self,m,v): self.adj=m self.V=v def mColoring(k,m,g,x): while(True): x[k]=getNodeColor(k,m,g,x) if(x[k]==0): return if(k==g.V-1): print(x) else: mColoring(k+1,m,g,x) def getNodeColor(k,m,g,x): while(True): x[k]=(x[k]+1)%(m+1) #bcoz any vertex should be assigned from 1 to m if(x[k]==0): return x[k] #checking for any collisions of color for j in range(g.V): if(g.adj[k][j]==1 and x[k]==x[j]): #same color break else: return x[k] def main(): matrix=[[0,1,1,1], [1,0,1,0], [1,1,0,1], [1,0,1,0] ] g=Graph(matrix,4) m=3 #Number of colors x=[0 for i in range(g.V)] mColoring(0,m,g,x) if __name__=='__main__': main() ''' Possible Coloring: [1, 2, 3, 2] [1, 3, 2, 3] [2, 1, 3, 1] [2, 3, 1, 3] [3, 1, 2, 1] [3, 2, 1, 2] ''' ================================================ FILE: Dynamic Programing/Dynamic_fibonacci.py ================================================ # Function for nth fibonacci number - Dynamic Programing # Taking 1st two fibonacci nubers as 0 and 1 FibArray = [0,1] def fibonacci(n): if n<0: print("Incorrect input") elif n<=len(FibArray): return FibArray[n-1] else: temp_fib = fibonacci(n-1)+fibonacci(n-2) FibArray.append(temp_fib) return temp_fib # Driver Program #Suppose we wan't to print the 9th fibonacci number #You can ask for user input and substitute in place of 9 print(fibonacci(9)) ================================================ FILE: Dynamic Programing/Edit Distance.Py ================================================ memo={} def DP(x,y,i,j): if i>=len(x): memo[(i,j)]=len(y)-j return len(y)-j if j>=len(y): memo[(i,j)]=len(x)-i return len(x)-i if (i,j) in memo: return memo[(i,j)] if x[i]==y[j]: memo[(i,j)]=min(DP(x,y,i,j+1),DP(x,y,i+1,j),DP(x,y,i+1,j+1)) return memo[(i,j)] else: res=1+min(DP(x,y,i,j+1),DP(x,y,i+1,j),DP(x,y,i+1,j+1)) memo[(i,j)]=res return res '''Driver PRogram''' x='MICHAELANGELO' y='HIEROGLYPHOLOGY' s1='a' s2='ab' r=DP(x,y,0,0) print(r) ================================================ FILE: Dynamic Programing/Knapsack.py ================================================ ######'''Knapsack problem'''##### memo={} included={} def DP(val,s,i,x): if i==len(val) or x==0: return 0 if i in memo: return memo[(i,x)] #Not Possible to be added if s[i]>x: memo[(i,x)]=DP(val,s,i+1,x) included[i]=0 return memo[(i,x)] else: #Not Added if DP(val,s,i+1,x)>val[i]+DP(val,s,i+1,x-s[i]): memo[(i,x)]=DP(val,s,i+1,x) included[i]=0 #Added else: memo[(i,x)]=val[i]+DP(val,s,i+1,x-s[i]) included[i]=1 return memo[(i,x)] '''Driver Program''' val=[4,10,2] s=[12,4,2] size=15 value=DP(val,s,0,size) print('Maximum Value:',value) print('Subset:',end=' ') for i in included: if included[i]: print(val[i],end=' ') ================================================ FILE: Dynamic Programing/Memoized Cut Rod.Py ================================================ import math memo={} piece={} def cut_rod(p,n): if n==0: return 0 if n in memo: return memo[n] else: q=-1 for i in range(1,n+1): #q=max(q,p[i]+cut_rod(p,n-i)) if q0): print (piece[n]) n-=piece[n] ================================================ FILE: Dynamic Programing/Word_Wrap.Py ================================================ import math memo={} parent={} def badness(i,j,m): totsize=0 extra=0 for x in range(i,j): totsize+=len(ls[x]) extra+=1 totsize+=extra-1 if m>=totsize: return ((m-totsize)**3) else: return math.inf def minimum(i,ls,w,n): p=[] for j in range(i+1,n+1): p+=[DP(j,ls,w,n)+badness(i,j,w)] parent[i]=p.index(min(p))+i+1 return min(p) def DP(i,ls,w,n): if i in memo: return memo[i] if i==n: parent[n]=None return 0 else: #t= min(DP(j,ls,w,n)+badness(i,j,w) for j in range(i+1,n+1)) t=minimum(i,ls,w,n) memo[i]=t return t '''Driver Code''' s='aaa bb cc ddddd' ls=s.split() print('Sample Text:',s) words=len(ls) width=6 DP(0,ls,width,words) #printing text p=0 while parent[p]!=None: print(*ls[p:parent[p]]) p=parent[p] ================================================ FILE: Dynamic Programing/longest_increasing_subsequence.cpp ================================================ #include using namespace std; int longestIncreasingSubsequence(int A[],int size){ int dp[size]; for(int i=0;i #include using namespace std; int main() { int num; //Number to be tested float chk; for (num = 1; num < 100 ; num++) { chk = sqrt(5*pow(num,2) + 4); if(chk - (int)chk == 0) cout< #define ll long long int #define mod 1000000007 #define show(a) for(i=0;i #define vs vector #define vll vector #define pb push_back #define pi pair #define si set #define sll set #define maxheap priority_queue #define minheap priority_queue,greater> #define mp make_pair #define fast_io() cin.sync_with_stdio(false);cout.sync_with_stdio(false); #define long_zero 0ll #define long_one 1ll inline int sbt(int x){return __builtin_popcount(x);} using namespace std; int freq[1111111]; int BLOCK; //Mo Sorting bool f(pair a, pair b){ if(a.se.fi/BLOCK == b.se.fi/BLOCK) return a.se.se>b.se.se; return a.se.fi/BLOCK>b.se.fi/BLOCK; } int main() { //fast_io() int n; scanf("%d",&n); int a[n+3]; for(int i=0;i>q; scanf("%d",&Q); //block size:SQRT(N) BLOCK = floor(sqrt(1.0*double(n))); for(int i=0;il){ freq[a[s-1]]++; if(freq[a[s-1]]==1) ans++; s--; } while(e<=r){ freq[a[e]]++; // mantains frequency if(freq[a[e]]==1) ans++; e++; } while(e>r+1){ freq[a[e-1]]--; if(freq[a[e-1]]==0) ans--; e--; } v[q[i].fi]=ans; } for(int i=0;i #include int main(void) { int n,r,a=0,t,c=0,z; printf("Enter a number: "); scanf("%d",&n); t=n; z=n; while(z>0) { z=z/10; c++; } while(n>0) { r=n%10; a=a+pow(r,c); n=n/10; } if(a==t) printf("\nThe number is armstrong\n"); else printf("\nThe number is not armstrong\n"); return 0; } ================================================ FILE: Mathematical Challenges/C:C++/armstrong_number/README.md ================================================ ### Armstrong number Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if : >**abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....** #### Example: Input : 1634
Output : The number is armstrong
14 + 64 + 34 + 44 = 1634 ================================================ FILE: Mathematical Challenges/C:C++/convexHull/ConvexHullScan.cpp ================================================ #include #include #include #include #include using namespace std; //This function decides if 3 points form a right turn or not bool Is_Right_Turn(vector > Hull){ pair P1, P2, P3; int Determinant; //P1, P2 and P3 are the last 3 points in the given Hull P1 = Hull[Hull.size() - 3]; P2 = Hull[Hull.size() - 2]; P3 = Hull[Hull.size() - 1]; /*Cross Product is given by the determinant of the following 3x3 matrix - 1 P1.x P1.y 1 P2.x P2.y 1 P3.x P3.y */ Determinant = ((P2.first - P1.first) * (P3.second - P1.second) - (P2.second - P1.second) * (P3.first - P1.first)); //Points form right turn only if the determinant is less than 0 (Equal to zero means colinear) return (Determinant < 0); } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int Number_of_Points, X, Y, i; vector > Points, Upper_Hull, Lower_Hull; set > Convex_Hull; cin>>Number_of_Points; //Enter the points as (X,Y) coordinates for(i = 0; i < Number_of_Points; i++){ cin>>X>>Y; Points.push_back(make_pair(X,Y)); } //Sort the points first by X coordinate and then by Y coordinate sort(Points.begin(),Points.end()); //Form the upper half of convex hull Upper_Hull.push_back(Points[0]); Upper_Hull.push_back(Points[1]); for(i = 2; i < Number_of_Points; i++){ Upper_Hull.push_back(Points[i]); while(Upper_Hull.size() >= 3){ if(Is_Right_Turn(Upper_Hull)) break; else //Remove the middle point from the hull Upper_Hull.erase(Upper_Hull.end() - 2); } } //Form the lower half of the hull Lower_Hull.push_back(Points[Number_of_Points - 1]); Lower_Hull.push_back(Points[Number_of_Points - 2]); for(i = Number_of_Points-3; i>= 0; i--){ Lower_Hull.push_back(Points[i]); while(Lower_Hull.size() >= 3){ if(Is_Right_Turn(Lower_Hull)) break; else //Remove the middle point from the hull Lower_Hull.erase(Lower_Hull.end() - 2); } } //Merge the Upper and Lower Hulls for(auto &upper:Upper_Hull) Convex_Hull.insert(upper); for(auto &lower:Lower_Hull) Convex_Hull.insert(lower); //Print the Convex Hull for(auto &point:Convex_Hull) cout<<"("< int main(){ int x; printf("Enter the number"); scanf("%d",&x); int fact=1; for(fact=1;x>1;x--){ fact=fact*x; } printf("%d",fact); return 0; } ================================================ FILE: Mathematical Challenges/C:C++/fibbinacci/fibbinacci.c ================================================ #include int main(){ int x,y,z; printf("Enter the number\n"); scanf("%d",&x); int temp=0; for(int i=0;i<=x;i++){ temp+=i; } printf("%d",temp); return 0; } ================================================ FILE: Mathematical Challenges/C:C++/gcd/extended_gcd.cpp ================================================ #include #define F0(i,t) for(int i=0; i mp; int debugg = 0; struct Res_gcd{ int gcd,x,y; Res_gcd(int gcd, int x, int y){ this -> gcd = gcd; this -> x = x; this -> y = y; } }; /* * return object of Res_gcd * Res_gcd.gcd ==> gcd of a,b * Res_gcd.x and Res_gcd.y ==> x and y such that ax + by = gcd(a,b) * NOTE : a must not be 0 ==> if so ans is b,0,1 */ Res_gcd gcd_extended(int a,int b){ if(b%a==0) return Res_gcd(a,1,0); //coz 1*a + 0*b = a { == gcd(a,b)} Res_gcd temp = gcd_extended(b%a,a); return Res_gcd( temp.gcd , temp.y - (b/a)*temp.x , temp.x ); } int main(){ int t=1; ios_base::sync_with_stdio(0);cin.tie(0); Res_gcd ans(1,1,1); cin>>t; while(t--){ int a,b; cin>>a>>b; if(a==0)//fxn throw divide by 0 exception on a = 0 ans = Res_gcd(b,0,1); else ans = gcd_extended(a,b); cout< /* * be careful a must not be zero * if so then ans is b */ int gcd(int a,int b){ if(b%a==0) return a; return gcd(b%a,a); } int main() { int t=1,a,b,ans; scanf("%d",&t); while(t--) { scanf("%d %d",&a,&b); if(a==0)//gcd throw exception on a = 0 ans = b; else ans=gcd(a,b); printf("%d\n",ans); } return 0; } ================================================ FILE: Mathematical Challenges/C:C++/gcd/mod_inverse.cpp ================================================ #include #define F0(i,t) for(int i=0; i mp; int debugg = 0; struct Res_gcd{ int gcd,x,y; Res_gcd(int gcd, int x, int y){ this -> gcd = gcd; this -> x = x; this -> y = y; } }; /* * return object of Res_gcd * Res_gcd.gcd ==> gcd of a,b * Res_gcd.x and Res_gcd.y ==> x and y such that ax + by = gcd(a,b) * NOTE : a must not be 0 ==> if so ans is b,0,1 */ Res_gcd gcd_extended(int a,int b){ if(b%a==0) return Res_gcd(a,1,0); //coz 1*a + 0*b = a { == gcd(a,b)} Res_gcd temp = gcd_extended(b%a,a); return Res_gcd( temp.gcd , temp.y - (b/a)*temp.x , temp.x ); } /* * i created this function because in cpp * -1%7 give -1 not 6 * this fxn give +ve values for even -ve values of num */ int modd(int num,int m){ return (num%m + m)%m; } /* * */ int mod_inverse(int a,int m){ Res_gcd temp = gcd_extended(a,m); if(temp.gcd != 1) return -1; else{ return modd(temp.gcd,m); } } int main(){ int t=1; ios_base::sync_with_stdio(0);cin.tie(0); Res_gcd ans(1,1,1); cin>>t; while(t--){ int a,m; cin>>a>>m; cout< int main(){ int x,y,z; printf("Enter 1st number"); scanf("%d",&x); printf("Enter 2nd number"); scanf("%d",&y); printf("Enter 3rd number"); scanf("%d",&z); int big=(x>y)?((x>z)?x:z):(y>z)?y:z; printf("%d",big); } ================================================ FILE: Mathematical Challenges/C:C++/mathpuzzle.c/matchstick game ================================================ //21 matchstick game in C #include int main (int argc, const char * argv[]) { int matchstick = 21; int user,computer; while (matchstick>=1) { if (matchstick==1) { printf("\nMatch stick status:%d",matchstick); printf("\nYou loose!!!!!!:(:("); break; } printf("\nMatch stick status:%d",matchstick); printf("\nEnter the choice (1,2,3,4)):"); scanf("%d",&user); printf("\nYou picked %d",user); if (user>=5 || user <=0) { printf("\nInvalid value"); continue; } computer = 5 - user; printf("\nComputer picked%d",computer); matchstick = matchstick - computer - user; } return 0; } ================================================ FILE: Mathematical Challenges/C:C++/multiplication/multiply 2 numbers greater than 10^6.cpp ================================================ /* This program can be used to multiply 2 numbers grater than 10^5, usually a major hurdle in languages like C/C++ in competitive programming, using this as a template one can perform implementations like Factorials of 100 etc */ #include using namespace std; int main() { ios_base::sync_with_stdio(false); int n1, n2; cin>>n1>>n2; int c = 0, ans[100000] = {0}, i = 0, basei = 0, temp = n2, dig = 0, tmp; while(n1) { if(n2) { c = ( (n1%10)*(n2%10) ); ans[i] += c; if(ans[i]>9) { ans[i+1] += ans[i]/10; ans[i] = ans[i]%10; } c /= 10; n2 /= 10; dig++; i++; } else { tmp = dig; n2 = temp; n1 /= 10; i = ++basei; c=0; dig = basei; } } for(int k = tmp-1 ;k>=0;k--) cout< #define ui unsigned long long int #define mod 1000000007 using namespace std; //faster wayy to calc (b^p)%mod in log(p) //it is fast as it dont use recursion ui modular_expo_no_rec(int base,int p){ ui ans = 1,fact = base; while(p){ if(p & 1) ans = (ans * fact)%mod; fact = (fact * fact)%mod; p = p>>1; } return ans%mod; } //return (b^p)%mod in log(p) ui modular_expo_rec(ui b,ui p){ if(p==1) return b; ui temp = modular_expo_rec(b,p/2); temp = (temp*temp)%mod; if(p & 1)//odd return (temp * b)%mod; else return temp; } int main(){ int t,base,pow; ui ans; cin>>t; while(t--){ cin>>base>>pow; cout< #define ui unsigned long long int #define mod 100000007 using namespace std; ui two_pow(int n){ ui ans = 1,fact = 2; while(n){ if(n & 1) ans = (ans * fact)%mod; fact = (fact * fact)%mod; n = n>>1; } return ans%mod; } //return b^p ui modular_expo(ui b,ui p){ if(p==1) return b; if(p & 1) return ((modular_expo(b,p/2)*modular_expo(b,p/2))%mod * b)%mod; else return (modular_expo(b,p/2)*modular_expo(b,p/2))%mod; } int main(){ int t,n; ui ans=0,pow,sum,a; cin>>t; for (int i=1;i<=t;i++){ sum=0; cin>>n; pow = modular_expo(2,n-1); while(n--){ cin>>a; sum+=a; } sum=sum%mod; ans = (sum*pow)%mod; cout<<"Case "< #define F0(i,t) for(int i=0; i mp; int debugg = 0; int two_pow(int p){ int ans = 1,fact =2; while(p){ if( p&1 )//p is odd ans = ans * fact; fact = fact * fact; p = p>>1; } return ans; } int main(){ int t=1; ios_base::sync_with_stdio(0);cin.tie(0); cin>>t; while(t--){ int p; cin>>p; cout< Set> powerSet( Set set ) { T[] element = (T[]) set.toArray(); final int SET_LENGTH = 1 << element.length; Set> powerSet = new HashSet<>(); for( int binarySet = 0; binarySet < SET_LENGTH; binarySet++ ) { Set subset = new HashSet<>(); for( int bit = 0; bit < element.length; bit++ ) { int mask = 1 << bit; if( (binarySet & mask) != 0 ) { subset.add( element[bit] ); } } powerSet.add( subset ); } return powerSet; } public static void main(String[] args) { Set test = new HashSet<>(); test.add( 'a' ); test.add( 'b' ); test.add( 'c' ); System.out.println("test = " + test); Set> result = powerSet( test ); System.out.println( result ); } } ================================================ FILE: Mathematical Challenges/C:C++/prime/PrimeCheck.py ================================================ #Simple way to check for primes using Pyton. #Prompt user for a integer Number = int(input("Enter any integer to check if prime number ")) #Set starting divisor to 2 Divisor = 2 for Divisor in range (Divisor, Number) : #Test every number between 2 and the integer if Number % Divisor == 0: prime = False # Tell computer to make prime false break #End loop Divisor += 1 #Add 1 to the divisor else: prime = True # If number % divisor does not equal 0, number must be a prime, so mark as true #Print results if prime == True : print("Your number is a prime") if prime == False : print("Your number is not a prime") ================================================ FILE: Mathematical Challenges/C:C++/prime/PrimeToNumber.py ================================================ #Python Prime checker. Not the most efficient way to check for primes, but very easy to code! num = int(input("Enter a integer to get primes up to ")) #Get highest number for prime div=2 #Set divisor to intitally 2 for num in range(2,num): #Check if prime prime = True #If prime is true set flag. for div in range(2,num): #If number can be divided by any number, from 2 to the number-1 if (num % div == 0):#If evenly divided, the number will therefore be notprime. prime = False #set prime to false if prime: print (num) ================================================ FILE: Mathematical Challenges/C:C++/prime/prime.c ================================================ #include int main(){ int x,y,z; printf("Enter the number\n"); scanf("%d",&x); y=x/2; if(x%2==0 && x!=2){ printf("It is not a prime\n"); } else{ for(z=3;z<=y;z++) { if(x%z==0){ printf("it is not a prime number "); } else{ printf("it is a prime"); break; } } return 0; } ================================================ FILE: Mathematical Challenges/C:C++/prime/sieveOferatosthenes.cpp ================================================ #include #include using namespace std; void sieve_of_eratosthenes(std::vector& primes, const int max) { vector isPrime; // Initially, all the numbers are considered to be prime for (int i = 0; i <= max; i++) { isPrime.push_back(true); } // 0 and 1 are obviously not prime, so we set it in the isPrime vector isPrime[0] = isPrime[1] = false; // Iterate from 2 up to the square root of max for (int i = 2; i*i <= max; i++) { if (isPrime[i]) { // If the current number is prime, then set i^2, i^2+i, i^2+2i, ... as not prime for (int j = i * i; j <= max; j += i) { isPrime[j] = false; } } } // Iterate from 2 to max again. All the numbers, that are still set to true, are prime for (int i = 2; i <= max; i++) { if (isPrime[i]) { primes.push_back(i); } } } int main() { int n = 100; vector primes; // Find primes up to n sieve_of_eratosthenes(primes, n); cout << "Primes up to "< using namespace std; int main() { int numofprimes = 10, prime; for (int i = 2; i #define ui unsigned long long int using namespace std; ui arr[10]={0,1,3,6,10,15,21,28,36,45}; ui sum[11]; ui sum_of_digits(string str){ ui ans =0; for(int i=0;i>a>>b; while(a>=0){ if(a==0)a++; aa=to_string(a-1); bb=to_string(b); ans_a=digit_sum(aa); ans_b=digit_sum(bb); // cout<>a>>b; } } ================================================ FILE: Mathematical Challenges/python/pernicious_prime/pernicious.py ================================================ '''This is a proposed brute force algorithm writtem in python to test whether a given input positive integer other than 1 and 2 is a pernicious prime or not''' #OUTPUT FORMAT :- if pernicious number , output yes else no #INPUT FORMAT :- A positive integer other than 1 and 2 '''According to number theory , a positive number is pernicious number if sum of the digit of this number in binary form is prime''' '''Basic Outline Of Algorithm:- We count the set bits of a number and check whether that count is prime or not''' #################### Overall complexity is O(sqrt(n)*log(n)) ############################ import math def isprime(num): #function to check whether a number is prime or not #A simple solution is to iterate through all numbers from 2 to n-1 #and for every number check if it divides n. If we find any number that #divides, we return false. We can do following optimizations: #Instead of checking till n, we can check till sqrt(n) because a larger #factor of n must be a multiple of smaller factor that has been already #checked.The algorithm can be improved further by observing that all #primes are of the form 6k + 1 or 6k - 1, with the exception of 2 and 3. #This is because all integers can be expressed as (6k + i) for some #integer k and for i = -1, 0, 1, 2, 3, or 4.This is because since 2 #divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more #efficient method is to test if n is divisible by 2 or 3, then to check #through all the numbers of form 6k + 1 or 6k - 1 if num<3 or num==3: return 1 if num%2==0 or num%3==0: return 0 for i in range(5,int(math.sqrt(num))+1,6): if num%i==0 or num%(i+2)==0: return 0 return 1 ########## O(sqrt(n)) def count_ones(num): #function to calculate the number of set bits in a number #Loop through all bits in an integer, check if a bit is set and if it is #then increment the set bit count. But we can also do it in more efficient way :- #Subtraction of 1 from a number toggles all the bits (from right to left) till #the rightmost set bit(including the righmost set bit). So if we subtract a #number by 1 and do bitwise & with itself (n & (n-1)), we unset the righmost #set bit. If we do n & (n-1) in a loop and count the no of times loop executes #we get the set bit count.Beauty of the this solution is number of times it loops #is equal to the number of set bits in a given integer. count=0 while num: num = (num&(num-1)) count+=1 return count ########## O(log(n)) while 1: num = input("Enter any positive integer: ") #other than 1 and 2 if num!=1 and num!=2: total_set_bits = count_ones(num) #since sum of set bits is equivalent to counting those bits flag=isprime(total_set_bits) if flag==1: print "yes\n" else: print "no\n" else: print "Please enter any number other tha 1 or 2\n" ================================================ FILE: Mathematical Challenges/python/sieve_of_eratoshthenes.py ================================================ import sys import array import math isprime=array.array('i',(0 for i in range(0,1001))) def sieve(): for i in range(2,math.sqrt(1000)): for j in range(2,sys.maxsize**10): if(i*j >1000): break isprime[i*j]=1 sieve() n=int(input()) for i in range(2,n+1): if(isprime[i] is 0): print(i,end=" ") ================================================ FILE: Patterns/pattern10.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; int count = 1; char spaces = ' '; for( int i = 1; i <= n; i++ ){ for( int j = n - i; j > 0; j-- ){ cout << spaces; } for( int j = 1; j <= i; j++ ){ cout << count; count++; } cout << endl; } return 0; } /* 4 1 23 456 78910 */ ================================================ FILE: Patterns/pattern11.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; int count = 1; char spaces = ' '; for( int i = 1; i <= n; i++ ){ for( int j = n - i; j > 0; j-- ){ cout << spaces; } for( int j = 1; j <= i; j++ ){ cout << count << " "; count++; } cout << endl; } return 0; } /* 4 1 2 3 4 5 6 7 8 9 10 */ ================================================ FILE: Patterns/pattern12.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; int count = 1; char spaces = ' '; for( int i = 1; i <= n; i++ ){ for( int j = 1; j < i; j++ ){ cout << spaces; } for( int j = n; j >= i; j-- ){ cout << count << " "; count++; } cout << endl; } return 0; } /* 3 1 2 3 4 5 6 */ ================================================ FILE: Patterns/pattern13.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; int count = 1; char spaces = ' '; for( int i = 1; i <= n; i++ ){ for( int j = 1; j < i; j++ ){ cout << spaces; } for( int j = n; j >= i; j-- ){ cout << count; count++; } cout << endl; } return 0; } /* 3 123 45 6 */ ================================================ FILE: Patterns/pattern14.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; int count = 1; char spaces = ' '; for( int i = 1; i <= n; i++ ){ for( int j = n - i; j > 0; j-- ){ cout << spaces; } for( int j = 1; j <= i; j++ ){ cout << count << " "; count++; } cout << endl; } count--; for( int i = 1; i <= n; i++ ){ for( int j = 1; j < i; j++ ){ cout << spaces; } for( int j = n; j >= i; j-- ){ count--; cout << count << " "; } cout << endl; } return 0; } /* 4 1 2 3 4 5 6 7 8 9 10 6 5 4 3 2 1 */ ================================================ FILE: Patterns/pattern15.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; int count = 1; char spaces = ' '; for( int i = 1; i <= n; i++ ){ for( int j = n - i; j > 0; j-- ){ cout << spaces; } for( int j = 1; j <= i; j++ ){ cout << count << " "; count++; } cout << endl; } for( int i = 1; i <= n; i++ ){ for( int j = 1; j < i; j++ ){ cout << spaces; } for( int j = n; j >= i; j-- ){ cout << count; count++; } cout << endl; } return 0; } /* 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 */ ================================================ FILE: Patterns/pattern16.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; int count = 1; char spaces = ' '; for( int i = 1; i <= n; i++ ){ for( int j = n - i; j > 0; j-- ){ cout << spaces; } for( int j = 1; j <= i; j++ ){ cout << count << " "; count++; } cout << endl; } count--; for( int i = 1; i <= n-1; i++ ){ for( int j = 1; j <= i; j++ ){ cout << spaces; } for( int j = n-1; j >= i; j-- ){ count--; cout << count << " "; } cout << endl; } return 0; } ================================================ FILE: Patterns/pattern8.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; int count = 1; for( int i = 0; i < n; i++ ){ for( int j = 0; j <= i; j++ ){ if ( n < count){ return 0; } cout << count << " "; count++; } cout << endl; } cout << endl; return 0; } /* 10 1 23 456 78910 */ ================================================ FILE: Patterns/pattern9.cpp ================================================ #include using namespace std; int main(){ int n; cin >> n; char spaces = ' '; for( int i = 1; i <= 5; i++ ){ for( int j = n - i; j > 0; j-- ){ cout << spaces; } for( int j = 1; j <= i; j++ ){ cout << i; } cout << endl; } return 0; } /* 5 1 22 333 4444 55555 */ ================================================ FILE: README.md ================================================ # Algo_Ds ## Overview: This repo is a conglomeration of algorithms for competitive programming, data structure, sorting and related areas. It currently features C/C++, Python and some Java implementations. It contains many advanced algorithms like greedy, graph traversal algorithms, including Dijkstra's algorithm and Floyd Warshal algorithm, and data structures like queues, stacks, and binary search trees. Use this repo to study or review your knowledge and don't forget to star and collaborate! ## Contents: ### Search Algorithms - Linear Search - binary search - Ternary search ### Sorting Algorithms - Bubble Sort - Selection Sort - Insertion sort - Merge sort - Quick sort - Radix sort - Bogo sort ### Shortest Path Algorithms - Dijkstra - Floyd Warshall ### Common Data Structures - heap - queue - stack - Array - Linked List ## Languages Used: - C/C++ - Python - Java - More to come ## How to contribute: Please comment your code thoroughly as to make it possible for anyone to understand. If possible, check your code using unit tests. Avoid all the bad implementations, make your code as clean as possible. After that, find the folder that fits the category of your code and submit a PR. *Star* this repo if the information here is useful to you. ### Please have a look at these : - [CONTRIBUTING.md](https://github.com/srbcheema1/Algo_Ds/blob/master/CONTRIBUTING.md) for quick quidelines - [STRUCTURE.md](https://github.com/srbcheema1/Algo_Ds/blob/master/STRUCTURE.md) for structure of directories ================================================ FILE: STL C++/STACK_with_Application/Evaluating Postfix Expression.c ================================================ #include #include #define MAX 200 int isoperator(char c){ return (c=='*' || c=='/' || c=='+' || c=='-'); } struct stack { int top; double a[MAX]; }s; void push(double c){ s.a[++s.top]=c; } double pop(){ return s.a[s.top--]; } double perform(double a, double b, char c){ if (c=='*') { return a*b; } else if (c=='+') { return a+b; } else if (c=='/') { return a/b; } else return a-b; } void post_infix(char a[],int l){ int i; for(i=0;i int j; struct temp{ char a[200]; int top; }; struct temp s; void push(char item){ s.a[++s.top]=item; } int isempty(){ return s.top==-1; } char pop(){ if(!isempty())return s.a[s.top--]; } int isoperator(char c){ if(c=='*'||c=='/'|| c=='+'|| c=='-')return 1; return 0; } int precedence(char c){ if(c=='+' || c=='-')return 1; else if(c=='*' || c=='/')return 2; else if(c=='^')return 3; return 0; } char *infix_postfix(char *p){ int i; j=0; char *p1 = (char *)malloc(100*sizeof(char)); for(i=0;p[i]!='\0';i++){ //printf("%d\n",j); if(isalpha(p[i]) || isdigit(p[i])){ p1[j++]=p[i]; } else if(isoperator(p[i])){//printf("%c\n",p[i]); while(!isempty() && /*s.a[s.top]!='(' &&*/ (precedence(p[i]) <= precedence(s.a[s.top]))){ p1[j++] = s.a[s.top]; pop(); } push(p[i]); } else if(p[i]=='(')push(p[i]); else if(p[i]==')'){ while(!isempty() && s.a[s.top]!='('){ p1[j++]=s.a[s.top]; pop(); } pop(); } } while(!isempty()){ //printf("%c ",s.a[s.top]); p1[j++]=s.a[s.top]; pop(); } //for(i=0;i #include #include #include using namespace std; int main(){ string str; printf("Enter a String"); cin>>str; int l = str.length(); stack s; for(int i=0;i struct stack{ char book_name[200][200]; int book_id[20]; int book_price[20]; int top; }; struct stack *p; int size; void push(){ if((p->top)==size-1){ printf("Overflow"); return; } p->top = p->top +1; //printf("p->top = %d",p->top); printf("\nEnter elements to be pushed : "); printf("\nEnter book name:"); scanf("%s",p->book_name[p->top]); printf("\nEnter book id:"); scanf("%d",&p->book_id[p->top]); printf("\nEnter book price:"); scanf("%d",&p->book_price[p->top]); } void pop(){ if(p->top==-1){ printf("Underflow\n"); } else{ p->top = p->top - 1; } } void peep(){ int i= p->top; printf("\nBook Name : %s",p->book_name[i]); printf("\nBook ID : %d",p->book_id[i]); printf("\nBook Price : %d",p->book_price[i]); printf("\n"); } void print(){ int x = p->top; if(x==-1){ printf("Nothing to be displayed\n"); } int i; for(i=0;i<=x;i++){ printf("\nBook Name : %s",p->book_name[i]); printf("\nBook ID : %d",p->book_id[i]); printf("\nBook Price : %d",p->book_price[i]); printf("\n"); } } int main(){ printf("********************************\t\n"); printf("Enter stack size : "); scanf("%d",&size); p = (struct stack*)malloc(sizeof(struct stack)); p->top = -1; while(1){ printf("\n1.Push\n2.Pop\n3.Peep\n4.Display all elements\n5.Exit\n"); int ch; scanf("%d",&ch); if(ch==1){ //p->top = p->top + 1; push(); } else if(ch==2){ pop(); } else if(ch==3){ peep(); } else if(ch==4){ print(); } else{ break; } } } ================================================ FILE: STL C++/sorting_a_vector.cpp ================================================ #include #include #include #include using namespace std; bool compare(int a,int b){ return a>b; } int main(){ vector v; for(int i=1;i<5;i++){ v.push_back(i); } int p; cin>>p; int d; cin>>d; v.insert(v.begin() + p,d); for(int i=0;i { private int max; private int top; private Object[] list; public Stack() { max = 512; top = 0; list = new Object[max]; } public Stack(int size) { max = size; top = 0; list = new Object[max]; } @SuppressWarnings("unchecked") public boolean isEmpty() { for(E t : (E[]) list) { if(t != null) { return false; } } return true; } @SuppressWarnings("unchecked") public E peek() { return (E) list[top]; } @SuppressWarnings("unchecked") public int size() { if(top == 0) { return 0; } int count = 0; for(E t : (E[]) list) { if(t != null) { count++; } } return count; } @SuppressWarnings("unchecked") public E pop() { if(isEmpty()) { throw new IndexOutOfBoundsException("This stack is empty; nothing to pop."); } E data = (E) list[top]; top = (top == 0 ? 0 : top - 1); return data; } public void push(E data) { if(top == max - 1) { list = Arrays.copyOf(list, list.length * 2); } top++; list[top] = data; } } ================================================ FILE: STL C++/stack/largestRectangleHistogram.cpp ================================================ #include #include #include using namespace std; int main() { int n; int a[]={6,2,5,4,5,1,6}; //input array n = sizeof(a)/sizeof(a[0]); int i,q; stack s; // stack to calculate max area i=0; int area,maxarea=INT_MIN; while(i #include "../linked_list/ll.hpp" using namespace std; template struct stackmp{ ll_node *top; int capacity; // number of elements the stack can contain int size; // number of elements in the stack stackmp(int cap) : capacity(cap),size(0) {} void push(T new_data){ if(size == capacity){ cout << "Stack is full! Cannot push new element" << endl; return; } ll_node *new_node = create_node(new_data); ll_node *temp_node = this->top; new_node->next = temp_node; this->top = new_node; size++; } void print(){ ll_node *temp_node = this->top; if(size == 0){ cout << "Stack is empty" << endl; return; } cout << "Printing stack:" << endl; for(int i=0;isize;i++){ cout << temp_node->data << ' '; temp_node = temp_node->next; } cout << endl; } T pop(){ if(size == 0){ cout << "Stack is empty, can't pop" << endl; return '\0'; } T data = this->top->data; this->top = this->top->next; size--; return data; } T peek(){ return this->top->data; } }; template int get_size(stackmp *s){ return s->size; } template int get_capacity(stackmp *s){ return s->capacity; } ================================================ FILE: STL C++/using_map.cpp ================================================ map m; map :: iterator it; m[1] = 2; m[2] = 3; m[6] = 4; m[5] = 5; it = m.find(5); if (it != m.end()) cout << "5 is present as key" << endl; else cout << "5 is not present as key" << endl; /* Output: 5 is present as key */ it = m.find(3); if (it != m.end()) cout << "3 is present as key" << endl; else cout << "3 is not present as key" << endl; /* Output: 3 is not present as key */ ================================================ FILE: STL C++/using_set.cpp ================================================ set s; s.insert(5); // 5 is inserted into set s.insert(2); // 2 is inserted into set s.insert(3); // 3 is inserted into set s.insert(2); // no new element inserted set :: iterator it; it = s.find(5) if (it != s.end()) cout << "Element is present in set" << endl; else cout << "Element is not present in set" << endl; /* Output : Element is present in set */ it = s.find(9) if (it != s.end()) cout << "Element is present in set" << endl; else cout << "Element is not present in set" << endl; /* Output : Element is not present in set */ ================================================ FILE: STRUCTURE.md ================================================ # Directory Structure Example ## please maintain the directory structure as in this example - Data structures - stack - DESCRIPTION.md - Python - Applications - Cpp - Applications - ques - Java - Sorting Algorithms - bubblesort - DESCRIPTION.md - Python - Applications - ques - Cpp - ques - Java - Graph - Dijakstra - DESCRIPTION.md - Cpp - Applications - ques - java - Python ================================================ FILE: Searching Algorithms/Bogo_sort.cpp ================================================ // C Program to Implement BogoSort in an Integer Array #include #include #define size 7 /* Function Prototypes */ int is_sorted(int *, int); void shuffle(int *, int); void bogosort(int *, int); int main() { int numbers[size]; int i; printf("Enter the elements of array:"); for (i = 0; i < size;i++) { scanf("%d", &numbers[i]); } bogosort(numbers, size); printf("The array after sorting is:"); for (i = 0;i < size;i++) { printf("%d\n", numbers[i]); } printf("\n"); } /* Code to check if the array is sorted or not */ int is_sorted(int *a, int n) { while (--n >= 1) { if (a[n] < a[n - 1]) { return 0; } } return 1; } /* Code to shuffle the array elements */ void shuffle(int *a, int n) { int i, t, temp; for (i = 0;i < n;i++) { t = a[i]; temp = rand() % n; /* Shuffles the given array using Random function */ a[i] = a[temp]; a[temp] = t; } } /* Code to check if the array is sorted or not and if not sorted calls the shuffle function to shuffle the array elements */ void bogosort(int *a, int n) { while (!is_sorted(a, n)) { shuffle(a, n); } } ================================================ FILE: Searching Algorithms/C:C++/Binary_Search.cpp ================================================ //Time Complexity: O(logn) #include using namespace std; int main() { int a[100],n,i,beg,end,mid,item; cout<<"Enter No. of Elements= "; cin>>n; cout<<"Enter Elements in Sorted Order=\n"; for(i=1;i<=n;i++) cin>>a[i]; cout<<"Enter Item you want to Search= "; cin>>item; beg=1; end=n; mid=(beg+end)/2; while(beg<=end && a[mid]!=item) { if(a[mid] #include void main() { clrscr(); int n, i, arr[50], search, first, last, middle; cout<<"Enter total number of elements :"; cin>>n; cout<<"Enter "<>arr[i]; } cout<<"Enter a number to find :"; cin>>search; first = 0; last = n-1; middle = (first+last)/2; while (first <= last) { if(arr[middle] < search) { first = middle + 1; } else if(arr[middle] == search) { cout< last) { cout<<"Not found! "< using namespace std; int main(){ int N,x; cin>>N; int arr[N]; for(int i=0;i>arr[i]; } //Taking the number to be searched. cin>>x; //Getting first and last index of the array. int lo = 0, hi = (N - 1); int flag=0; //If the element is present in the sorted array, it must be in the range defined by 'hi' and 'lo'. while (lo <= hi && x >= arr[lo] && x <= arr[hi]) { // The idea of formula is to return higher value of pos // when element to be searched is closer to arr[hi], and // smaller value when closer to arr[lo] int pos = lo + (((double)(hi-lo) / (arr[hi]-arr[lo]))*(x - arr[lo])); if (arr[pos] == x) { cout< #include using namespace std; // If x is present in arr[0..n-1], then returns // index of it, else returns -1. long long int interpolation_search(int arr[],int n,int x) { int low=0,high=n-1; //Beacuse the array is sorted, element has to be present in range //made by corner i.e low and high while ((low<=high) and (x>=arr[low]) and (x<=arr[high])) { // Now we will enquire the position keeping in mind the uniform distribution in mind int pos=low+(((double)(high-low)/(arr[high]-arr[low]))*(x-arr[low])); // If x is larger, x is in upper part if (arr[pos]x) high=pos-1; // Target found else return pos; } return -1; } int main() { int n; cout<<"Please enter the number of elements in array\n"; cin>>n; int arr[n]; cout<<"Please enter "<>arr[i]; } // For Interpolation search we need to sort the array sort(arr,arr+n); cout<<"Enter the number you want to search\n"; int x;// Target number cin>>x; int index=interpolation_search(arr, n, x); // If element was found if (index != -1) cout<<"Element found at index "< using namespace std; int jumpSearch(int arr[], int x, int n) { // Finding block size to be jumped int step = sqrt(n); // Finding the block where element is // present (if it is present) int prev = 0; while (arr[min(step, n)-1] < x) { prev = step; step += sqrt(n); if (prev >= n) return -1; } // Doing a linear search for x in block // beginning with prev. while (arr[prev] < x) { prev++; // If we reached next block or end of // array, element is not present. if (prev == min(step, n)) return -1; } // If element is found if (arr[prev] == x) return prev; return -1; } // Driver program to test function int main() { int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 }; int x = 55; int n = sizeof(arr) / sizeof(arr[0]); // Find the index of 'x' using Jump Search int index = jumpSearch(arr, x, n); // Print the index where 'x' is located cout << "\nNumber " << x << " is at index " << index; return 0; } ================================================ FILE: Searching Algorithms/C:C++/Liear_search.cpp ================================================ /* C++ Program - Linear Search */ #include #include void main() { clrscr(); int arr[10], i, num, n, c=0, pos; cout<<"Enter the array size : "; cin>>n; cout<<"Enter Array Elements : "; for(i=0; i>arr[i]; } cout<<"Enter the number to be search : "; cin>>num; for(i=0; i #include using namespace std; /* int findMedian() -> Returns the median of the input array. int partition() -> The partition work is done by this function. int kthSmallest() -> The recursive function that performs the major calculations of finding the kthSmallest element only on the condition that the value of k is less than the size of the array produced after after every recursive cycle. int main() -> Driver Function. */ /* predefined stuff -> sort() swap() INT_MAX */ int findMedian(int arr[], int size_of_array) { sort(arr, arr+size_of_array); // Sort the array return arr[size_of_array/2]; // Return middle element } int partition(int arr[], int low, int high, int variable_to_be_found) { // Search for variable_to_find in arr[low..high] and move it to end int i; for (i=low; i 0 && k <= high - low + 1) { int n = high-low+1; // Number of elements in arr[low..high] // Divide arr[] in groups of size 5, calculate median // of every group and store it in median[] array. int i, median[(n+4)/5]; // There will be floor((n+4)/5) groups; for (i=0; i k-1) // If position is more, recur for left return kthSmallest(arr, low, pos-1, k); // Else recur for right subarray return kthSmallest(arr, pos+1, high, k-pos+l-1); } // If k is more than number of elements in array return INT_MAX; } // It searches for x in arr[l..r], and partitions the array // around x. int main() { int arr[] = {12, 3, 5, 7, 4, 19, 26}; int n = sizeof(arr)/sizeof(arr[0]), k = 3; cout << "K'th smallest element is " << kthSmallest(arr, 0, n-1, k); return 0; } ================================================ FILE: Searching Algorithms/C:C++/Selection_sort.cpp ================================================ /* C++ Program - Selection Sort */ #include #include void main() { clrscr(); int size, arr[50], i, j, temp; cout<<"Enter Array Size : "; cin>>size; cout<<"Enter Array Elements : "; for(i=0; i>arr[i]; } cout<<"Sorting array using selection sort...\n"; for(i=0; iarr[j]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } cout<<"Now the Array after sorting is :\n"; for(i=0; i using namespace std; #define s 12 //I gave space in the array as 12,but you can give the number you want. int ternary_search (int v[],int n, int left, int right, int x); int main() { int v[s]; short x; for(int i = 1; i <= s; i++) { v[i-1] = i; } cout << "Enter number for research:\n"; cin >> x; int left = s/3; int right = (s/3)*2; if(ternary_search(v,s,left-1,right-1,x) == -1) { cout<<"Number does not exist in array.\n"; } else { cout<<"The index is:"< n-1 || left > right) { return -1; } if(x == v[left]) { return left; } if(x == v[right]) { return right; } // Update the two index left and right if the element is not found. if(x < v[left]) { return ternary_search(v,n,left-1,right,x); } if (x > v[left] && x < v[right]) { return ternary_search(v,n,left+1,right-1,x); } if(x > v[right]) { return ternary_search(v,n,left,right+1,x); } } ================================================ FILE: Searching Algorithms/C:C++/b_search.cpp ================================================ #include using namespace std; int b_search(int a[],int l,int u,int s) { int m=(l+u)/2; if(l>=u) return -1; if(a[m]>s) return b_search(a,l,m-1,s); else if(a[m] using namespace std; int _fibonacci_search(int n, int arr[], int x) { /*Assuming the Input array is sorted*/ /*Fibonacci Searching algorithm */ /* Initialize fibonacci numbers */ int fibMMm2 = 0; // (m-2)'th Fibonacci No. int fibMMm1 = 1; // (m-1)'th Fibonacci No. int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci /* fibM is going to store the smallest Fibonacci Number greater than or equal to n */ while (fibM < n) { fibMMm2 = fibMMm1; fibMMm1 = fibM; fibM = fibMMm2 + fibMMm1; } // Marks the eliminated range from front int offset = -1; /* while there are elements to be inspected. Note that we compare arr[fibMm2] with x. When fibM becomes 1, fibMm2 becomes 0 */ while (fibM > 1) { // Check if fibMm2 is a valid location int index = min(offset+fibMMm2, n-1); /* If x is greater than the value at index fibMm2, cut the subarray array from offset to i */ if (arr[index] < x) { fibM = fibMMm1; fibMMm1 = fibMMm2; fibMMm2 = fibM - fibMMm1; offset = index; } /* If x is greater than the value at index fibMm2, cut the subarray after i+1 */ else if (arr[index] > x) { fibM = fibMMm2; fibMMm1 = fibMMm1 - fibMMm2; fibMMm2 = fibM - fibMMm1; } /* element found. return index */ else return index; } /* comparing the last element with x */ if(fibMMm1 && arr[offset+1]==x)return offset+1; /*element not found. return -1 */ return -1; } ================================================ FILE: Searching Algorithms/C:C++/seaching algorithms [rename]/binary_search.cpp ================================================ /* This code illustrates a recursive implementation of binary search in a sorted array. */ #include using namespace std; int binarySearch(int array[], int left, int right, int search) { if (right >= 1) { int mid = ((right-1)-left)/2; if (array[mid] == search) //Checks if the element is present at the middle return mid; if (array[mid] > search) //Since this is a sorted array, therefore if value of element is less than middle return binarySearch(array, left, mid-1, search); //element, it lies in left part of array. Recursively searching again the left part. return binarySearch(array, mid+1, right, search); //If element was neither in Middle nor in left part, it can only be in the right. } return -1; //If element was not found, return -1 } int main() { int array [] = {1,2,3,4,5,6,7,8,9,10}, search = 5, position; int size = sizeof(array)/ sizeof(array[0]); position = binarySearch(array, 0, size-1, search); //here left index for binary search is sent as 0, while right as size - 1 if(position == -1) //therefore for an array of size 10, 9 will be sent (since arrays are 0 indexed) cout<<"Element is not present in array"; else cout<<"Element is present at "< using namespace std; /* * return position of last elem less than or equal to num * best is best position till now * every elem is atleast greater than 0th elem (-1) so initially best is 0 */ int binary_search(vector &vec,int l,int r,int num,int best){ if(r>n; vector vec(n+1); vec[0]=-1; for(int i=1;i<=n;i++){ cin>>vec[i]; } sort(vec.begin()+1,vec.end()); int q;//querries cin>>q; while(q--){ int num; cin>>num; cout< using namespace std; /* * return position of last elem less than or equal to num * best is best position till now */ int binary_search(vector &vec,int l,int r,int num,int best){ if(rnum){//out of reach ... go back return binary_search(vec,l,m-1,num,best); } } /* * program to find first occurance of num in sorted array * if not there print -1 */ int main(){ int n; cin>>n; vector vec(n+1); vec[0]=-1; for(int i=1;i<=n;i++){ cin>>vec[i]; } sort(vec.begin()+1,vec.end()); int q;//querries cin>>q; while(q--){ int num; cin>>num; cout< using namespace std; /* * return position of elem just less than num * best is best position till now * every elem is atleast greater than 0th elem (-1) so initially best is 0 */ int binary_search(vector &vec,int l,int r,int num,int best){ if(r>n; vector vec(n+1); vec[0]=-1; for(int i=1;i<=n;i++){ cin>>vec[i]; } sort(vec.begin()+1,vec.end()); int q;//querries cin>>q; while(q--){ int num; cin>>num; cout< using namespace std; /* * return position of num in sorted array * if not there then return -1 */ int binary_search(vector &vec, int l, int r, int num){ if(rnum){ return binary_search(vec,l,m-1,num); } else{ return m; } } int main(){ int n; cin>>n; vector vec(n+1); for(int i=1;i<=n;i++){ cin>>vec[i]; } sort(vec.begin()+1,vec.end()); int q;//num of querries cin>>q; while(q--){ int num; cin>>num; cout< using namespace std; int arr[100002]; int np,nc; int ans; int find(int l,int r){ int m=(l+r)/2; int cnt=1,last=1; for(int i=2;i<=np;i++){ if(arr[i]-arr[last]>=m){ cnt++; last=i; } } if(l==r){ if(m>ans && cnt>=nc)ans=m; return ans; } if(cntans)ans=m; return find(m+1,r); } } int main(){ int t; cin>>t; while(t--){ ans=1; cin>>np>>nc; for(int i=1;i<=np;i++) cin>>arr[i]; sort(arr+1,arr+np+1); cout< #include using namespace std; int jumpSearch(int array[], int search, int size) { int step = sqrt(size); //Best Jump block size is sqrt(size) [Reference: http://www.geeksforgeeks.org/jump-search/] int location = 0; //Store nearest found result while searching while (array[step-1] < search) //search for the element by jumping blocks while the current element is less that the one we { //are searching for. location = step; step += sqrt(size); if (location >= size) //If element not found till the end of array, return -1 return -1; } while (array[location] < search) //If array element was greater than the element we are searching for, do a linear { //search from last known location. location++; if (location == step) return -1; } if (array[location] == search) return location; return -1; } int main() { int array [] = {1,2,3,4,5,6,7,8,9,10}, search = 5, position; int size = sizeof(array)/ sizeof(array[0]); position = jumpSearch(array, search, size); if(position == -1) cout<<"Element is not present in array"; else cout<<"Element is present at "< using namespace std; int main() { int array [] = {1,2,3,4,5,6,7,8,9,10}, search = 5, position; for(position = 0 ; position < 10 ; position++) if(search == array[position]) cout< /* * Part of Cosmos by OpenGenus Foundation */ using namespace std; int ternarySearch(int arr[],int l,int r, int x){ if(r>=l){ int mid1 = l + (r-l)/3; int mid2 = r - (r-l)/3; if(arr[mid1] == x) return mid1; /* In this search, after each iteration it neglects (1/3)rd part of the array and repeats the same operations on the remaining 2/3rd part of array */ if(arr[mid2] == x) return mid2; if(xarr[mid2]) return ternarySearch(arr,mid2+1,r,x); else return ternarySearch(arr,mid1+1,mid2-1,x); } return -1; // if x is not found in array arr } int main(){ int arr[] = {1, 2, 3, 5}; int size = sizeof(arr)/ sizeof(arr[0]); int find = 3; cout<<"Position of "< int ternarySearch(int arr[],int l,int r, int x){ if(r>=l){ int mid1 = l + (r-l)/3; int mid2 = r - (r-l)/3; if(arr[mid1] == x) return mid1; /* In this search, after each iteration it neglects (1/3)rd part of the array and repeats the same operations on the remaining 2/3rd part of array */ if(arr[mid2] == x) return mid2; if(xarr[mid2]) return ternarySearch(arr,mid2+1,r,x); else return ternarySearch(arr,mid1+1,mid2-1,x); } return -1; // if x is not found in array arr } int main(){ int arr[] = {1, 2, 3, 5}; int size = sizeof(arr)/ sizeof(arr[0]); int find = 3; printf("Position of %d is %d",find,ternarySearch(arr,0,size-1,find)); return 0; } ================================================ FILE: Searching Algorithms/Java/TODO ================================================ * Write all the search algorithms in different classes. * Make one driving program containing the main to access all the search classes. * Use java packages. To continue adding the search algorithm: * Make a class name of that algorithm name. * include in the package asset as: package asset; * write the .java files in algos directory. * Compile the .java files as: `javac -d ../ `. * Check if the .class file get added in the asset folder. * To run these class files, include: `import asset.` in the **driving.java** (the driving program). ================================================ FILE: Searching Algorithms/Java/algos/BinarySearch.java ================================================ package asset; public class BinarySearch{ public static int binarySearch(int [] arr, int key, int low, int high) { int index = Integer.MAX_VALUE; while (low <= high) { int mid = (low + high) / 2; if(arr[mid] < key) { low = mid + 1; } else if (arr[mid] > key) { high = mid - 1; } else if (arr[mid] == key) { index = mid; break; } else return -1; } return index; } } ================================================ FILE: Searching Algorithms/Java/algos/LinearSearch.java ================================================ package asset; public class LinearSearch{ public static int linearSearch(int [] arr, int key) { int size = arr.length; for(int i = 0; i < size; i++) { if(arr[i] == key) { return i; } } return -1; } } ================================================ FILE: Searching Algorithms/Java/driving.java ================================================ package pkg; public class LinearSearch{ public static int linearSearch(int [] arr, int key) { int size = arr.length; for(int i = 0; i < size; i++) { if(arr[i] == key) { return i; } } return -1; } public static void main(String a[]) { int[] arr1 = {1, 4, 12, 435, 76}; int searchKey = 4; System.out.println("Key " + searchKey + " found at index: " + linearSearch(arr1, searchKey)); } } ================================================ FILE: Searching Algorithms/Python/binarysearch.py ================================================ def binary_search(item_list,item): first = 0 last = len(item_list)-1 found = False while( first<=last and not found): mid = (first + last)//2 if item_list[mid] == item : found = True else: if item < item_list[mid]: last = mid - 1 else: first = mid + 1 return found print(binary_search([1,2,3,5,8], 6)) print(binary_search([1,2,3,5,8], 5)) """ TIME COMPLEXITY Best-case performance O(1) Average performance O(log n) Worst-case space complexity O(1) SPACE COMPLEXITY Best-case performance O(1) Average performance O(log n) Worst-case space complexity O(1) """ ================================================ FILE: Searching Algorithms/Python/bst.py ================================================ #Time Complexity : O(height) # Python program to demonstrate insert operation in binary search tree # A utility class that represents an individual node in a BST class Node: def __init__(self,key): self.left = None self.right = None self.val = key # A utility function to insert a new node with the given key def insert(root,node): if root is None: root = node else: if root.val < node.val: if root.right is None: root.right = node else: insert(root.right, node) else: if root.left is None: root.left = node else: insert(root.left, node) # A utility function to do inorder tree traversal def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) # Driver program to test the above functions # Let us create the following BST # 50 # / \ # 30 70 # / \ / \ # 20 40 60 80 r = Node(50) insert(r,Node(30)) insert(r,Node(20)) insert(r,Node(40)) insert(r,Node(70)) insert(r,Node(60)) insert(r,Node(80)) insert(r,Node(100)) insert(r,Node(200)) # Print inoder traversal of the BST inorder(r) ================================================ FILE: Segment Trees/ADA/README.md ================================================ # Compile and run an ADA program gnatmake nome_do_programa.adb ./nome_do_programa or gcc-4.9 -c nome_do_programa.adb gnatbind -x nome_do_programa.adb gnatlink nome_do_programa.adb ./nome_do_programa # Definition Segment tree can be used to do preprocessing and query in moderate time. With segment tree, preprocessing time is O(n) and time to for range minimum query is O(Logn). The extra space required is O(n) to store the segment tree. Representation of Segment trees * Leaf Nodes are the elements of the input array. * Each internal node represents minimum of all leaves under it. An array representation of tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, right child at 2*i+2 and the parent is at floor of (i - 1)/2. ## Construction of Segment Tree from given array We start with a segment arr[0 . . . n-1]. and every time we divide the current segment into two halves(if it has not yet become a segment of length 1), and then call the same procedure on both halves, and for each such segment, we store the minimum value in a segment tree node. All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree because we always divide segments in two halves at every level. Since the constructed tree is always full binary tree with n leaves, there will be n-1 internal nodes. So total number of nodes will be 2*n – 1. [Credits](http://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/) ================================================ FILE: Segment Trees/ADA/segmentree.adb ================================================ with Ada.Integer_Text_IO, Ada.Text_IO; use Ada.Integer_Text_IO, Ada.Text_IO; --To compile an ADA program you have to install gnat on your computer -- sudo apt-get install gnat-5 -- gnatmake segmentree.adb -- ./segmentree --or -- gcc-4.9 -c segmentree.adb -- gnatbind -x segmentree.adb -- gnatlink segmentree.adb -- ./segmentree procedure segmentree is INT_MAX: constant integer := 999999; MAXN : constant integer := 100005; v : array(0..MAXN) of integer; tree: array(0..4*MAXN) of integer; n : integer; q : integer; a : integer; b : integer; c : integer; function min(a: integer; b: integer) return integer is begin if a < b then return a; else return b; end if; end min; procedure build(node: integer; l: integer; r: integer) is mid: integer; begin mid := (l + r)/2; if l = r then tree(node) := v(l); return; end if; build(2 * node, l, mid); build(2*node+1,mid+1,r); tree(node) := min( tree(2*node), tree(2*node + 1)); end build; -- Update procedure procedure update(node: integer; l: integer; r: integer; pos: integer; val: integer) is mid: integer := (l + r)/2; begin if l > pos or r < pos or l > r then return; end if; if(l = r) then tree(node) := val; return; end if; if pos <= mid then update(2*node,l,mid,pos,val); else update(2*node+1,mid+1,r,pos,val); end if; tree(node) := min( tree(2*node), tree(2*node + 1)); end update; -- Query function function query(node : integer; l: integer; r: integer; x: integer; y: integer) return integer is mid: integer := (l + r)/2; p1: integer; p2: integer; begin if l > r or l > y or r < x then return INT_MAX; end if; if x <= l and r <= y then return tree(node); end if; p1 := query(2*node,l,mid,x,y); p2 := query(2*node+1,mid+1,r,x,y); if p1 = INT_MAX then return p2; end if; if p2 = INT_MAX then return p1; end if; return min(p1, p2); end query; begin Put_Line("Input the array range"); Get(n); Put_Line("Input the values"); for i in 1..n loop Get(v(i)); end loop; build(1,0,n-1); Put_Line("Input the number of operations"); Get(q); while q > 0 loop Put_Line("Input 0 to query and 1 to update"); Get(a); Put_Line("Input the STARTING index of the query range"); Get(b); Put_Line("Input the ENDING index of the query range"); Get(c); if a = 0 then Put_Line("Minimum value of the given range"); Put(query(1,1,n,b,c)); Put_Line(""); elsif a = 1 then update(1,1,n,b,c); else Put_Line("Invalid Operation"); q := q + 1; end if; q := q - 1; end loop; end segmentree; ================================================ FILE: Segment Trees/C++/RangeMinimumQuery.cpp ================================================ //Following code calculates the minimum value in the range l to r #include using namespace std; int rmq(int *st, int n, int ss, int se, int qs, int qe, int si) { if(qs < 0 || qs > qe || qe >= n) { return -1; } if(ss >= qs && se <= qe) { //segment range fully within query range return st[si]; } if(se < qs || ss > qe) {//segment range has not intersection return INT_MAX; } int mid = (ss + se)/2; return min(rmq(st, n, ss ,mid, qs, qe, 2*si+1), rmq(st, n, mid+1 ,se, qs, qe, 2*si+2)); } int buildTree(int a[], int n, int ss, int se, int *st, int si) { if(ss == se) { st[si] = a[ss]; return a[ss]; } int mid = (ss + se)/2; st[si] = min(buildTree(a,n,ss, mid,st, 2*si + 1), buildTree(a, n, mid+1, se,st,2*si+2)); return st[si]; } int *constructTree(int a[], int n) { int x = (int)(ceil(log2(n))); int max_size = 2*(int)pow(2,x) - 1; int *st = new int[max_size]; buildTree(a, n, 0, n-1, st, 0); return st; } int main() { int n; cin>>n; int a[n], i; for(i=0;i>a[i]; } int *st = constructTree(a, n); int qs, qe; cin>>qs>>qe; cout< using namespace std; int getSum(int *st, int n, int ss, int se, int qs, int qe, int si) { if(qs < 0 || qs > qe || qe >= n) { return -1; } if(ss >= qs && se <= qe) { //segment range fully within query range return st[si]; } if(se < qs || ss > qe) {//segment range has not intersection return 0; } int mid = (ss + se)/2; return getSum(st, n, ss ,mid, qs, qe, 2*si+1) + getSum(st, n, mid+1 ,se, qs, qe, 2*si+2); } void UpdateUtil(int *st, int ss, int se, int i, int diff, int si) { if(i < ss || i > se) { return; } st[si] += diff; if(ss != se) { int mid = (ss + se)/2; UpdateUtil(st, ss, mid, i, diff, 2*si+1); UpdateUtil(st, mid+1, se, i, diff, 2*si+2); } } void UpdateValue(int a[], int *st, int n, int i, int new_value) { if(i < 0 || i > n -1) { return; } int diff = new_value - a[i]; a[i] = new_value; UpdateUtil(st, 0, n-1, i, diff, 0); } int buildTree(int a[], int n, int ss, int se, int *st, int si) { if(ss == se) { st[si] = a[ss]; return a[ss]; } int mid = (ss + se)/2; st[si] = buildTree(a, n, ss, mid,st, 2*si + 1) + buildTree(a, n, mid+1, se,st,2*si+2); return st[si]; } int *constructTree(int a[], int n) { int x = (int)(ceil(log2(n))); int max_size = 2*(int)pow(2,x) - 1; int *st = new int[max_size]; buildTree(a, n, 0, n-1, st, 0); return st; } int main() { int n; cin>>n; int a[n], i; for(i=0;i>a[i]; } int *st = constructTree(a, n); int qs, qe; cin>>qs>>qe; cout<>qs>>qe; cout< index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum. us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */ void updateRangeUtil(int si, int ss, int se, int us, int ue, int diff) { // If lazy value is non-zero for current node of segment // tree, then there are some pending updates. So we need // to make sure that the pending updates are done before // making new updates. Because this value may be used by // parent after recursive calls (See last line of this // function) if (lazy[si] != 0) { // Make pending updates using value stored in lazy // nodes tree[si] += (se - ss + 1) * lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // We can postpone updating children we don't // need their new values now. // Since we are not yet updating children of si, // we need to set lazy flags for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } // Set the lazy value for current node as 0 as it // has been updated lazy[si] = 0; } // out of range if (ss > se || ss > ue || se < us) return; // Current segment is fully in range if (ss >= us && se <= ue) { // Add the difference to current node tree[si] += (se - ss + 1) * diff; // same logic for checking leaf node or not if (ss != se) { // This is where we store values in lazy nodes, // rather than updating the segment tree itelf // Since we don't need these updated values now // we postpone updates by storing values in lazy[] lazy[si * 2 + 1] += diff; lazy[si * 2 + 2] += diff; } return; } // If not completely in rang, but overlaps, recur for // children, int mid = (ss + se) / 2; updateRangeUtil(si * 2 + 1, ss, mid, us, ue, diff); updateRangeUtil(si * 2 + 2, mid + 1, se, us, ue, diff); // And use the result of children calls to update this // node tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } // Function to update a range of values in segment // tree /* us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue */ void updateRange(int n, int us, int ue, int diff) { updateRangeUtil(0, 0, n - 1, us, ue, diff); } /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. si --> Index of current node in the segment tree. Initially 0 is passed as root is always at' index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., tree[si] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int ss, int se, int qs, int qe, int si) { // If lazy flag is set for current node of segment tree, // then there are some pending updates. So we need to // make sure that the pending updates are done before // processing the sub sum query if (lazy[si] != 0) { // Make pending updates to this node. Note that this // node represents sum of elements in arr[ss..se] and // all these elements must be increased by lazy[si] tree[si] += (se - ss + 1) * lazy[si]; // checking if it is not leaf node because if // it is leaf node then we cannot go further if (ss != se) { // Since we are not yet updating children os si, // we need to set lazy values for the children lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } // unset the lazy value for current node as it has // been updated lazy[si] = 0; } // Out of range if (ss > se || ss > qe || se < qs) return 0; // At this point sure, pending lazy updates are done // for current node. So we can return value (same as // was for query in our previous post) // If this segment lies in range if (ss >= qs && se <= qe) return tree[si]; // If a part of this segment overlaps with the given // range int mid = (ss + se) / 2; return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } // Return sum of elements in range from index qs (query // start) to qe (query end). It mainly uses getSumUtil() int getSum(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println("Invalid Input"); return -1; } return getSumUtil(0, n - 1, qs, qe, 0); } /* A recursive function that constructs Segment Tree for array[ss..se]. si is index of current node in segment tree st. */ void constructSTUtil(int arr[], int ss, int se, int si) { // out of range as ss can never be greater than se if (ss > se) return; /* If there is one element in array, store it in current node of segment tree and return */ if (ss == se) { tree[si] = arr[ss]; return; } /* If there are more than one elements, then recur for left and right subtrees and store the sum of values in this node */ int mid = (ss + se) / 2; constructSTUtil(arr, ss, mid, si * 2 + 1); constructSTUtil(arr, mid + 1, se, si * 2 + 2); tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ void constructST(int arr[], int n) { // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, 0); } // Driver program to test above functions public static void main(String args[]) { int arr[] = {1, 3, 5, 7, 9, 11}; int n = arr.length; LazySegmentTree tree = new LazySegmentTree(); // Build segment tree from given array tree.constructST(arr, n); // Print sum of values in array from index 1 to 3 System.out.println("Sum of values in given range = " + tree.getSum(n, 1, 3)); // Add 10 to all nodes at indexes from 1 to 5. tree.updateRange(n, 1, 5, 10); // Find sum after the value is updated System.out.println("Updated sum of values in given range = " + tree.getSum(n, 1, 3)); } } ================================================ FILE: Sorting Algorithms/C:C++/Counting_Sort.cpp ================================================ #include using namespace std; int main() { int N,x; cin>>N; int A[N]; //The elements of the array must not exceed the size of the array. //This algo is ideally suited for numbers within a range with repetitions. for(int i=0;i>A[i]; } // Find the maximum value in A[] int K = 0; for(int i=0; i #include void main() { clrscr(); int size, arr[50], i, j, temp; cout<<"Enter Array Size : "; cin>>size; cout<<"Enter Array Elements : "; for(i=0; i>arr[i]; } cout<<"Sorting array using selection sort ... \n"; for(i=1; i=0)) { arr[j+1]=arr[j]; j=j-1; } arr[j+1]=temp; } cout<<"Array after sorting : \n"; for(i=0; i using namespace std; // A function to merge the two half into a sorted data. void Merge(int *a, int low, int high, int mid) { // We have low to mid and mid+1 to high already sorted. int i, j, k, temp[high-low+1]; i = low; k = 0; j = mid + 1; // Merge the two parts into temp[]. while (i <= mid && j <= high) { if (a[i] < a[j]) { temp[k] = a[i]; k++; i++; } else { temp[k] = a[j]; k++; j++; } } // Insert all the remaining values from i to mid into temp[]. while (i <= mid) { temp[k] = a[i]; k++; i++; } // Insert all the remaining values from j to high into temp[]. while (j <= high) { temp[k] = a[j]; k++; j++; } // Assign sorted data stored in temp[] to a[]. for (i = low; i <= high; i++) { a[i] = temp[i-low]; } } // A function to split array into two parts. void MergeSort(int *a, int low, int high) { int mid; if (low < high) { mid=(low+high)/2; // Split the data into two half. MergeSort(a, low, mid); MergeSort(a, mid+1, high); // Merge them to get sorted output. Merge(a, low, high, mid); } } int main() { int n, i; cout<<"\nEnter the number of data element to be sorted: "; cin>>n; int arr[n]; for(i = 0; i < n; i++) { cout<<"Enter element "<>arr[i]; } MergeSort(arr, 0, n-1); // Printing the sorted data. cout<<"\nSorted Data "; for (i = 0; i < n; i++) cout<<"->"< void swap (int a[], int left, int right) { int temp; temp=a[left]; a[left]=a[right]; a[right]=temp; }//end swap void quicksort( int a[], int low, int high ) { int pivot; // Termination condition! if ( high > low ) { pivot = partition( a, low, high ); quicksort( a, low, pivot-1 ); quicksort( a, pivot+1, high ); } } //end quicksort int partition( int a[], int low, int high ) { int left, right; int pivot_item; int pivot = left = low; pivot_item = a[low]; right = high; while ( left < right ) { // Move left while item < pivot while( a[left] <= pivot_item ) left++; // Move right while item > pivot while( a[right] > pivot_item ) right--; if ( left < right ) swap(a,left,right); } // right is final position for the pivot a[low] = a[right]; a[right] = pivot_item; return right; }//end partition // void quicksort(int a[], int, int); void printarray(int a[], int); int main() { int a[50], i, n; printf("nEnter no. of elements: "); scanf("%d", &n); printf("nEnter the elements: n"); for (i=0; i using namespace std; void quick_sort(int[],int,int); int partition(int[],int,int); int main() { int a[50],n,i; cout<<"How many elements?"; cin>>n; cout<<"\nEnter array elements:"; for(i=0;i>a[i]; quick_sort(a,0,n-1); cout<<"\nArray after sorting:"; for(i=0;i #include #define MAX 10 class radixsort{ int arr[MAX],n; public: void getdata(); void showdata(); void sortLogic(); }; void radixsort :: getdata(){ cout<<"How many elements you require : "; cin>>n; for(int i=0;i>arr[i]; } void radixsort :: showdata(){ cout<<"\n--Display--\n"; for(int i=0;i largest) largest=arr[i]; } while(largest > 0) //Find number of digits in largest number { no_of_passes++; largest /= 10; } for(pass_no=0; pass_no < no_of_passes; pass_no++){ for(k=0; k<10; k++) buck_count[k]=0; //Initialize bucket countfor(i=0;i using namespace std; int main(){ int a[10]; ///Creates an array of 10 integers int n,key; cin>>n; ///Read n numbers; for(int i=0;i>a[i]; } ///Bubble Sort - Optimised for(int times=0;timesa[j+1]){ ///Inbuild Swap Fn swap(a[j],a[j+1]); swaps++; } } if(swaps==0){ break; } } ///Print for(int i=0;i #include void main() { clrscr(); int n, i, arr[50], j, temp; cout<<"Enter total number of elements :"; cin>>n; cout<<"Enter "<>arr[i]; } cout<<"Sorting array using bubble sort technique...\n"; for(i=0; i<(n-1); i++) { for(j=0; j<(n-i-1); j++) { if(arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } cout<<"Elements sorted successfully..!!\n"; cout<<"Sorted list in ascending order :\n"; for(i=0; i #define SIZE 10 void bucketSort(int a[], int n) { int i, j, k, buckets[SIZE]; for(i = 0; i < SIZE; ++i) buckets[i] = 0; for(i = 0; i < n; ++i) ++buckets[a[i]]; for(i = 0, j = 0; j < SIZE; ++j) for(k = buckets[j]; k > 0; --k) a[i++] = j; } int main() { int i, a[] = {3, 6, 5, 1, 8, 4, 3, 1}, n = 8; printf("Before sorting:\n"); for(i = 0; i < n; ++i) printf("%d ", a[i]); bucketSort(a, n); printf("\n\nAfter sorting:\n"); for(i = 0; i < n; ++i) printf("%d ", a[i]); return 0; } ================================================ FILE: Sorting Algorithms/C:C++/heapSort.c ================================================ #include int heapify(int* a, int i, int n) { int j=(2*i+1),k=(2*i+2),x; if(j<=n) { if(k<=n) if(a[k]>a[j]) j=k; if(a[j]>a[i]) { x=a[j]; a[j]=a[i]; a[i]=x; heapify(a,j,n); } } return 0; } int buildheap(int *a, int n) { int i; for(i=n/2;i>=0;i--) heapify(a,i,n-1); return 0; } int sort(int* a, int n) { int x,i; buildheap(a,n); x=a[0]; a[0]=a[n-1]; a[n-1]=x; for(i=n-2;i>=0;i--) { heapify(a,0,i); x=a[0]; a[0]=a[i]; a[i]=x; } return 0; } int main() { return 0; } ================================================ FILE: Sorting Algorithms/C:C++/insertion.hpp ================================================ #include using namespace std; void insertion_sort(int length, int v[]){ for(int i=0;i0 && v[j] < v[j-1]){ swap(v[j], v[j-1]); j--; } } } ================================================ FILE: Sorting Algorithms/C:C++/merge.hpp ================================================ #include using namespace std; void _merge(int v[], int left, int mid, int right){ int i, j, k; int n1 = mid - left + 1; // size of first subarray int n2 = right - mid; // size of second subarray // create temp arrays int L[n1], R[n2]; // Copy data to temp arrays L[] and R[] for (i = 0; i < n1; i++) L[i] = v[left + i]; for (j = 0; j < n2; j++) R[j] = v[mid + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = left; // Initial index of merged subarray while (i < n1 && j < n2){ if (L[i] <= R[j]){ v[k] = L[i]; i++; }else{ v[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1){ v[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2){ v[k] = R[j]; j++; k++; } } void _merge_sort(int v[], int left, int right){ if(left < right){ // same as (left + right) / 2, but avoids overflow due to large values of left and right int mid = left + (right - left) / 2; _merge_sort(v, left, mid); _merge_sort(v, mid + 1, right); _merge(v, left, mid, right); } } void merge_sort(int length, int v[]){ _merge_sort(v, 0, length-1); } ================================================ FILE: Sorting Algorithms/C:C++/quick.hpp ================================================ #include using namespace std; int _partition(int v[], int left, int right){ int pivot = v[right]; int i = left-1; for(int j=left;j void quicksort(int number[25],int first,int last){ int i, j, pivot, temp; if(firstnumber[pivot]) j--; if(i using namespace std; void _count_sort(int arr[], int length, int exp){ int output[length]; // output array int i, count[10] = {0}; // Store count of occurrences in count[] for (i = 0; i < length; i++) count[ (arr[i]/exp)%10 ]++; // Change count[i] so that count[i] now contains actual // position of this digit in output[] for (i = 1; i < 10; i++) count[i] += count[i - 1]; // Build the output array for (i = length - 1; i >= 0; i--){ output[ count[ (arr[i]/exp)%10 ] - 1] = arr[i]; count[ (arr[i]/exp)%10 ]--; } // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to current digit for (i = 0; i < length; i++) arr[i] = output[i]; } void radix_sort(int length, int v[]){ int mx = *max_element(v, v+length); for(int i = 1; mx / i > 0; i *= 10){ _count_sort(v, length, i); } } ================================================ FILE: Sorting Algorithms/C:C++/selectionsort.c ================================================ /*Take as input N, the size of array. Take N more inputs and store that in an array. Write a function that selection sorts the array. Print the elements of sorted array. 1.It reads a number N. 2.Take Another N numbers as input and store them in an Array. 3.Sort the array using Selection Sort and print that Array. */ // C program for implementation of selection sort #include void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void selectionSort(int arr[], int n) { int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); } } /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } // Driver program to test above functions int main() { int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0; } ================================================ FILE: Sorting Algorithms/C:C++/shell_sort.h ================================================ #ifndef ALGO_SHELL_SORT_H__ #define ALGO_SHELL_SORT_H__ namespace alg { /** * shell sort an array */ template static void shell_sort(T *array, int len) { int h = 1; while (h < len / 3) { h = 3 * h + 1; // 1, 4, 13, 40, 121, ... } while (h >= 1) { for (int i = h; i < len; i++) { int cur = array[i]; int j = i - h; while (j >= 0 && array[j] > cur) { array[j + h] = array[j]; j = j - h; } array[j + h] = cur; } h = h / 3; } } } #endif // ================================================ FILE: Sorting Algorithms/C:C++/slow.cpp ================================================ #include using namespace std; void _slow_sort(int v[], int i, int j) { if (i >= j) return; int m = i + (j-i)/2; _slow_sort(v, i, m); _slow_sort(v, m+1, j); if (v[j] < v[m]) swap(v[j], v[m]); _slow_sort(v, i, j-1); } void slow_sort(int length, int v[]) { _slow_sort(v, 0, length-1); } ================================================ FILE: Sorting Algorithms/C:C++/sorting_a_vector.cpp ================================================ #include #include #include #include using namespace std; bool compare(int a,int b){ return a>b; } int main(){ vector v; for(int i=1;i<5;i++){ v.push_back(i); } int p; cin>>p; int d; cin>>d; v.insert(v.begin() + p,d); for(int i=0;i= 0; i--) heapify(a, n, i); // extract element from the heap for (int i=n-1; i>=0; i--) { int temp = a[0]; a[0] = a[i]; a[i] = temp; // rebuild the heap heapify(a, i, 0); } } public static void heapify(int arr[], int n, int i) { int largest = i; int l = 2*i + 1; int r = 2*i + 2; // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } } ================================================ FILE: Sorting Algorithms/Java/MergeSort.java ================================================ package test; public class test { public static void main(String[] args) { String[] nums = { "AB", "DD", "CC", "BB", "CA", "AA" }; mergeSort(nums, 0, nums.length - 1); System.out.println("Sorted character strings : "); for (String i : nums) { System.out.println(i); } } public static void mergeSort(String[] a, int low, int high) { int mid; if (low < high) { mid = (low + high) / 2; mergeSort(a, low, mid); mergeSort(a, mid + 1, high); merge(a, low, mid, high); } } public static void merge(String[] a, int low, int mid, int high) { int i, l, r, k; String[] temp = new String[a.length]; i = low; l = low; r = mid + 1; while (l <= mid && r <= high) { int letter = 0; boolean elementAdded = false; while (letter < a[l].length() && letter < a[r].length()) { if (a[l].charAt(letter) < a[r].charAt(letter)) { temp[i] = a[l]; elementAdded = true; l++; break; } else if (a[l].charAt(letter) > a[r].charAt(letter)) { temp[i] = a[r]; elementAdded = true; r++; break; } letter++; } if (!elementAdded) { if (a[l].length() < a[r].length()) { temp[i] = a[l]; l++; } else { temp[i] = a[r]; r++; } } i++; } if (l > mid) { for (k = r; k <= high; k++) { temp[i] = a[k]; i++; } } else { for (k = l; k <= mid; k++) { temp[i] = a[k]; i++; } } for (k = low; k <= high; k++) { a[k] = temp[k]; } } } ================================================ FILE: Sorting Algorithms/Javascript/bubblesort.js ================================================ //function takes in array const bubblesort = (array) => { let length = array.length; for (let i=0;i array[j+1]){ //do the swap let temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } } } return array; } //test array console.log(bubblesort([3,17,24,4,5,1,4,2,3])); ================================================ FILE: Sorting Algorithms/Python/QuickSort.py ================================================ def partition(arr,low,high): i = ( low-1 ) # index of smaller element pivot = arr[high] # pivot for j in range(low , high): # If current element is smaller than or # equal to pivot if arr[j] <= pivot: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return ( i+1 ) # The main function that implements QuickSort # arr[] --> Array to be sorted, # low --> Starting index, # high --> Ending index # Function to do Quick sort def quickSort(arr,low,high): if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr,low,high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi-1) quickSort(arr, pi+1, high) # Driver code to test above arr = [10, 7, 8, 9, 1, 5] n = len(arr) quickSort(arr,0,n-1) print ("Sorted array is:") for i in range(n): print ("%d" %arr[i]), ================================================ FILE: Sorting Algorithms/Python/bogosort.py ================================================ from random import shuffle # Sorting algorithm that relies solely on shuffling all # numbers until the array is sorted. Worst case scenario # is when it never sorts :( def bogosort(my_array): pos = 0 while True: if(pos == (len(my_array)-1)): break while (my_array[pos] > my_array[pos+1]): shuffle(my_array) pos = 0 pos= 1) return my_array ================================================ FILE: Sorting Algorithms/Python/bubblesort.py ================================================ def bubble_sort(arr): changed = True while changed: changed = False for i in range(len(arr) - 1): if arr[i] > arr[i+1]: arr[i], arr[i+1] = arr[i+1], arr[i] changed = True return None ================================================ FILE: Sorting Algorithms/Python/cocktailsort.py ================================================ # Cocktail sorting def cocktailsort(a): n=len(a) swapped=True start=0 end=n-1 while(swapped==True): swapped=False for i in range(start,end): if (a[i] > a[i+1]) : a[i], a[i+1]= a[i+1], a[i] swapped=True if (swapped==False) : break swapped=False end=end-1 for i in range(end-1,start-1,-1) : if (a[i] > a[i+1]) : a[i], a[i+1]= a[i+1], a[i] swapped=True start=start+1 a=[8,2,1,3,4] cocktailsort(a) print("Sorted array is:") for i in range(len(a)): print ("%d" %a[i]), ================================================ FILE: Sorting Algorithms/Python/insertionsort.py ================================================ def insertion_sort(my_array): ordered_array = [] for pos in range(len(my_array)): new_pos = pos while(new_pos > 0 and (my_array[new_pos] < my_array[new_pos-1])): temp = my_array[new_pos] my_array[new_pos] = my_array[new_pos-1] my_array[new_pos-1] = temp new_pos -= 1 return my_array ================================================ FILE: Sorting Algorithms/Python/mergesort.py ================================================ def mergeSort(nlist): if len(nlist)>1: mid = len(nlist)//2 lefthalf = nlist[:mid] righthalf = nlist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=j=k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: nlist[k]=lefthalf[i] i=i+1 else: nlist[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): nlist[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): nlist[k]=righthalf[j] j=j+1 k=k+1 nlist = [14,46,43,27,57,41,45,21,70] mergeSort(nlist) print(nlist) # time complexity : O(nlogn) # space complexity: O(logn) ================================================ FILE: Sorting Algorithms/Python/quicksort.py ================================================ def quickSort(data_list): quickSortHlp(data_list,0,len(data_list)-1) def quickSortHlp(data_list,first,last): if first < last: splitpoint = partition(data_list,first,last) quickSortHlp(data_list,first,splitpoint-1) quickSortHlp(data_list,splitpoint+1,last) def partition(data_list,first,last): pivotvalue = data_list[first] leftmark = first+1 rightmark = last done = False while not done: while leftmark <= rightmark and data_list[leftmark] <= pivotvalue: leftmark = leftmark + 1 while data_list[rightmark] >= pivotvalue and rightmark >= leftmark: rightmark = rightmark -1 if rightmark < leftmark: done = True else: temp = data_list[leftmark] data_list[leftmark] = data_list[rightmark] data_list[rightmark] = temp temp = data_list[first] data_list[first] = data_list[rightmark] data_list[rightmark] = temp return rightmark data_list = [54,26,93,17,77,31,44,55,20] quickSort(data_list) print(data_list) ================================================ FILE: Sorting Algorithms/Python/topological_sort.py ================================================ #Python program to print topological sorting of a DAG from collections import defaultdict #Class to represent a graph class Graph: def __init__(self,vertices): self.graph = defaultdict(list) #dictionary containing adjacency List self.V = vertices #No. of vertices # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A recursive function used by topologicalSort def topologicalSortUtil(self,v,visited,stack): # Mark the current node as visited. visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.topologicalSortUtil(i,visited,stack) # Push current vertex to stack which stores result stack.insert(0,v) # The function to do Topological Sort. It uses recursive # topologicalSortUtil() def topologicalSort(self): # Mark all the vertices as not visited visited = [False]*self.V stack =[] # Call the recursive helper function to store Topological # Sort starting from all vertices one by one for i in range(self.V): if visited[i] == False: self.topologicalSortUtil(i,visited,stack) # Print contents of stack print stack g= Graph(6) g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); print "Following is a Topological Sort of the given graph" g.topologicalSort() ================================================ FILE: Sorting Algorithms/sleep sort.c ================================================ #include #include #include void routine(void *a) { int n = *(int *) a; // typecasting from void to int // Sleeping time is proportional to the number // More precisely this thread sleep for 'n' milliseconds Sleep(n); // After the sleep, print the number printf("%d ", n); void sleepSort(int arr[], int n) { // An array of threads, one for each of the elements // in the input array HANDLE threads[n]; // Create the threads for each of the input array elements for (int i = 0; i < n; i++) threads[i] = (HANDLE)_beginthread(&routine, 0, &arr[i]); // Process these threads WaitForMultipleObjects(n, threads, TRUE, INFINITE); return; } // Driver program to test above functions int main() { // Doesn't work for negative numbers int arr[] = {34, 23, 122, 9}; int n = sizeof(arr) / sizeof(arr[0]); sleepSort (arr, n); return(0); } ================================================ FILE: String Manipulation/C:C++/String_algo/KMP.cpp ================================================ /* Time-Complexity :- O(length of string) Used for outputing indices where a particular text appears in a given string */ #include #include #include using namespace std; #define mod 1000000007 #define all(v) v.begin(),v.end() #define loop(i,a,b) for(i=(int)a;i<(int)b;i++) #define revloop(i,a,b) for(i=(int)a;i>=(int)b;i--) #define stloop(it,v) for(it=v.begin();it!=v.end();++it) #define ii pair #define MP make_pair #define pb push_back #define ll long long int #define fill(v,d) memset(v,d,sizeof(v)) #define INF 1000000005 #define PI acos(-1.0) vector b; string p,t; int i; void preprocess(string a) { int i = 1,j = 0; b[0] = 0; while(i < (int)a.length()) { while(j > 0 && a[i] != a[j]) { j--; j= b[j]; } if(a[i] == a[j]) j++; b[i] = j; i++; } } void kmp(string a,string t) { int i=0,j=0; while(i<(int)a.length()) { while(j > 0 && a[i] != t[j]) { j--; j= b[j]; } if(a[i] == t[j]) j++; if(j == (int)t.length()) { cout<>t>>p; b.resize(p.length()); preprocess(p); loop(i,0,b.size()) cout< #include #include using namespace std; #define mod 1000000007 #define all(v) v.begin(),v.end() #define loop(i,a,b) for(i=(int)a;i<(int)b;i++) #define revloop(i,a,b) for(i=(int)a;i>=(int)b;i--) #define stloop(it,v) for(it=v.begin();it!=v.end();++it) #define ii pair #define MP make_pair #define pb push_back #define ll long long int #define fill(v,d) memset(v,d,sizeof(v)) #define INF 1000000005 #define PI acos(-1.0) vector > sa; struct mytuple{ int orig; int first; int second; }; bool cmp(mytuple a,mytuple b) { if(a.first == b.first) return a.second < b.second; return a.first < b.first; } int main() { std::ios_base::sync_with_stdio(false); cin.tie(NULL); string a; int i,n,curr,cnt,stp; cin>>a; n = a.length(); stp = log(n)/log(2) + 2; sa.assign(stp,vector(n)); loop(i,0,n) sa[0][i] = a[i]-'a'; mytuple L[n]; stp = 1; for(cnt = 1;cnt < n; cnt*=2) { for(i=0;i z[] = {-1,2,1,0,2,1,0} s = aaaaa => z[] = {-1,4,3,2,1} s = abacaba => z[] = {-1,0,1,0,3,0,1} */ #include using namespace std; #define mod 1000000007 #define all(v) v.begin(),v.end() #define rep(i,a,b) for(i=(ll)a;i<(ll)b;i++) #define revrep(i,a,b) for(i=(ll)a;i>=(ll)b;i--) #define strep(it,v) for(it=v.begin();it!=v.end_();++it) #define ii pair #define MP make_pair #define pb push_back #define f first #define se second #define ll long long int #define vi vector ll modexp(ll a,ll b){ ll res = 1; while(b > 0){ if(b & 1) res = (res * a); a = (a * a); b/=2; } return res; } #define rs resize long long readLI(){ register char c; for(c = getchar(); !(c>='0' && c<='9'); c = getchar()); register long long a=c-'0'; for(c = getchar(); c>='0' && c<='9'; c = getchar()) a = (a<<3)+(a<<1)+c-'0'; return a; } const int N = 100009; string a; ll i,z[N]; void z_function(string s) { ll l = 0,r = 0,n = s.length(); rep(i,1,n){ if(i <= r) z[i] = min(r - i + 1,z[i - l]); while(i + z[i] < n and s[z[i]] == s[i + z[i]]) z[i]++; if(i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } } int main() { std::ios_base::sync_with_stdio(false); cin.tie(NULL); cin>>a; z[0] = -1; //Not possible of zero length z_function(a); rep(i,0,a.length()) cout< #include #include int main () { std::string str (" Please split this sentence into tokens "); char * cstr = new char [str.length()+1]; std::strcpy (cstr, str.c_str()); // cstr now contains a c-string copy of str char * p = std::strtok (cstr," "); std::cout< using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary.*/ int dictionaryContains(string &word) { string dictionary[] = {"mobile","samsung","nokia","apple","car","book","ball","bat","hello","boy","girl", "red","good","bad","lovely", "nice","and","bad","bad","bad","bad","bad","bad","bad","bad","bad", "go","are","love","ice","cream" }; int n = sizeof(dictionary)/sizeof(dictionary[0]); for (int i = 0; i < n; i++) if (dictionary[i].compare(word) == 0) return true; return false; } void wordBreakUtil(string str, int size, string result); void wordBreak(string str) { // last argument is prefix wordBreakUtil(str, str.size(), ""); } // result store the current prefix with spaces between words void wordBreakUtil(string str, int n, string result) { cout<<"here"; //Process all prefixes one by one for (int i=1; i<=n; i++) { //extract substring from 0 to i in prefix string prefix = str.substr(0, i); // if dictionary conatins this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if (dictionaryContains(prefix)) { // if no more elements are there, print it if (i == n) { // add this element to previous prefix result += prefix; cout << result << endl; //print result return; } wordBreakUtil(str.substr(i, n-i), n-i,result + prefix + " "); } }//end for }//end function int main() { cout << "First Test:\n"; wordBreak("iloveicecreamandmango"); cout << "\nSecond Test:\n"; wordBreak("ilovesamsungmobile"); return 0; } ================================================ FILE: String Manipulation/Python/LCS.py ================================================ def lcs(a, b): lengths = [[0 for j in range(len(b)+1)] for i in range(len(a)+1)] # row 0 and column 0 are initialized to 0 already for i, x in enumerate(a): for j, y in enumerate(b): if x == y: lengths[i+1][j+1] = lengths[i][j] + 1 else: lengths[i+1][j+1] = max(lengths[i+1][j], lengths[i][j+1]) # read the substring out from the matrix result = "" x, y = len(a), len(b) while x != 0 and y != 0: if lengths[x][y] == lengths[x-1][y]: x -= 1 elif lengths[x][y] == lengths[x][y-1]: y -= 1 else: assert a[x-1] == b[y-1] result = a[x-1] + result x -= 1 y -= 1 return result ================================================ FILE: backtrack/sudoku/code2.cpp ================================================ //http://www.spoj.com/problems/EASUDOKU/ #include using namespace std; typedef vector > matrix; bool check_possibility(matrix& vec,int num,int row,int col){ //check in row && col for(int i=0;i<9;i++){ if(i!=col && vec[row][i]==num) return false; if(i!=row && vec[i][col]==num) return false; } //check in 3*3 matrix int row_ = row - row%3; int col_ = col - col%3; for(int i=row_;i poss; int temp = vec[row][col]; for(int i=1;i<=9;i++)//collect all possibilities if(isGood(vec,i,row,col)) poss.push_back(i); if(row==9-1 && col==9-1 )//last elem if(poss.size()==1){//last elem with single possibility vec[row][col]=poss[0];return true; } else return false; for(int i : poss){ vec[row][col]=i; if(col==9-1){//move to next row if(back_track(vec,row+1,0)) return true; } else{ if(back_track(vec,row,col+1)) return true; } } //backtrack vec[row][col]=temp; return false; } int main(){ int t=1; ios_base::sync_with_stdio(0);cin.tie(0); cin>>t; while(t--){ matrix vec(9,vector(9,0)); for(int i=0;i<9;i++) for(int j=0;j<9;j++){ cin>>vec[i][j]; } if( back_track(vec,0,0) ){ for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ cout< using namespace std; typedef vector > matrix; bool check_possibility(matrix& vec,int num,int row,int col){ //check in row && col for(int i=0;i<9;i++){ if(i!=col && vec[row][i]==num) return false; if(i!=row && vec[i][col]==num) return false; } //check in 3*3 matrix int row_ = row - row%3; int col_ = col - col%3; for(int i=row_;i poss; int temp = vec[row][col]; for(int i=1;i<=9;i++)//collect all possibilities if(isGood(vec,i,row,col)) poss.push_back(i); if(row==9-1 && col==9-1 )//last elem if(poss.size()==1){//last elem with single possibility vec[row][col]=poss[0];return true; } else return false; for(int i : poss){ vec[row][col]=i; if(col==9-1){//move to next row if(back_track(vec,row+1,0)) return true; } else{ if(back_track(vec,row,col+1)) return true; } } //backtrack vec[row][col]=temp; return false; } int main(){ matrix vec(9,vector(9,0)); for(int i=0;i<9;i++) for(int j=0;j<9;j++){ cin>>vec[i][j]; } if( back_track(vec,0,0) ){//soln exists cout<<"ans : \n"; for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ cout<id){ current = current.left; }else{ current = current.right; } } return false; } public boolean delete(int id){ Node parent = root; Node current = root; boolean isLeftChild = false; while(current.data!=id){ parent = current; if(current.data>id){ isLeftChild = true; current = current.left; }else{ isLeftChild = false; current = current.right; } if(current ==null){ return false; } } //if i am here that means we have found the node //Case 1: if node to be deleted has no children if(current.left==null && current.right==null){ if(current==root){ root = null; } if(isLeftChild ==true){ parent.left = null; }else{ parent.right = null; } } //Case 2 : if node to be deleted has only one child else if(current.right==null){ if(current==root){ root = current.left; }else if(isLeftChild){ parent.left = current.left; }else{ parent.right = current.left; } } else if(current.left==null){ if(current==root){ root = current.right; }else if(isLeftChild){ parent.left = current.right; }else{ parent.right = current.right; } }else if(current.left!=null && current.right!=null){ //now we have found the minimum element in the right sub tree Node successor = getSuccessor(current); if(current==root){ root = successor; }else if(isLeftChild){ parent.left = successor; }else{ parent.right = successor; } successor.left = current.left; } return true; } public Node getSuccessor(Node deleleNode){ Node successsor =null; Node successsorParent =null; Node current = deleleNode.right; while(current!=null){ successsorParent = successsor; successsor = current; current = current.left; } //check if successor has the right child, it cannot have left child for sure // if it does have the right child, add it to the left of successorParent. // successsorParent if(successsor!=deleleNode.right){ successsorParent.left = successsor.right; successsor.right = deleleNode.right; } return successsor; } public void insert(int id){ Node newNode = new Node(id); if(root==null){ root = newNode; return; } Node current = root; Node parent = null; while(true){ parent = current; if(id #include #include #include #include #include #include #include #define BLOCKSIZE 4096 #define T 255 #define LEAF 0x0001 #define ONDISK 0x0002 #define MARKFREE 0x0004 namespace alg { class BTree { private: // 4K node, 4096 bytes to write // t = 255 struct node_t { uint16_t n; // num key uint16_t flag; // flags uint32_t offset; // lseek offset related to file beginning char padding[12]; // padding to 4096 int32_t key[509]; // key int32_t c[510]; // childs pointers (represented as file offsets) } __attribute__ ((packed)); typedef struct node_t *node; public: // node and index struct Res { uint32_t offset; int32_t idx; }; private: int fd; private: BTree(const BTree &); BTree& operator=(const BTree&); public: BTree(const char * path) { fd = open(path, O_RDWR|O_CREAT, 0640); if (fd == -1) return; node x = (node)ALLOCBLK(); int n = read(fd,x,BLOCKSIZE); if (n != BLOCKSIZE) { // init new btree x->flag |= LEAF; WRITE(x); } } ~BTree() { close(fd); } Res Search(int32_t x) { node root = ROOT(); return search(root, x); } void Insert(int32_t k) { node r = ROOT(); if (r->n == 2*T - 1) { // place the old root node to the end of the file r->flag &= ~ONDISK; WRITE(r); // new root node s = (node)ALLOCBLK(); s->flag &= ~LEAF; s->flag |= ONDISK; // write to offset 0 s->offset = 0; s->n = 0; s->c[0] = r->offset; split_child(s, 0); // split_child with write s insert_nonfull(s, k); } else { insert_nonfull(r, k); } } void DeleteKey(int32_t k) { node root = ROOT(); delete_op(root, k); } private: /** * search a key, returns node and index */ Res search(node x, int32_t k) { int32_t i = 0; Res ret; while (in && k > x->key[i]) i++; if (in && k == x->key[i]) { // search in [0,n-1] ret.offset = x->offset; ret.idx = i; return ret; } else if (x->flag & LEAF) { // leaf, no more childs ret.offset = 0; ret.idx = -1; return ret; } else { std::auto_ptr xi(READ(x, i)); // search in a child return search(xi.get(), k); } } /** * insert into non-full node */ void insert_nonfull(node x, int32_t k) { int32_t i = x->n-1; if (x->flag & LEAF) { // insert into this leaf while (i>=0 && k < x->key[i]) { // right shift to x->key[i+1] = x->key[i]; // make place for k i = i - 1; } x->key[i+1] = k; x->n = x->n + 1; WRITE(x); } else { while(i>=0 && k < x->key[i]) { i = i-1; } i=i+1; node xi = READ(x, i); // insert the key into one child. if (xi->n == 2*T-1) { split_child(x, i); if (k > x->key[i]) { i = i+1; } // NOTICE! // reload x[i] after split_child. xi = READ(x, i); } insert_nonfull(xi, k); delete xi; } } /** * split a node into 2. */ void split_child(node x, int32_t i) { std::auto_ptr z((node)ALLOCBLK()); std::auto_ptr y(READ(x, i)); z->flag &= ~LEAF; z->flag |= (y->flag & LEAF); z->n = T - 1; int32_t j; for (j=0;jkey[j] = y->key[j+T]; } if (!(y->flag & LEAF)) { // if not leaf, copy childs too. for (j=0;jc[j] = y->c[j+T]; } } y->n = T-1; // shrink y to t-1 elements WRITE(y.get()); WRITE(z.get()); for (j=x->n;j>=i+1;j--) { // make place for the new child in x x->c[j+1] = x->c[j]; } x->c[i+1] = z->offset; // make z the child of x for (j=x->n-1;j>=i;j--) { // move keys in x x->key[j+1] = x->key[j]; } x->key[i] = y->key[T-1]; // copy the middle element of y into x x->n = x->n+1; WRITE(x); } /** * recursive deletion. */ void delete_op(node x, int32_t k) { int32_t i; /* int t; printf("key:%d n:%d\n",k, x->n); for (t=0;tn;t++) { printf("=%d=", x->key[t]); } printf("\n"); */ if (x->n == 0) { // emtpy node return; } i = x->n - 1; while (i>=0 && k < x->key[i]) { // search the key. i = i - 1; } if (i >= 0 && x->key[i] == k) { // key exists in this node. if (x->flag & LEAF) { //printf("in case 1 [%d] [%d]\n", i,x->n); case1(x, i, k); } else { //printf("in case 2 [%d] [%d]\n", i,x->n); case2(x, i, k); } } else { // case 3. on x.c[i+1] case3(x, i+1, k); } } /** * case 1. * If the key k is in node x and x is a leaf, delete the key k from x. */ void case1(node x, int32_t i, int32_t k) { int j; for (j = i;jn-1;j++) { // shifting the keys only, no childs available. x->key[j] = x->key[j+1]; } x->n = x->n - 1; WRITE(x); } void case2(node x, int32_t i, int32_t k) { // case 2a: // If the child y that precedes k in node x has at least t // keys, then find the predecessor k0 of k in the subtree // rooted at y. Recursively delete k0, and replace k by k0 in x. // (We can find k0 and delete it in a single downward pass.) std::auto_ptr y(READ(x, i)); if (y->n >= T) { int32_t k0 = y->key[y->n-1]; //printf("case2a %d %d\n", k0, x->key[i]); x->key[i] = k0; WRITE(x); delete_op(y.get(), k0); return; } // case 2b. // If y has fewer than t keys, then, symmetrically, examine // the child z that follows k in node x. If z has at least t keys, // then find the successor k0 of k in the subtree rooted at z. // Recursively delete k0, and replace k by k0 in x. (We can find k0 // and delete it in a single downward pass.) std::auto_ptr z(READ(x, i+1)); if (z->n >= T) { int32_t k0 = z->key[0]; //printf("case2b %d %d\n", k0, x->key[i]); x->key[i] = k0; WRITE(x); delete_op(z.get(), k0); return; } // case 2c: // Otherwise, if both y and z have only t-1 keys, // merge k and all of z into y, so that x loses both k and the // pointer to z, and y now contains 2t - 1 keys. // Then free z and recursively delete k from y. if (y->n == T-1 && z->n == T-1) { //printf("case2c"); // merge k & z into y y->key[y->n] = k; int j; for (j=0;jn;j++) { // merge keys of z y->key[y->n+1+j] = z->key[j]; } for (j=0;jn+1;j++) { // merge childs of z y->c[y->n+1+j] = z->c[j]; } // mark free z z->flag |= MARKFREE; y->n = y->n + z->n + 1; // size after merge WRITE(z.get()); WRITE(y.get()); for (j=i;jn-1;j++) { // delete k from node x x->key[j] = x->key[j+1]; } for (j=i+1;jn;j++){ // delete pointer to z --> (i+1)th x->c[j] = x->c[j+1]; } x->n = x->n - 1; WRITE(x); // recursive delete k delete_op(y.get(), k); return; } // cannot reach here assert(false); } void case3(node x, int32_t i, int32_t k) { std::auto_ptr ci(READ(x, i)); if (ci->n > T-1) { // ready to delete in child. delete_op(ci.get(), k); return; } // case 3a. // If x.c[i] has only t - 1 keys but has an immediate sibling with at least t keys, // give x.c[i] an extra key by moving a key from x down into x.c[i], moving a // key from x.c[i]’s immediate left or right sibling up into x, and moving the // appropriate child pointer from the sibling into x.c[i]. std::auto_ptr left(READ(x, i-1)); if (i-1>=0 && left->n >= T) { // printf("case3a, left"); // right shift keys and childs of x.c[i] to make place for a key // right shift ci childs int j; for (j=ci->n-1;j>0;j--) { ci->key[j] = ci->key[j-1]; } for (j=ci->n;j>0;j--) { ci->c[j] = ci->c[j-1]; } ci->n = ci->n+1; ci->key[0] = x->key[i-1]; // copy key from x[i-1] to ci[0] ci->c[0] = left->c[left->n]; // copy child from left last child. x->key[i] = left->key[left->n-1]; // copy left last key into x[i] left->n = left->n-1; // decrease left size WRITE(ci.get()); WRITE(x); WRITE(left.get()); delete_op(ci.get(), k); return; } // case 3a. right sibling std::auto_ptr right(READ(x, i+1)); if (i+1<=x->n && right->n >= T) { // printf("case3a, right"); ci->key[ci->n] = x->key[i]; // append key from x ci->c[ci->n+1] = right->c[0]; // append child from right ci->n = ci->n+1; x->key[i] = right->key[0]; // subsitute key in x int j; for (j=0;jn-1;j++) { // remove key[0] from right sibling right->key[j] = right->key[j+1]; } for (j=0;jn;j++) { // and also the child c[0] of the right sibling. right->c[j] = right->c[j+1]; } right->n = right->n - 1; // reduce the size of the right sibling. WRITE(ci.get()); WRITE(x); WRITE(right.get()); delete_op(ci.get(), k); // recursive delete key in x.c[i] return; } // case 3b. // If x.c[i] and both of x.c[i]’s immediate siblings have t-1 keys, merge x.c[i] // with one sibling, which involves moving a key from x down into the new // merged node to become the median key for that node. if ((i-1<0 ||left->n == T-1) && (i+1 <=x->n || right->n == T-1)) { if (left->n == T-1) { // copy x[i] to left left->key[left->n] = x->key[i]; left->n = left->n + 1; // remove key[i] from x and also the child // shrink the size & set the child-0 to left delete_i(x, i); int j; // append x.c[i] into left sibling for (j=0;jn;j++) { left->key[left->n + j] = ci->key[j]; } for (j=0;jn+1;j++) { left->c[left->n + j] = ci->c[j]; } left->n += ci->n; // left became 2T-1 ci->flag |= MARKFREE; // free ci ci->n = 0; WRITE(ci.get()); WRITE(x); // root check if (x->n == 0 && x->offset ==0) { left->flag |= MARKFREE; WRITE(left.get()); left->flag &= ~MARKFREE; left->offset = 0; } WRITE(left.get()); delete_op(left.get(), k); return; } else if (right->n == T-1) { // copy x[i] to x.c[i] ci->key[ci->n] = x->key[i]; ci->n = ci->n + 1; // remove key[i] from x and also the child // shrink the size & set the child-0 to ci delete_i(x, i); int j; // append right sibling into x.c[i] for (j=0;jn;j++) { ci->key[ci->n + j] = right->key[j]; } for (j=0;jn+1;j++) { ci->c[ci->n + j] = right->c[j]; } ci->n += right->n; // ci became 2T-1 right->flag |= MARKFREE; // free right right->n = 0; WRITE(right.get()); WRITE(x); // root check if (x->n == 0 && x->offset ==0) { ci->flag |= MARKFREE; WRITE(ci.get()); ci->flag &= ~MARKFREE; ci->offset = 0; } WRITE(ci.get()); delete_op(ci.get(), k); return; } } } /** * delete ith key & child. */ void delete_i(node x, int32_t i) { int j; for (j=i;jn-1;j++) { x->key[j] = x->key[j+1]; } for (j=i+1;jn;j++) { x->c[j] = x->c[j+1]; } x->n = x->n - 1; } /** * Allocate empty node struct. * A better allocator should be consider in practice, such as * re-cycling the freed up blocks on disk, so used blocks * should be traced in some data strucuture, file header maybe. */ void * ALLOCBLK() { node x = new node_t; x->n = 0; x->offset = 0; x->flag = 0; memset(x->key, 0, sizeof(x->key)); memset(x->c, 0, sizeof(x->c)); memset(x->padding, 0xcc, sizeof(x->padding)); return x; } /** * Load the root block */ node ROOT() { void *root = ALLOCBLK(); lseek(fd, 0, SEEK_SET); read(fd, root, BLOCKSIZE); return (node)root; } /** * Read a 4K-block from disk, and returns the node struct. */ node READ(node x, int32_t i) { void *xi = ALLOCBLK(); if (i >=0 && i <= x->n) { lseek(fd, x->c[i], SEEK_SET); read(fd, xi, BLOCKSIZE); } return (node)xi; } /** * update a node struct to file, create if offset is -1. */ void WRITE(node x) { if (x->flag & ONDISK) { lseek(fd, x->offset, SEEK_SET); } else { x->offset = lseek(fd,0, SEEK_END); } x->flag |= ONDISK; write(fd, x, BLOCKSIZE); } }; } ================================================ FILE: cryptography/Python/porta.py ================================================ from pycipher.base import Cipher #################################################################################### class Porta(Cipher): """The Porta Cipher is a polyalphabetic substitution cipher, and has a key consisting of a word e.g. 'FORTIFICATION'. :param key: The keyword, any word or phrase will do. Must consist of alphabetical characters only, no punctuation of numbers. """ def __init__(self,key='FORTIFICATION'): self.key = [k.upper() for k in key] def encipher(self,string): """Encipher string using Porta cipher according to initialised key. Punctuation and whitespace are removed from the input. Example:: ciphertext = Porta('HELLO').encipher(plaintext) :param string: The string to encipher. :returns: The enciphered string. """ string = self.remove_punctuation(string) ret = '' for (i,c) in enumerate(string): i = i%len(self.key) if self.key[i] in 'AB': ret += 'NOPQRSTUVWXYZABCDEFGHIJKLM'[self.a2i(c)] elif self.key[i] in 'YZ': ret += 'ZNOPQRSTUVWXYBCDEFGHIJKLMA'[self.a2i(c)] elif self.key[i] in 'WX': ret += 'YZNOPQRSTUVWXCDEFGHIJKLMAB'[self.a2i(c)] elif self.key[i] in 'UV': ret += 'XYZNOPQRSTUVWDEFGHIJKLMABC'[self.a2i(c)] elif self.key[i] in 'ST': ret += 'WXYZNOPQRSTUVEFGHIJKLMABCD'[self.a2i(c)] elif self.key[i] in 'QR': ret += 'VWXYZNOPQRSTUFGHIJKLMABCDE'[self.a2i(c)] elif self.key[i] in 'OP': ret += 'UVWXYZNOPQRSTGHIJKLMABCDEF'[self.a2i(c)] elif self.key[i] in 'MN': ret += 'TUVWXYZNOPQRSHIJKLMABCDEFG'[self.a2i(c)] elif self.key[i] in 'KL': ret += 'STUVWXYZNOPQRIJKLMABCDEFGH'[self.a2i(c)] elif self.key[i] in 'IJ': ret += 'RSTUVWXYZNOPQJKLMABCDEFGHI'[self.a2i(c)] elif self.key[i] in 'GH': ret += 'QRSTUVWXYZNOPKLMABCDEFGHIJ'[self.a2i(c)] elif self.key[i] in 'EF': ret += 'PQRSTUVWXYZNOLMABCDEFGHIJK'[self.a2i(c)] elif self.key[i] in 'CD': ret += 'OPQRSTUVWXYZNMABCDEFGHIJKL'[self.a2i(c)] return ret def decipher(self,string): """Decipher string using Porta cipher according to initialised key. Punctuation and whitespace are removed from the input. For the Porta cipher, enciphering and deciphering are the same operation. Example:: plaintext = Porta('HELLO').decipher(ciphertext) :param string: The string to decipher. :returns: The deciphered string. """ return self.encipher(string) if __name__ == '__main__': print('use "import pycipher" to access functions') ================================================ FILE: cryptography/des/java/Converter.java ================================================ /** * Convert to binary code russian letters. */ package cryptography.des.java; import java.io.UnsupportedEncodingException; public class Converter { public static String convertToBinaryCode(String text) { StringBuilder binaryCode = new StringBuilder(); for (int i = 0; i < text.length(); i++) { byte[] bytes = getBytes(text.substring(i, i+ 1)); int[] m = new int[bytes.length]; for (int j = 0; j < bytes.length; j++) { m[j] = bytes[j]; } for (int k = 0; k < m.length; k++) { StringBuilder str = new StringBuilder(Integer.toBinaryString(m[k])); for (int n = str.length(); n < 32; n++) { str.insert(0, "0"); } binaryCode.append(str.toString().substring(24)); } } return binaryCode.toString(); } private static byte[] getBytes (String text) { try { return text.getBytes("Cp1251"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } } ================================================ FILE: cryptography/des/java/DES.java ================================================ package cryptography.des.java; public class DES { private String key; private String message; private String[] keys = new String[17]; public String getKey() { return key; } public void setKey(String key) { this.key = Converter.convertToBinaryCode(key); } public String getMessage() { return message; } public void setMessage(String message) { this.message = Converter.convertToBinaryCode(message); } public String encrypt() { String messageAfterPermutation = messagePermutation(message); String[] L = new String[17]; String[] R = new String[17]; String[] Rtemp = new String[17]; L[0] = messageAfterPermutation.substring(0, 32); R[0] = messageAfterPermutation.substring(32); String[] B = new String[9]; generateKeys(key); for (int i = 1; i <= 16; i++) { L[i] = R[i-1]; String Er = E(R[i-1]); Rtemp[i] = xor(Er, keys[i]); B[1] = Rtemp[i].substring(0, 6); B[2] = Rtemp[i].substring(6, 12); B[3] = Rtemp[i].substring(12, 18); B[4] = Rtemp[i].substring(18, 24); B[5] = Rtemp[i].substring(24, 30); B[6] = Rtemp[i].substring(30, 36); B[7] = Rtemp[i].substring(36, 42); B[8] = Rtemp[i].substring(42); String[] C = new String[9]; for (int j = 1; j < 9; j++) { C[j] = sBox(j, B[j]); if (C[j].length() == 3) { C[j] = "0" + C[j]; } else if (C[j].length() == 2) { C[j] = "00" + C[j]; } else if (C[j].length() == 1) { C[j] = "000" + C[j]; } else if (C[j].length() == 0) { C[j] = "0000" + C[j]; } } String cFinal = ""; for (int j = 1; j < C.length; j++) { cFinal += C[j]; } cFinal = cPermute(cFinal); R[i] = xor(L[i-1], cFinal); } return lastInverse(R[16]+L[16]); } private String messagePermutation(String input) { int[] positionTable = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; StringBuilder newMessage = new StringBuilder(); for (int position : positionTable) { newMessage.append(input.substring(position - 1, position)); } return newMessage.toString(); } private void generateKeys(String key) { key = beginKeyPermutation(key); String c = key.substring(0, 28); String d = key.substring(28, key.length()); for (int i = 1; i < 17; i++) { c = leftShiftBits(c, i); d = leftShiftBits(d, i); keys[i] = finishKeyPermutation(c + d); } } private String beginKeyPermutation(String input) { int[] positionTable = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 }; StringBuilder newKey = new StringBuilder(); for (int position : positionTable) { newKey.append(input.substring(position - 1, position)); } return newKey.toString(); } private String leftShiftBits(String input, int step) { int[] shift = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; String shifted = input; for (int j = 0; j < shift[step - 1]; j++) { shifted = shifted.substring(1, shifted.length()) + shifted.substring(0, 1); } return shifted; } private String finishKeyPermutation(String input) { int[] positionTable = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; StringBuilder newKey = new StringBuilder(); for (int position : positionTable) { newKey.append(input.substring(position - 1, position)); } return newKey.toString(); } private String E(String input) { int[] positionTable = { 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 }; StringBuilder newR = new StringBuilder(); for (int position : positionTable) { newR.append(input.substring(position - 1, position)); } return newR.toString(); } private static String xor(String x1, String x2) { StringBuilder out = new StringBuilder(); int len; int start; if (x1.length() < x2.length()) { len = x1.length(); start = x2.length() - x1.length(); out.append(x2.substring(0, start)); x2 = x2.substring(start); } else { len = x2.length(); start = x1.length() - x2.length(); out.append(x1.substring(0, start)); x1 = x1.substring(start); } for (int i = 0; i < len; i++) { String s1 = x1.substring(i, i + 1); String s2 =x2.substring(i, i + 1); out.append(Integer.parseInt(x1.substring(i, i + 1)) ^ Integer.parseInt(x2.substring(i, i + 1))); } return out.toString(); } private String sBox(int boxNumber, String b) { int[] sbox1 = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 }; int[] sBox2 = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 }; int[] sBox3 = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 }; int[] sBox4 = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 }; int[] sBox5 = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 }; int[] sBox6 = { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 }; int[] sBox7 = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 }; int[] sBox8 = { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 }; String temp = b.substring(0, 1) + b.substring(5); int row = Integer.parseInt(temp,2); int col = Integer.parseInt(b.substring(1, 5), 2); row = row * 16; switch (boxNumber) { case 1: return Integer.toBinaryString(sbox1[(row + col)]); case 2: return Integer.toBinaryString(sBox2[(row + col)]); case 3: return Integer.toBinaryString(sBox3[(row + col)]); case 4: return Integer.toBinaryString(sBox4[(row + col)]); case 5: return Integer.toBinaryString(sBox5[(row + col)]); case 6: return Integer.toBinaryString(sBox6[(row + col)]); case 7: return Integer.toBinaryString(sBox7[(row + col)]); case 8: return Integer.toBinaryString(sBox8[(row + col)]); } return null; } private String cPermute(String input) { int[] positionTable = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; StringBuilder newC = new StringBuilder(); for (int position : positionTable) { newC.append(input.substring(position - 1, position)); } return newC.toString(); } private String lastInverse(String input) { int[] positionTable = { 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 }; StringBuilder inverse = new StringBuilder(); for (int position : positionTable) { inverse.append(input.substring(position - 1, position)); } return inverse.toString(); } } ================================================ FILE: cryptography/des/java/IO.java ================================================ package cryptography.des.java; import java.io.*; public class IO { private final String INPUT_FILE_PATH; private final String OUTPUT_FILE_PATH; public IO(String inputFilePath, String outputFilePath) { this.INPUT_FILE_PATH = inputFilePath; this.OUTPUT_FILE_PATH = outputFilePath; } public String readMessageFromFile() { try (BufferedReader reader = new BufferedReader(new FileReader(INPUT_FILE_PATH))) { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public String readKeyFromFile() { try (BufferedReader reader = new BufferedReader(new FileReader(INPUT_FILE_PATH))) { reader.readLine(); return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public void writeStringInFile(String text) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH))) { writer.write(text); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } } ================================================ FILE: cryptography/des/java/Main.java ================================================ /** * In input file write message and password on new line. */ package cryptography.des.java; public class Main { public static void main(String[] args) { IO IO = new IO("input.txt", "output.txt"); String message = IO.readMessageFromFile(); String key = IO.readKeyFromFile(); DES DES = new DES(); DES.setMessage(message); DES.setKey(key); String cypherText = DES.encrypt(); IO.writeStringInFile(cypherText); } } ================================================ FILE: dfs.cpp ================================================ #include void DFS(int); int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10] void main() { int i,j; printf("Enter number of vertices:"); scanf("%d",&n); //read the adjecency matrix printf("\nEnter adjecency matrix of the graph:"); for(i=0;i using namespace std; class disjoint_set { private: int *id, *size, count; public: disjoint_set(int n) : id(new int[n]), size(new int[n]), count(n) { // set ids for all e;ements, size = 1 for(int i=0;icount; } // return id of component corresponding to object n int find(int n){ int root = n; while(root != this->id[root]) root = this->id[root]; while(n != root){ int new_n = this->id[n]; this->id[n] = root; n = new_n; } return root; } void merge(int x, int y){ int i = this->find(x); int j = this->find(y); if(i == j) return; // make smaller root opint to larger one if(this->size[i] < this->size[j]){ this->id[i] = j; this->size[j] += this->size[i]; }else{ this->id[j] = i; this->size[i] += this->size[j]; } this->count--; } bool connected(int x, int y){ return this->find(x) == this->find(y); } }; ================================================ FILE: divide_and_conquer/maximum_sub_array.cpp ================================================ /** * Implementation of finding maximum subarray which consists of finding range and sum of the subarray * Using divide and conquer */ #include using namespace std; // vector array vector a; int resM[3]; int resR[3]; int resL[3]; int res[3]; // find maximum subarray int * findMaxSubArray(int, int); // find subarray in the middle of two halves int * findMiddleSubArray(int, int, int); int main(){ // size of array int n; cin>>n; int foo; for (int i = 0; i < n; i++){ cin>>foo; // add elements to vector a a.push_back(foo); } int *x = findMaxSubArray(0, n - 1); // left position cout<<"("<= res1R[2]) && (res1L[2] >= res1M[2])){ resL[0] = res1L[0]; resL[1] = res1L[1]; resL[2] = res1L[2]; return resL; } else if ((res1R[2] >= res1L[2]) && (res1R[2] >= res1M[2])){ resM[0] = res1R[0]; resM[1] = res1R[1]; resM[2] = res1R[2]; return resR; } else{ return res1M; } } } int * findMiddleSubArray(int low, int mid, int high){ int lSum = INT_MIN, rSum = INT_MIN; int sum = 0; // move through the left sub array starting from the middle to find the longest sub array for (int i = mid; i >= low; i--){ sum += a[i]; if (sum > lSum){ lSum = sum; resM[0] = i; } } sum = 0; // move through the right sub array starting from middle to find the longest sub array for (int i = mid + 1; i <= high; i++){ sum += a[i]; if (sum > rSum){ rSum = sum; resM[1] = i; } } // find sum of the combined middle sub array resM[2] = lSum + rSum; return resM; } ================================================ FILE: divide_and_conquer/strassen.cpp ================================================ #include #include #include using namespace std; void createMatrix(int **A4,int size); void output(int **A, int size); void standardMult(int **A, int **B, int **C, int size); void strassens(int **A, int **B, int **C, int size); void Add(int **A, int **B, int **T, int n); void Sub(int **A, int **B, int **T, int n); int main() { int size = 8; int **A, **B, **C; for(int size=16;size<2048;size*=2){ A = new int *[size]; B = new int *[size]; C = new int *[size]; for(int i=0; i using namespace std; int knapsack(int n, int w, int weight[], int val[]) { int K[n+1][w+1]; for(int i=0;i<=n;i++) { for(int j=0;j<=w;j++) { if(i==0||j==0) K[i][j]=0; else { if(weight[i-1]<=j) K[i][j] = max(val[i-1] + K[i-1][j-weight[i-1]], K[i-1][j]); else K[i][j] = K[i-1][j]; } } } return K[n][w]; } int main() { int t,n,w; cin>>t; while(t--) { cin>>n; cin>>w; int val[n], weight[n]; for(int i=0;i>val[i]; } for(int i=0;i>weight[i]; } cout< using namespace std; long long int dp[20][180][2]; long long int getDigits(long long int x, vector &digits) { while(x) { digits.push_back(x%10); x = x/10; } } long long int digitSum(int idx, int sum, int tight, vector &digit) { if(idx == -1) { return sum; } if(dp[idx][sum][tight] != -1 && tight != 1) { return dp[idx][sum][tight]; } long long int ret = 0; int k = (tight)?digit[idx]:9; int i; for(i=0;i<=k;i++) { int newTight = (digit[idx] == i)?tight:0; ret += digitSum(idx - 1, sum + i, newTight, digit); } return ret; } long long int rangeDigitSum(int a, int b) { memset(dp, -1, sizeof(dp)); vector digitA; getDigits(a-1, digitA); long long int ans1 = digitSum(digitA.size() - 1, 0, 1, digitA); vector digitB; getDigits(b, digitB); long long int ans2 = digitSum(digitB.size() - 1, 0, 1, digitB); return (ans2 - ans1); } int main() { int a,b; cin>>a>>b; cout<<(rangeDigitSum(a,b)); return 0; } ================================================ FILE: dp/coinchange.cpp ================================================ #include using namespace std; ///Coin Change Problem ///Top Down DP int dp[100] = {0}; int coinWaysTD(int amt,int coins[],int n){ if(amt==0){ dp[0] = 1; return 1; } ///Recursive Case int ans = 0; if(dp[amt]!=0){ return dp[amt]; } for(int i=0;i=0){ ans += coinWaysTD(amt-coins[i],coins,n); } } ///Store and return for the first time dp[amt] = ans; return ans; } ///Bottom Up DP int coinWaysBU(int amt,int coins[],int n){ int dp[100] = {0}; dp[0] = 1; for(int i=1;i<=amt;i++){ for(int j=0;j=0){ dp[i] += dp[i-coins[j]]; } } } return dp[amt]; } int main(){ int coins[] = {1,2,3,8}; int amount = 3; cout< #include #include #include using namespace std; inline int min(int a,int b,int c){ return min(a,min(b,c)); } int dp[100][100]; int editDistance(string a,string b,int m,int n){ if(m==0) return n; if(n==0) return m; if(dp[m][n]!=-1) return dp[m][n]; int ans=0; if(a[m-1]==b[n-1]) ans=editDistance(a,b,m-1,n-1); else ans=1+min(editDistance(a,b,m-1,n),editDistance(a,b,m,n-1),editDistance(a,b,m-1,n-1)); return dp[m][n]=ans; } int main(){ memset(dp,-1,sizeof(dp)); string a,b; a="coding"; b="hacking"; cout< using namespace std; int eggdrop(int n, int k) { int eggs[n+1][k+1]; for(int i=1;i<=n;i++) { eggs[i][0]=0; eggs[i][1]=1; } for(int i=1;i<=k;i++) { eggs[1][i]=i; } for(int i=2;i<=n;i++) { for(int j=2;j<=k;j++) { eggs[i][j]=INT_MAX; for(int x=1; x<=j; x++) { int res = 1+max(eggs[i-1][x-1], eggs[i][j-x]); if(res>t; while(t--) { cin>>n>>k; cout< using namespace std; int main() { int t,n,cur_max,max_fin; cin>>t; while(t--) { cin>>n; int arr[n]; for(int i=0;i>arr[i]; cur_max=arr[0];max_fin=arr[0]; for(int i=1;i #include using namespace std; int lcs(string s1,string s2,int i,int j){ if(i==0||j==0){ return 0; } if(s1[i-1]==s2[j-1]){ return 1 + lcs(s1,s2,i-1,j-1); } return max(lcs(s1,s2,i,j-1),lcs(s1,s2,i-1,j)); } int lcsMatrix(string s1,string s2) { int dp[100][100]; int l1 = s1.length(); int l2 = s2.length(); for(int i=0;i<=l1;i++){ for(int j=0;j<=l2;j++){ if(i==0||j==0){ dp[i][j] = 0; continue; } else if(s1[i-1]==s2[j-1]){ dp[i][j] = 1 + dp[i-1][j-1]; } else { dp[i][j] = max(dp[i-1][j],dp[i][j-1]); } } } for(int i=0;i<=l1;i++){ for(int j=0;j<=l2;j++){ cout<0 && y>0){ if(dp[x][y]==dp[x-1][y-1]+1){ cout< using namespace std; int main() { int t,n; cin>>t; while(t--) { cin>>n; int arr[n],lis[n]; for(int i=0;i>arr[i]; lis[i]=1; } int max=1; for(int i=1;imax) max=lis[i]; } cout< #include #include #include using namespace std; //random matrix sizes int mat[]={10,5,2,8,16,10,5,3,8,9,18,15,3,6,11,5,3,2,8,3,9,7,4,9,3}; //5 15 and 25 as number of matrices int nn[]={5,10,25}; //funtion for matrix chain multiplication using div and cnquer int mcmdnc(int a,int b) { int cost; //base Case if(a==b) cost=0; else { for(int i=a;i= arr[index - 1]: index = index + 1 else: arr[index], arr[index-1] = arr[index-1], arr[index] index = index - 1 return arr n=int(input()) arr=[] for i in range(n): c=int(input()) arr.append(c) arr = gnomeSort(arr, n) print "Sorted sequence after applying Gnome Sort :", for i in arr: print(i) ================================================ FILE: graph/Kosaraju_algorithm ================================================ #include #include #include using namespace std; class Graph { int V; // No. of vertices list *adj; // An array of adjacency lists // Fills Stack with vertices (in increasing order of finishing // times). The top element of stack has the maximum finishing // time void fillOrder(int v, bool visited[], stack &Stack); // A recursive function to print DFS starting from v void DFSUtil(int v, bool visited[]); public: Graph(int V); void addEdge(int v, int w); // The main function that finds and prints strongly connected // components void printSCCs(); // Function that returns reverse (or transpose) of this graph Graph getTranspose(); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } // A recursive function to print DFS starting from v void Graph::DFSUtil(int v, bool visited[]) { // Mark the current node as visited and print it visited[v] = true; cout << v << " "; // Recur for all the vertices adjacent to this vertex list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited); } Graph Graph::getTranspose() { Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex list::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { g.adj[*i].push_back(v); } } return g; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::fillOrder(int v, bool visited[], stack &Stack) { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) if(!visited[*i]) fillOrder(*i, visited, Stack); // All vertices reachable from v are processed by now, push v Stack.push(v); } // The main function that finds and prints all strongly connected // components void Graph::printSCCs() { stack Stack; // Mark all the vertices as not visited (For first DFS) bool *visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; // Fill vertices in stack according to their finishing times for(int i = 0; i < V; i++) if(visited[i] == false) fillOrder(i, visited, Stack); // Create a reversed graph Graph gr = getTranspose(); // Mark all the vertices as not visited (For second DFS) for(int i = 0; i < V; i++) visited[i] = false; // Now process all vertices in order defined by Stack while (Stack.empty() == false) { // Pop a vertex from stack int v = Stack.top(); Stack.pop(); // Print Strongly connected component of the popped vertex if (visited[v] == false) { gr.DFSUtil(v, visited); cout << endl; } } } // Driver program to test above functions int main() { // Create a graph given in the above diagram int n ; cout << "Enter how many vertices your graph will have?" << endl ; cin >> n ; Graph g(n) ; char ch = 'y' ; while(ch=='y'){ int src ; int dst ; cout << "Enter the originating vertice and the destination vertice with a space" << endl ; cin >> src >> dst ; g.addEdge(src, dst) ; cout << "Do you want to add another edge? type 'y' for yes, 'n' for no" << endl ; cin >> ch ; cout << endl ; } cout << "Following are strongly connected components in " "given graph \n"; g.printSCCs(); return 0; } ================================================ FILE: graph/bfs_dfs/bfs/BFS.cpp ================================================ // Program to print BFS traversal from a given source vertex (s). // BFS(int s) traverses vertices reachable from s. #include #include using namespace std; // This class represents a directed graph using adjacency list representation class Graph { int V; // No. of vertices // Pointer to an array containing adjacency list. list *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints BFS traversal from a given source s void BFS(int s); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } ///// MAIN LOGIC ALGORITHMIC FUNCTION ///// void Graph::BFS(int s) { // Mark all the vertices as not visited bool *visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS list queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); // 'i' will be used to get all adjacent vertices of the current vertex. list::iterator i; while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << " "; queue.pop_front(); // Get all adjacent vertices of the dequeued vertex s. // If a adjacent has not been visited, then mark it visited and enqueue it for (i = adj[s].begin(); i != adj[s].end(); ++i) { if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } } } int main() { // Create a graph (given is an example) Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Following is Breadth First Traversal " << "(starting from vertex 2) \n"; g.BFS(2); //2 is the starting vertex. return 0; } ================================================ FILE: graph/bfs_dfs/bfs/BFS.py ================================================ # Program to print BFS traversal from a given source vertex. # BFS(int s) traverses vertices reachable from s. from collections import defaultdict # This class represents a directed graph using adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) ### Main Algorithmic Function # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False]*(len(self.graph)) # Create a queue for BFS queue = [] # Mark the source node as visited and enqueue it queue.append(s) visited[s] = True while queue: # Dequeue a vertex from queue and print it s = queue.pop(0) print s, # Get all adjacent vertices of the dequeued vertex s. # If a adjacent has not been visited, then mark it visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True # Create a graph (given is an example) g = Graph() g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 2) g.addEdge(2, 0) g.addEdge(2, 3) g.addEdge(3, 3) print "Following is Breadth First Traversal (starting from vertex 2)" g.BFS(2) ================================================ FILE: graph/bfs_dfs/bfs/bfs.cpp ================================================ #include using namespace std; #define For(i,a,b) for(int i=(a);i<(b);i++) void bfs(int n, std::vector v[], int s){ int c[n+1]={0};//colour of vertices //0 white 1 gray c[s] = 1; queue q; q.push(s); int t; while(!q.empty()){ t = q.front(); cout << t << " "; //q.front(); q.pop(); For(i,0,v[t].size()){ if(c[v[t][i]] == 0){ c[v[t][i]] = 1; q.push(v[t][i]); } } } } int main(){ cout << "Enter number of vertices : "; int n; cin >> n; std::vector v[n+1]; cout << "Enter number of edges (Undirected Graph) : "; int e,a,b; cin >> e; cout << "Enter edges now : "; For(i,0,e){ cout << "\nEdge no." << i+1 << " : "; cin >> a; cin >> b; v[a].push_back(b); v[b].push_back(a); } cout << "Find BFS from which vertex ? "; int s;cin >> s; bfs(n,v,s); } ================================================ FILE: graph/bfs_dfs/dfs/DFS.cpp ================================================ #include #include #include #include using namespace std; #define WHITE 0 #define GRAY 1 #define BLACK 2 #define MAXV 15 typedef pair ii; // Vertex, Weight typedef vector vii; typedef map mii; vii adjList[MAXV]; // Adjacency List mii dfs_num; mii dfs_parent; mii dfs_d; mii dfs_f; int time_c = 0; void dfs(int u) { dfs_num[u] = GRAY; dfs_d[u] = ++time_c; for(vii::iterator it = adjList[u].begin(); it != adjList[u].end(); it++) { // Finding edges in the graph if (dfs_num[it->first] == WHITE) { dfs_parent[it->first] = u; dfs(it->first); } else if (dfs_num[it->first] == GRAY) { if (it->first != dfs_parent[u]) { // Finding return edges } else { // Finding bidirectional edges } } else if (dfs_num[it->first] == BLACK) { // Finding crossover edges } } dfs_num[u] = BLACK; dfs_f[u] = ++time_c; } void printTree(int V) { for (int i = 1; i <= V; i++) { cout << "Vértices: "; cout << setw(2) << i << " Discovery time: "; cout << setw(2) << dfs_d[i] << " End time: "; cout << setw(2) << dfs_f[i] << " Predecessor: "; if (dfs_parent[i] >= 0) { cout << setw(3) << dfs_parent[i] << endl; } else { cout << setw(3) << "NIL " << endl; } } } int main() { int V,E,X,Y; int IN; cin >> V >> E; for (int i=0; i> X >> Y; adjList[X].push_back(make_pair(Y,0)); } cin >> IN; dfs(IN); printTree(V); return 0; } ================================================ FILE: graph/bfs_dfs/dfs/DFS.java ================================================ /** * Input file example: * * 8 * INF 1 1 INF INF INF INF INF * 1 INF INF 1 1 INF INF INF * 1 INF INF INF INF 1 1 INF * INF 1 INF INF INF INF INF INF * INF 1 INF INF INF INF INF 1 * INF INF 1 INF INF INF INF INF * INF INF 1 INF INF INF INF INF * INF INF INF INF 1 INF INF INF * 1 * * First line is number of elements in graph * Next n-lines is graph * Last line is begin point * * Output file: * 1 -> 2 -> 4 -> 5 -> 8 -> 3 -> 6 -> 7 * */ package dfs; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.*; public class DFS { private static final String INPUT_FILE_PATH = "input.txt"; private static final String OUTPUT_FILE_PATH = "output.txt"; private static final int INF = Integer.MAX_VALUE / 2; private static boolean used[]; private static int begin; public static void main(String[] args) { int[][] matrix = readMatrixFromFile(); used = new boolean[matrix.length]; String answer = dfs(matrix, begin); printSolution(answer); } private static int[][] readMatrixFromFile() { int[][] matrix = null; try (Scanner scanner = new Scanner(new FileInputStream(INPUT_FILE_PATH))) { int matrixSize = Integer.parseInt(scanner.nextLine()); matrix = new int[matrixSize][matrixSize]; for (int row = 0; row < matrixSize; row++) { String[] numbers = scanner.nextLine().split(" "); for (int col = 0; col < matrixSize; col++) { if (numbers[col].equals("INF")) { matrix[row][col] = INF; } else { matrix[row][col] = Integer.parseInt(numbers[col]); } } } begin = scanner.nextInt() - 1; } catch (IOException e) { e.printStackTrace(); } return matrix; } private static String dfs(int[][] matrix, int v) { StringBuilder answer = new StringBuilder(); used[v] = true; answer.append(v + 1).append(" "); for (int nv = 0; nv < matrix.length; nv++) { if (!used[nv] && matrix[v][nv] != INF) { answer.append(dfs(matrix, nv)); } } return answer.toString(); } private static void printSolution(String answer) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH))) { String[] points = answer.split(" "); writer.write(points[0]); for (int i = 1; i < points.length; i++) { writer.write(" -> " + points[i]); } } catch (IOException e) { e.printStackTrace(); } } } ================================================ FILE: heap/heap.hpp ================================================ #include using namespace std; template class heap { private: T *arr; int size; int capacity; int type; // if 1, max heap else if -1 min heap public: heap() : arr(NULL), size(0), capacity(0), type(0) {} heap(int capacity, int type) : arr(new T[capacity]), size(0), capacity(capacity), type(type) {} // get private values int get_size(){ return this->size; } int get_capacity(){ return this->capacity; } int get_type(){ return this->type; } // util functions // get index of parent from child index int get_parent(int child_index){ if(child_index <=0 || child_index >= this->capacity) return -1; return (child_index-1)/2; } bool has_left_child(int parent_index){ return (parent_index * 2 + 1 < this->size) && (parent_index >= 0); } bool has_right_child(int parent_index){ return (parent_index * 2 + 2 < this->size) && (parent_index >= 0); } // get index of left child from parent's index int get_left_child(int parent_index){ int left_child_index = parent_index * 2 + 1; if(!has_left_child(parent_index)) return -1; return left_child_index; } // get index of left child from parent's index int get_right_child(int parent_index){ int right_child_index = parent_index * 2 + 2; if(!has_right_child(parent_index)) return -1; return right_child_index; } // get max / min, depending on the type of heap // get minimum from min heap T get_min(){ // returns null if array is empty or heap type is max if(this->size == 0 || this->type == 1) return '\0'; return this->arr[0]; } // get maximum from max heap T get_max(){ // returns null if array is empty or heap type is min if(this->size == 0 || this->type == -1) return '\0'; return this->arr[0]; } // takes location of element as input and heapifies our array downwards // considering max heap void down(int parent_index){ int left_child_index = get_left_child(parent_index), right_child_index = get_right_child(parent_index); if(left_child_index == -1 && right_child_index == -1) return; // everything is valid, so let's proceed to finding the next max element that can be swapped with the parent int max_element = parent_index; if(left_child_index != -1){ if(arr[left_child_index] > arr[parent_index]) max_element = left_child_index; else max_element = parent_index; } else max_element = parent_index; if(right_child_index != -1){ if(arr[right_child_index] > arr[max_element]) max_element = right_child_index; } if(max_element == -1) return; // swap max_element with parent if(max_element != parent_index){ int temp = arr[max_element]; arr[max_element] = arr[parent_index]; arr[parent_index] = temp; } down(max_element); } bool is_full(){ return this->size == this->capacity; } bool is_empty(){ return this->size == 0; } void resize(){ T *old_array = this->arr; this->arr = static_cast< T* > (malloc(sizeof(T) * this->capacity * 2)); if(this->arr == NULL){ cout << "Memory error" << endl; return; } for(int i=0;icapacity;i++) this->arr[i] = old_array[i]; this->capacity *= 2; delete [] old_array; } void insert(T data){ if(this->is_full()) this->resize(); this->size++; int i = this->size - 1; while(i>0 && data > this->arr[get_parent(i)]){ this->arr[i] = this->arr[get_parent(i)]; i = get_parent(i); } this->arr[i] = data; } // another constructor to create a heap from an array heap(T ar[], int capacity, int type) : arr(new T[capacity]), size(capacity), capacity(capacity), type(type) { for(int i=0;iarr[i] = ar[i]; for(int i=(capacity-1)/2;i>=0;i--) down(i); } void print(){ cout << "Printing heap: " << endl; for(int i=0;isize;i++) cout << this->arr[i] << " "; cout << endl; } bool is_heap(){ int i = 0; // assuming max heap for(int j=0;jsize;j++){ if(this->has_left_child(j) && this->arr[this->get_left_child(j)] > this->arr[j]) return false; if(this->has_right_child(j) && this->arr[this->get_right_child(j)] > this->arr[j]) return false; } return true; } }; ================================================ FILE: heap/min_heap.cpp ================================================ #include #include using namespace std; class minHeap{ vector v; void heapify(int i){ int l=2*i; int r=2*i+1; int minIndex = i; if(l < v.size() && v[l]1){ swap(v[index],v[parent]); index=parent; parent=parent/2; } } int getmin(){ return v[1]; } void pop(){ int last=v.size()-1; swap(v[1],v[last]); v.pop_back(); heapify(1); } bool isEmpty(){ return v.size()==1; } }; int main(){ int a[] = {10,45,33,211,16,120,150,132}; int n = sizeof(a)/sizeof(int); minHeap h; for(int i=0;i using namespace std; // Function to find the waiting time for all // processes void findWaitingTime(int processes[], int n, int bt[], int wt[]) { // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++ ) wt[i] = bt[i-1] + wt[i-1] ; } // Function to calculate turn around time void findTurnAroundTime( int processes[], int n, int bt[], int wt[], int tat[]) { // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i]; } //Function to calculate average time void findavgTime( int processes[], int n, int bt[]) { int wt[n], tat[n], total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details cout << "Processes "<< " Burst time " << " Waiting time " << " Turn around time\n"; // Calculate total waiting time and total turn // around time for (int i=0; i using namespace std; // Function to find the waiting time for all // processes void findWaitingTime(int processes[], int n, int bt[], int wt[], int quantum) { // Make a copy of burst times bt[] to store remaining // burst times. int rem_bt[n]; for (int i = 0 ; i < n ; i++) rem_bt[i] = bt[i]; int t = 0; // Current time // Keep traversing processes in round robin manner // until all of them are not done. while (1) { bool done = true; // Traverse all processes one by one repeatedly for (int i = 0 ; i < n; i++) { // If burst time of a process is greater than 0 // then only need to process further if (rem_bt[i] > 0) { done = false; // There is a pending process if (rem_bt[i] > quantum) { // Increase the value of t i.e. shows // how much time a process has been processed t += quantum; // Decrease the burst_time of current process // by quantum rem_bt[i] -= quantum; } // If burst time is smaller than or equal to // quantum. Last cycle for this process else { // Increase the value of t i.e. shows // how much time a process has been processed t = t + rem_bt[i]; // Waiting time is current time minus time // used by this process wt[i] = t - bt[i]; // As the process gets fully executed // make its remaining burst time = 0 rem_bt[i] = 0; } } } // If all processes are done if (done == true) break; } } // Function to calculate turn around time void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) { // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i]; } // Function to calculate average time void findavgTime(int processes[], int n, int bt[], int quantum) { int wt[n], tat[n], total_wt = 0, total_tat = 0; // Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt, quantum); // Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); // Display processes along with all details cout << "Processes "<< " Burst time " << " Waiting time " << " Turn around time\n"; // Calculate total waiting time and total turn // around time for (int i=0; i using namespace std; struct Process { int pid; // Process ID int bt; // Burst Time int art; // Arrival Time }; // Function to find the waiting time for all // processes void findWaitingTime(Process proc[], int n, int wt[]) { int rt[n]; // Copy the burst time into rt[] for (int i = 0; i < n; i++) rt[i] = proc[i].bt; int complete = 0, t = 0, minm = INT_MAX; int shortest = 0, finish_time; bool check = false; // Process until all processes gets // completed while (complete != n) { // Find process with minimum // remaining time among the // processes that arrives till the // current time` for (int j = 0; j < n; j++) { if ((proc[j].art <= t) && (rt[j] < minm) && rt[j] > 0) { minm = rt[j]; shortest = j; check = true; } } if (check == false) { t++; continue; } // Reduce remaining time by one rt[shortest]--; // Update minimum minm = rt[shortest]; if (minm == 0) minm = INT_MAX; // If a process gets completely // executed if (rt[shortest] == 0) { // Increment complete complete++; // Find finish time of current // process finish_time = t + 1; // Calculate waiting time wt[shortest] = finish_time - proc[shortest].bt - proc[shortest].art; if (wt[shortest] < 0) wt[shortest] = 0; } // Increment time t++; } } // Function to calculate turn around time void findTurnAroundTime(Process proc[], int n, int wt[], int tat[]) { // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n; i++) tat[i] = proc[i].bt + wt[i]; } // Function to calculate average time void findavgTime(Process proc[], int n) { int wt[n], tat[n], total_wt = 0, total_tat = 0; // Function to find waiting time of all // processes findWaitingTime(proc, n, wt); // Function to find turn around time for // all processes findTurnAroundTime(proc, n, wt, tat); // Display processes along with all // details cout << "Processes " << " Burst time " << " Waiting time " << " Turn around time\n"; // Calculate total waiting time and // total turnaround time for (int i = 0; i < n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; cout << " " << proc[i].pid << "\t\t" << proc[i].bt << "\t\t " << wt[i] << "\t\t " << tat[i] << endl; } cout << "\nAverage waiting time = " << (float)total_wt / (float)n; cout << "\nAverage turn around time = " << (float)total_tat / (float)n; } // Driver code int main() { Process proc[] = { { 1, 6, 1 }, { 2, 8, 1 }, { 3, 7, 2 }, { 4, 3, 3 } }; int n = sizeof(proc) / sizeof(proc[0]); findavgTime(proc, n); return 0; } ================================================ FILE: os/scheduling/readme.txt ================================================ Various Scheduling algorithms used in Operating System First Come First Serve Shortest Job first Shortest Remaining Time First Priority Scheduling Round Robin Scheduling ================================================ FILE: shellsort.c ================================================ #include void shellsort(int arr[], int num) { int i, j, k, tmp; for (i = num / 2; i > 0; i = i / 2) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..i-1] are already in //gapped order keep adding one more element until the //entire array is gap sorted. for (j = i; j < num; j++) { for(k = j - i; k >= 0; k = k - i) { if (arr[k+i] >= arr[k]) break; else { tmp = arr[k]; arr[k] = arr[k+i]; arr[k+i] = tmp; } } } } } int main() { int arr[30]; int k, num; printf("Enter total no. of elements : "); scanf("%d", &num); printf("\nEnter %d numbers: ", num); for (k = 0 ; k < num; k++) { scanf("%d", &arr[k]); } shellsort(arr, num); printf("\n Sorted array is: "); for (k = 0; k < num; k++) printf("%d ", arr[k]); return 0; } ================================================ FILE: sieve_of_eratoshthenes.cpp ================================================ //isPrime denotes the array which will be used to mark prime numbers. //N is the limit, upto which we need to find prime numbers. bool isPrime[N+1]; void sieve() { int i, j; memset(isPrime, true, sizeof(isPrime)) for(i = 2; i*i <= N; i++) { if(isPrime[i] == true) { for(j = i*i; j <= N; j = j+i) isPrime[j] = false; } } } ================================================ FILE: square_root_decomposition ================================================ // C++ program to demonstrate working of Square Root // Decomposition. //This is a programme that will help to reduce time complexity //for big arrays #include "iostream" #include "math.h" using namespace std; #define MAXN 10000 #define SQRSIZE 100 int arr[MAXN]; // original array int block[SQRSIZE]; // decomposed array int blk_sz; // block size // Time Complexity : O(1) void update(int idx, int val) { int blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val; } // Time Complexity : O(sqrt(n)) int query(int l, int r) { int sum = 0; while (l int matrix[25][25], visited_cities[10], limit, cost = 0; int tsp(int c) { int count, nearest_city = 999; int minimum = 999, temp; for(count = 0; count < limit; count++) { if((matrix[c][count] != 0) && (visited_cities[count] == 0)) { if(matrix[c][count] < minimum) { minimum = matrix[count][0] + matrix[c][count]; } temp = matrix[c][count]; nearest_city = count; } } if(minimum != 999) { cost = cost + temp; } return nearest_city; } void minimum_cost(int city) { int nearest_city; visited_cities[city] = 1; printf("%d ", city + 1); nearest_city = tsp(city); if(nearest_city == 999) { nearest_city = 0; printf("%d", nearest_city + 1); cost = cost + matrix[city][nearest_city]; return; } minimum_cost(nearest_city); } int main() { int i, j; printf("Enter Total Number of Cities:\t"); scanf("%d", &limit); printf("\nEnter Cost Matrix\n"); for(i = 0; i < limit; i++) { printf("\nEnter %d Elements in Row[%d]\n", limit, i + 1); for(j = 0; j < limit; j++) { scanf("%d", &matrix[i][j]); } visited_cities[i] = 0; } printf("\nEntered Cost Matrix\n"); for(i = 0; i < limit; i++) { printf("\n"); for(j = 0; j < limit; j++) { printf("%d ", matrix[i][j]); } } printf("\n\nPath:\t"); minimum_cost(0); printf("\n\nMinimum Cost: \t"); printf("%d\n", cost); return 0; }