├── .gitattributes ├── .gitignore ├── Data Structures ├── Stack │ ├── Main.java │ └── README.md ├── Prefix Sum Array │ ├── Prefix_Sum_Array.java │ └── README.md ├── Difference Array │ └── Difference_Array.java └── Disjoint Union Set │ ├── Disjoint_Union_Set.java │ └── README.md ├── Graph Theory ├── Dijkstras │ ├── Dijkstra Matrix │ │ ├── README.md │ │ └── Dijkstras.java │ └── Dijkstra Optimized │ │ ├── README.md │ │ └── Dijkstra.java ├── Depth First Search │ └── DFS.java ├── Breadth First Search │ ├── BFS │ │ └── BFS.java │ └── Grid BFS │ │ └── BFS.java └── Kruskals │ └── Kruskals.java ├── String Manipulation ├── Lexicographically Least Substring │ └── Lexicographically_Least_Substring.java └── Counting Occurences In A String │ └── Counting_Occurences_In_A_String.java ├── Dynamic Programming ├── Longest Increasing Subsequence │ └── LIS.java ├── Longest Common Subsequence │ └── LCS.java ├── Knapsack │ ├── Knapsack 1 │ │ └── Knapsack1.java │ └── Knapsack 2 │ │ └── Knapsack2.java └── Bit Mask │ └── Bit_Mask.md ├── Sorting ├── Bubble Sort │ └── Bubble_Sort.java └── Merge Sort │ └── Merge_Sort.java └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Eclipse files 5 | .classpath 6 | .project 7 | 8 | # Log file 9 | *.log 10 | 11 | # BlueJ files 12 | *.ctxt 13 | 14 | # Mobile Tools for Java (J2ME) 15 | .mtj.tmp/ 16 | 17 | # Package Files # 18 | *.jar 19 | *.war 20 | *.nar 21 | *.ear 22 | *.zip 23 | *.tar.gz 24 | *.rar 25 | 26 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 27 | hs_err_pid* 28 | -------------------------------------------------------------------------------- /Data Structures/Stack/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Main { 3 | /** 4 | * A stack is a first in last out data structure 5 | **/ 6 | public static void main(String[]args){ 7 | Scanner sc = new Scanner(System.in); 8 | Stack st = new Stack(); 9 | for(int i = 1; i <= 10; i++) 10 | st.push(i); 11 | while(!st.isEmpty()) { 12 | System.out.print(st.pop() + " "); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Graph Theory/Dijkstras/Dijkstra Matrix/README.md: -------------------------------------------------------------------------------- 1 | # Dijkstras 2 | 3 | Dijkstras is an algorithm that finds the shortest path between 2 nodes in a weighted graph. 4 | 5 | This algorithm runs in O(N2) time, but can be optimized. 6 | 7 | The algorithm works by taking one node, include it into the shortest path graph, then finding the edge that is the smallest, and take that node that is connected by that edge. Then the algorithm repeats itself until it finds the shortest path. 8 | 9 | This algorithm is very similar to Prim's algorithm. 10 | 11 | See the file for implmentation details. 12 | -------------------------------------------------------------------------------- /Graph Theory/Dijkstras/Dijkstra Optimized/README.md: -------------------------------------------------------------------------------- 1 | # Dijkstras Optimized 2 | 3 | Dijkstras is a algorithm that finds the shortest path between 2 nodes in a weighted graph. 4 | 5 | This optimized version of dijkstras can solve the normal dijkstras algorithm in O(N Log N) time, making it significantly faster than the normal one. 6 | But this only works if the graph is not a complete graph, meaning there's less ```N - 1``` edges present, as it will also run in O(N2) time and might even run slower than the normal dijkstras. 7 | 8 | Please look at the dijkstras under ```Dijkstra Matrix``` for the explanation of the dijkstras algorithm. 9 | -------------------------------------------------------------------------------- /String Manipulation/Lexicographically Least Substring/Lexicographically_Least_Substring.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class LexicographicallyLeastSubstring { 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | String s = in.nextLine(); 6 | int K = in.nextInt(); 7 | String min = s.substring(0, K); 8 | for(int i = 1; i < s.length() - K; i++) 9 | { 10 | String temp = s.substring(i,i + K); 11 | if(temp.compareTo(min) < 0) 12 | min = temp; 13 | } 14 | System.out.println(min); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /String Manipulation/Counting Occurences In A String/Counting_Occurences_In_A_String.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class CoutingOccurencesInAString { 3 | public static void main(String[]args) { 4 | Scanner sc = new Scanner(System.in); 5 | String s[] = sc.nextLine().split(""); 6 | int scnt = 0, ocnt = 0, ucnt = 0, pcnt = 0; 7 | for(int i = s.length - 1; i >= 0; i--) { 8 | if(s[i] == 'p') pcnt++; 9 | if(s[i] == 'u') ucnt += pcnt; 10 | if(s[i] == 'o') ocnt += ucnt; 11 | if(s[i] == 's') snct += ocnt; 12 | } 13 | System.out.println(scnt); 14 | sc.close(); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Data Structures/Prefix Sum Array/Prefix_Sum_Array.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Prefix_Sum_Array { 3 | public static void main(String[]args){ 4 | Scanner sc = new Scanner(System.in); 5 | int n = sc.nextInt(); 6 | int q = sc.nextInt(); 7 | long psa[] = new long[n + 1]; 8 | for(int i = 1; i <= n; i++) { 9 | psa[i] = sc.nextInt(); 10 | psa[i] += psa[i-1]; 11 | } 12 | for(int i = 1; i <= q; i++) { 13 | int l = sc.nextInt(); 14 | int r = sc.nextInt(); 15 | System.out.println("Sum in ranges " + l + " and " + r + " is " + (psa[r] - psa[l-1])); 16 | } 17 | sc.close(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Increasing Subsequence/LIS.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class LIS { 3 | public static void main(String[]args) { 4 | Scanner sc = new Scanner(System.in); 5 | int n = sc.nextInt(), a[] = new int[n]; 6 | for(int i = 0; i < n; i++) a[i] = sc.nextInt(); 7 | System.out.println(lis(a, n)); sc.close(); 8 | } 9 | static int binarySearch(int a[], int l, int r, int key) { 10 | while(r - l > 1) { 11 | int m = l + (r - l ) / 2; 12 | if(a[m] >= key) r = m; 13 | else l = m; 14 | } 15 | return r; 16 | } 17 | static int lis(int v[], int n) { 18 | if(n == 0) return 0; 19 | int a[] = new int[n], len = 1; 20 | a[0] = v[0]; 21 | 22 | for(int i = 1; i < n; i++) { 23 | if(v[i] < a[0]) a[0] = v[i]; 24 | else if(v[i] > a[len - 1]) a[len++] = v[i]; 25 | else a[binarySearch(a, -1, len - 1, v[i])] = v[i]; 26 | } 27 | return len; 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/Bubble_Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Bubble_Sort { 3 | public static void main(String[]args){ 4 | Scanner sc = new Scanner(System.in); 5 | int n = sc.nextInt(); 6 | int array[] = new int[n]; 7 | for(int i = 0; i < n; i++) { 8 | array[i] = sc.nextInt(); 9 | } 10 | boolean isSorted = false; 11 | while(!isSorted) { 12 | isSorted = true; 13 | for(int i = 0; i < n - 1; i++) { 14 | if(array[i] > array[i + 1]){ 15 | int temp = array[i]; 16 | array[i] = array[i + 1]; 17 | array[i + 1] = temp; 18 | isSorted = false; 19 | } 20 | } 21 | } 22 | for(int i = 0; i < n; i++) { 23 | System.out.print(array[i] + " "); 24 | } 25 | sc.close(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Graph Theory/Depth First Search/DFS.java: -------------------------------------------------------------------------------- 1 | /* Based on EspiDev's method. 2 | Feel free to use this in your own CP solutions. 3 | By Raymo111. 4 | */ 5 | 6 | import java.util.*; 7 | 8 | // Depth-first search to traverse a tree 9 | public class DFS { 10 | private static int size = 5; 11 | private static ArrayList[] adjList = new ArrayList[size]; 12 | private static boolean[] visited = new boolean[size]; 13 | 14 | public static void main(String[] args) { 15 | for (int i = 0; i < size; i++) { 16 | adjList[i] = new ArrayList(); 17 | } 18 | // TODO: Get input and connect vertices 19 | } 20 | 21 | private static void dfs(int node) { 22 | // TODO: Base case (when to stop) here 23 | visited[node] = true; 24 | // TODO: Action for node here 25 | for (int i = 0; i < adjList[node].size(); i++) 26 | if (!visited[adjList[node].get(i)]) { 27 | dfs(adjList[node].get(i)); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Competitive Programming Algorithms 3 | #### By [Raymo111](https://github.com/raymo111) & [magicalsoup](https://github.com/magicalsoup) 4 | Please feel free to contribute by helping to port some of [espidev](https://github.com/espidev) and [jimgao1](https://github.com/jimgao1)'s algorithms over to Java from C++: 5 | > https://gitlab.com/EspiDev/Algorithms \ 6 | > https://github.com/jimgao1/competitive-programming/tree/master/Algorithms 7 | 8 | This set of algorithms contains levels ranging from easy to advanced. 9 | 10 | Please read https://github.com/magicalsoup/CCC-Junior-Prep to get a better understanding in the field of competitive programming, such as time complexity and memory allocation. 11 | 12 | All algorithms should contain a ```README.md``` file, explaining how the algorithm works, with a file labled either as ```main.java``` or the algortihm's name + ```.java``` showing an implmentation of the algorithm idea. 13 | 14 | We will try to start translating some of the algorithms into other languages such as python and c++, but for now, its all done in java. Sorry for the inconvience. 15 | -------------------------------------------------------------------------------- /Data Structures/Difference Array/Difference_Array.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Difference_Array { 3 | public static void main(String [] args) { 4 | Scanner sc = new Scanner(System.in); 5 | int n = sc.nextInt(), q = sc.nextInt(); 6 | int array[] = new int[n]; 7 | for(int i=0; i[] adjList = new ArrayList[size]; 12 | private static boolean[] visited = new boolean[size]; 13 | 14 | public static void main(String[] args) { 15 | for (int i = 0; i < size; i++) { 16 | adjList[i] = new ArrayList(); 17 | } 18 | // Get input and connect vertices 19 | } 20 | 21 | private static void bfs(int node) { 22 | Queue q = new LinkedList(); 23 | int curNode; 24 | q.offer(node); // Add node to queue 25 | while (!q.isEmpty()) { 26 | curNode = q.poll(); 27 | visited[curNode] = true; // Mark visited 28 | // Action for node here 29 | for (int i = 0; i < adjList[curNode].size(); i++) // Add child nodes to queue 30 | if (!visited[adjList[curNode].get(i)]) { // Check for child node having been visited 31 | bfs(adjList[curNode].get(i)); // Add child node 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Graph Theory/Dijkstras/Dijkstra Matrix/Dijkstras.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Dijkstras { //single shortest path 3 | static Scanner sc = new Scanner(System.in); 4 | 5 | public static void main(String[] args) { 6 | int n = sc.nextInt(), m = sc.nextInt(), adj[][] = new int[n+1][n+1]; //adjaceny matrix 7 | for(int i = 0; i <= n; i++)Arrays.fill(adj[i], Integer.MAX_VALUE); 8 | for(int i = 1; i <= m; i++) { 9 | int u = sc.nextInt(); 10 | int v = sc.nextInt(); 11 | int w = sc.nextInt(); 12 | adj[u][v] = Math.min(adj[u][v], w); 13 | adj[v][u] = Math.min(adj[v][u], w); 14 | } 15 | int dis[] = new int[n+1]; boolean vis[] = new boolean[n+1]; 16 | Arrays.fill(dis, Integer.MAX_VALUE); 17 | dis[1] = 0; 18 | for(int i = 1; i <= n; i++) { 19 | int min = Integer.MAX_VALUE; 20 | int u = -1; 21 | for(int j = 1; j <= n; j++){ 22 | if(!vis[j] && dis[j] 5 19 | |4| 20 | |3| 21 | |2| 22 | |1| 23 | --- 24 | ``` 25 | 26 | As you can see, one was the first in, and thus its at the bottom of the stack and will be the last one out. 27 | 28 | Lets now discuss some useful methods that the stack has, and of course, you can always search up the java documentations on stack. 29 | 30 | ```java 31 | Stack st = new Stack(); 32 | 33 | st.push(x); // pushes the integer x into the stack 34 | 35 | st.add(x); // adds the integer x into the stack 36 | 37 | st.pop(); //retrieves and removes the element on the top of the stack. 38 | 39 | st.isEmpty(); // returns true if the stack is empty, false otherwise 40 | 41 | st.remove(x); // removes the element at index x, or removes the element x (depends on the way you call this method). 42 | 43 | st.indexOf(x); // returns the index of the element x, or -1 if not present 44 | 45 | st.peek(x); // retrieves the element on the top of the stack without removing it 46 | ``` 47 | 48 | There are plenty of more methods, but these ones are the most commonly used. 49 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Common Subsequence/LCS.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class LCS { 3 | /** 4 | * @NOTE: Remember, LCS always runs in O(n^2) time (best time complexity) 5 | **/ 6 | public static void main(String[]args) { 7 | Scanner sc = new Scanner(System.in); 8 | String a = sc.nextLine(), b = sc.nextLine(); 9 | int dp[][] = new int[a.length() + 1][b.length() + 1]; 10 | System.out.println(findlen(dp, a, b)); 11 | System.out.println(findword(dp, a, b)); 12 | sc.close(); 13 | } 14 | static int findLCS(int dp[][], String a, String b) { 15 | int n = a.length(), m = b.length(); 16 | for(int i = 1; i <= n; i++) { 17 | for(int j = 1; j <= m; j++) { 18 | if(a.charAt(i - 1) == b.charAt(j - 1)) 19 | dp[i][j] = dp[i - 1][j - 1] + 1; 20 | else 21 | dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); 22 | } 23 | } 24 | return dp[n][m]; 25 | } 26 | static String findword(int dp[][], String a, String b) { 27 | String res = ""; 28 | int i = a.length(), j = b.length(); 29 | while(i > 0 && j > 0) { 30 | if(a.charAt(i - 1) == b.charAt(i - 1)) { 31 | res = a.charAt(i - 1) + res; 32 | i--; j--; 33 | } 34 | else if(dp[i - 1][j] > dp[i][j - 1]) i--; 35 | else j--; 36 | } 37 | return res; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Graph Theory/Breadth First Search/Grid BFS/BFS.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class BFS { 3 | static int move[][] = {{0,1}, {1,0}, {-1,0}, {0,-1}}; 4 | public static void main(String[]args) { 5 | Scanner sc = new Scanner(System.in); 6 | int n = sc.nextInt(); 7 | char g[][] = new char[n][n]; 8 | for(int i = 0; i < n; i++) g[i] = sc.next().toCharArray(); 9 | 10 | Point start = new Point(sc.nextInt(), sc.nextInt()); 11 | Point end = new Point(sc.nextInt(), sc.nextInt()); 12 | System.out.println(bfs(start, end, g, n)); 13 | sc.close(); 14 | } 15 | static int bfs(Point start, Point end, char g[][], int n) { 16 | LinkedList q = new LinkedList(); 17 | boolean vis[][] = new boolean[n][n]; 18 | int dist[][] = new int[n][n]; 19 | q.add(start); 20 | while(!q.isEmpty()) { 21 | Point cur = q.poll(); 22 | for(int i = 0; i < 4; i++) { 23 | int nx = cur.x + move[i][0], cur.y + move[i][1]; 24 | if(nx < 0 || ny < 0 || nx >= n || ny >= n || vis[nx][ny] || g[nx][ny] == 1) continue; 25 | dist[nx][ny] = dist[cur.x][cur.y] + 1; 26 | if(nx == end.x && ny == end.y) return dist[nx][ny]; 27 | q.add(new Point(nx, ny); 28 | } 29 | } 30 | return -1; 31 | } 32 | static class Point { 33 | int x, y; 34 | public Point(int x, int y) { 35 | this.x = x; 36 | this.y = y; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Dynamic Programming/Knapsack/Knapsack 1/Knapsack1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | public class Knapsack1{ 4 | /** 5 | * @NOTE: use this when weight is small and value is big 6 | */ 7 | static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 8 | static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); 9 | static StringTokenizer st; 10 | public static void main(String[]args) throws IOException{ 11 | int n = readInt(), w = readInt(); long value[] = new long[n + 1]; int weight[] = new int[n + 1]; 12 | long dp[] = new long[w + 1]; 13 | for(int i = 1; i <= n; i++) { 14 | weight[i] = readInt(); 15 | value[i] = readLong(); 16 | } 17 | for(int i = 1; i <= n; i++) { 18 | for(int j = w; j >= weight[i]; j--) { 19 | dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]); 20 | } 21 | } 22 | pw.println(dp[w]); pw.close(); 23 | } 24 | static String next () throws IOException { 25 | while (st == null || !st.hasMoreTokens()) 26 | st = new StringTokenizer(br.readLine().trim()); 27 | return st.nextToken(); 28 | } 29 | 30 | static long readLong () throws IOException { 31 | return Long.parseLong(next()); 32 | } 33 | 34 | static int readInt () throws IOException { 35 | return Integer.parseInt(next()); 36 | } 37 | 38 | static double readDouble () throws IOException { 39 | return Double.parseDouble(next()); 40 | } 41 | 42 | static String readLine () throws IOException { 43 | return br.readLine().trim(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Graph Theory/Dijkstras/Dijkstra Optimized/Dijkstra.java: -------------------------------------------------------------------------------- 1 | 2 | // Created in honor of Espidev and with his much needed help 3 | import java.util.*; 4 | 5 | // Shortest path algorithm 6 | public class Dijkstra { 7 | static int size = 5, weights[] = new int[size]; 8 | static ArrayList[] adjList = new ArrayList[size]; 9 | 10 | public static void main(String[] args) { 11 | for (int i = 0; i < size; i++) { 12 | adjList[i] = new ArrayList(); 13 | weights[i] = 2147483647; 14 | } 15 | // Get input and connect nodes 16 | dijkstra(0); // Replace 0 with the starting node 17 | // "And the answer will be weights[dest]" - Espidev 18 | } 19 | 20 | private static void dijkstra(int nodeID) { 21 | PriorityQueue q = new PriorityQueue(); 22 | Node curNode = new Node(nodeID, 0); 23 | q.offer(curNode); // Add node to queue 24 | while (!q.isEmpty()) { 25 | curNode = q.poll(); 26 | for (Node node : adjList[curNode.nodeID]) // Add child nodes to queue 27 | if (node.weight + curNode.weight < weights[node.nodeID]) { // Check for child node having smaller weight 28 | weights[node.nodeID] = node.weight + curNode.weight; 29 | q.offer(new Node(node.nodeID, weights[node.nodeID])); // Add child node 30 | } 31 | } 32 | } 33 | 34 | static class Node implements Comparable{ // needs priority queue, so we need to implement a comparable to be able to sort the values 35 | int weight, nodeID; 36 | 37 | Node(int weight, int nodeID) { 38 | this.nodeID = nodeID; 39 | this.weight = weight; 40 | } 41 | public int compareTo(Node o){ 42 | Integer.compare(weight, o.weight); 43 | } 44 | 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Data Structures/Disjoint Union Set/README.md: -------------------------------------------------------------------------------- 1 | # Disjoint Union Set 2 | 3 | The disjoint union set data structure can be build in about O(n log n) time and can answer queries in about O(1) time. 4 | 5 | The queries is to find if any 2 nodes/sets are connected. 6 | 7 | The disjoint union sets works by putting every node under a leader node, meaning that all the nodes under the leader are connected. 8 | 9 | The disjoint union set contains 2 main methods. 10 | 11 | 1. ```Find(x)``` 12 | - this method finds the parent/leader of x 13 | 14 | 2. ```Merge(x, y)``` 15 | - connect the 2 nodes together, doesn't matter if the node itself is a leader 16 | 17 | To make a disjoint union set, we must first make everyone their own leader. 18 | 19 | ```java 20 | public static void makeSet(int n) { 21 | for(int i = 0; i <= n; i++) 22 | parentArray[i] = i; 23 | } 24 | ``` 25 | Now we will make the ```find``` method 26 | 27 | ```java 28 | public static int find(int x) { 29 | if(x != parentArray[x]) // if parentArray[x] is not x's parent 30 | parentArray[x] = find(parentArray[x]); // path compression 31 | return parentArray[x]; 32 | } 33 | ``` 34 | Here we used the path compression, this makes the ```find``` method alot faster, as we don't have to go up the chain to find the leader, as we make every node we go to the leader of the node higher in the chain, making it very easy for us to find ```x```'s leader. 35 | 36 | 37 | Now we will make the ```merge``` method 38 | 39 | ```java 40 | public static void merge(int x, int y) { 41 | int xroot = find(x); // find x's leader 42 | int yroot = find(y); // find y's leader 43 | if(xroot == yroot) return; // if they are part of the same set, we don't need to merge them 44 | 45 | 46 | 47 | } 48 | ``` 49 | -------------------------------------------------------------------------------- /Dynamic Programming/Knapsack/Knapsack 2/Knapsack2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | public class Knapsack2{ 4 | /** 5 | * @NOTE: use this when weight is big and value is small 6 | **/ 7 | static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 8 | static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); 9 | static StringTokenizer st; 10 | static int MAXN = 105, MAXV = (int)1e3 + 5; 11 | public static void main(String[]args) throws IOException{ 12 | int N = readInt(), W = readInt(); int w[] = new int[N + 1], v[] = new int[N + 1]; 13 | long dp[] = new long[MAXN * MAXV + 1]; Arrays.fill(dp, 0x3f3f3f3f3f3f3f3fL); 14 | for(int i = 0; i < N; i++) { 15 | w[i] = readInt(); 16 | v[i] = readInt(); 17 | } 18 | dp[0] = 0; 19 | for(int i = 0; i < N; i++) 20 | for(int j = MAXN * MAXN - 1; j >= v[i]; j--) 21 | dp[j] = Math.min(dp[j], dp[j - v[i]] + w[i]); 22 | 23 | for(int i = MAXN * MAXV - 1; i >= 0; i--) { 24 | if(dp[i] <= W) { 25 | pw.println(i); 26 | pw.close(); 27 | return; 28 | } 29 | } 30 | pw.close(); 31 | } 32 | static String next () throws IOException { 33 | while (st == null || !st.hasMoreTokens()) 34 | st = new StringTokenizer(br.readLine().trim()); 35 | return st.nextToken(); 36 | } 37 | 38 | static long readLong () throws IOException { 39 | return Long.parseLong(next()); 40 | } 41 | 42 | static int readInt () throws IOException { 43 | return Integer.parseInt(next()); 44 | } 45 | 46 | static double readDouble () throws IOException { 47 | return Double.parseDouble(next()); 48 | } 49 | 50 | static String readLine () throws IOException { 51 | return br.readLine().trim(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/Merge_Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Merge_Sort { 3 | public static void main(String[]args) { 4 | Scanner sc = new Scanner(System.in); 5 | int n = sc.nextInt(); 6 | int array[] = new int[n]; 7 | for(int i = 0; i < n; i++) 8 | array[i] = sc.nextInt(); 9 | 10 | mergeSort(array); 11 | for(int i = 0; i < n; i++) 12 | System.out.print(array[i] + " "); 13 | sc.close(); 14 | } 15 | public static void mergeSort(int array[]){ 16 | mergeSort(array, 0, array.length - 1); 17 | } 18 | public static void mergeSort(int array[], int left, int right) { 19 | if(left == right) return; 20 | int mid = (left + right) / 2; 21 | // sort the left 22 | mergeSort(array, left, mid); 23 | // sort the right 24 | mergeSort(array, mid + 1, right); 25 | // merge 26 | merge(array, left, mid, right); 27 | } 28 | public static void merge(int array[], int left, int mid, int right) { 29 | int leftSideSize = mid - left + 1; 30 | int rightSideSize = right - mid; 31 | 32 | int L[] = new int[leftSideSize]; 33 | int R[] = new int[rightSideSize]; 34 | 35 | // copy the arrays 36 | for(int i = 0; i < leftSideSize; i++) 37 | L[i] = array[left + i]; 38 | 39 | for(int i = 0; i < rightSideSize; i++) 40 | R[i] = array[mid + 1 + i]; 41 | 42 | int i = 0, j = 0, k = left; 43 | // merge 44 | while(i < rightSideSize && j < leftSideSize) { 45 | if(L[i] <= R[j]) { 46 | array[k] = L[i]; 47 | i++; 48 | } 49 | else { 50 | array[k] = R[j]; 51 | j++; 52 | } 53 | k++; 54 | } 55 | 56 | // copy back the remaining elements into the array 57 | while(i < leftSideSize) { 58 | array[k] = L[i]; 59 | i++; 60 | k++; 61 | } 62 | while(j < rightSideSize) { 63 | array[k] = R[j]; 64 | j++; 65 | k++; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Dynamic Programming/Bit Mask/Bit_Mask.md: -------------------------------------------------------------------------------- 1 | # Bit Masks 2 | 3 | - Bit Masks is a type of compression used on problems that have rather low bounds. It is mostly used with dynamic programming, and are used in problems where it requires to check every single possible combinaton. 4 | - Lets say you have N Kings on a N x N chess board, we can simulate all the possible ways to place all the kings so that they don't touch each other. 5 | 6 | ## How is it Done 7 | - As the name suggests, we use Bits to keep track of the different combinations. A bit is either 1 or 0, and several of them form a byte, kilobytes, and so on. 8 | - Going back to the problem above, we can say a square would be 1 if a king is placed, and a 0 if its not placed. So if we place the kings like this: 9 | 10 | ``` 11 | ------------- 12 | | K | . | K | 13 | ------------- 14 | | . | . | . | 15 | ------------- 16 | | K | . | . | 17 | ------------- 18 | ``` 19 | 20 | - Our board would look like this in bits: 21 | 22 | ``` 23 | ------------- 24 | | 1 | 0 | 1 | 25 | ------------- 26 | | 0 | 0 | 0 | 27 | ------------- 28 | | 1 | 0 | 0 | 29 | ------------- 30 | ``` 31 | 32 | - which we can then change each of the rows into a number, so the numbers from top to bottom would be `5, 0, 4`, as the in binary form, the numbers would be `101, 000, 100`. 33 | - So in essence, we have just compressed a grid into N numbers, better than having a N x N grid and checking every single one. Now we can just randomly place 1s on the grid, check the configurations, and create another state, and so on and so on. 34 | - This is a classical example of grid compression using bit mask. 35 | 36 | - The things you need to know is: 37 | 38 | - Setting a Bit: 39 | ```java 40 | static int setBit(int n, int bit) { return n |(1 << bit); } 41 | ``` 42 | - Clearing a Bit: 43 | ```java 44 | static int clearBit(int n, int bit) { return n & (~(1 << bit)); } 45 | ``` 46 | - Checking a Bit: 47 | ```java 48 | static boolean getBit(int n, int bit) { return (n & (1 << bit)) == 1;} 49 | ``` 50 | - Toggling a Bit: 51 | ```java 52 | static int toggleBit(int n, int bit) { return (n ^ (1 << bit));} 53 | ``` 54 | More information on bitMasks can be found in places such as: 55 | - https://codeforces.com/blog/entry/18169 56 | - https://www.hackerearth.com/practice/algorithms/dynamic-programming/bit-masking/tutorial/ 57 | This is a rushed summary, just to get you started on ideas, visit the sites above to learn more. 58 | -------------------------------------------------------------------------------- /Graph Theory/Kruskals/Kruskals.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | public class Kruskals{ 4 | static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 5 | static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); 6 | static StringTokenizer st; 7 | static int[] p; // create parent array 8 | public static void main(String[]args) throws IOException{ 9 | int n = readInt(), m = readInt(), cnt = 0, mst = 0; Edge e[] = new Edge[m]; p = new int[n + 1]; 10 | for(int i = 0; i < p.length; i++) p[i] = i; // initialize the parent array for disjoint set 11 | 12 | for(int i = 0; i < m; i++) { 13 | e[i] = new Edge(readInt(), readInt(), readInt()); // get values, 14 | } 15 | Arrays.sort(e); // sort the edges according to weight 16 | for(int i =0; i < m; i++) { 17 | int u = e[i].u, v = e[i].v, w = e[i].w; 18 | if(cnt == n - 1) break; // if we visited every edge, break 19 | int fu = Find(u), fv = Find(v); // find the parents of u and v 20 | if(fu != fv) { // if the nodes are not connected 21 | p[fu] = fv; // set the parent of fu to fv 22 | cnt++; // add one to number of visited edges 23 | mst += w; // add the weight to the mst 24 | } 25 | } 26 | pw.println(mst); // print mst 27 | pw.close(); 28 | } 29 | static int Find(int d) { // create method find for disjoint set 30 | if(d != p[d]) // path compression 31 | p[d] = Find(p[d]); 32 | return p[d]; 33 | } 34 | static class Edge implements Comparable{ 35 | int u, v, w; 36 | public Edge(int u, int v, int w) { 37 | this.u = u; 38 | this.v = v; 39 | this.w = w; 40 | } 41 | public int compareTo(Edge x) { // override method to allow java to sort this object 42 | return Integer.compare(w, x.w); 43 | } 44 | } 45 | static String next () throws IOException { 46 | while (st == null || !st.hasMoreTokens()) 47 | st = new StringTokenizer(br.readLine().trim()); 48 | return st.nextToken(); 49 | } 50 | 51 | static long readLong () throws IOException { 52 | return Long.parseLong(next()); 53 | } 54 | 55 | static int readInt () throws IOException { 56 | return Integer.parseInt(next()); 57 | } 58 | 59 | static double readDouble () throws IOException { 60 | return Double.parseDouble(next()); 61 | } 62 | 63 | static String readLine () throws IOException { 64 | return br.readLine().trim(); 65 | } 66 | } 67 | --------------------------------------------------------------------------------