From 2d85bd05394b1af48364994518479fef0a55f09e Mon Sep 17 00:00:00 2001 From: Kushal Das <61356005+Kushal997-das@users.noreply.github.com> Date: Sat, 3 Oct 2020 16:22:33 +0530 Subject: [PATCH 01/10] added 10 dp's problems --- DynamicProgramming/BoardPath.java | 77 ++++++++++++++ DynamicProgramming/CoinChange.java | 79 ++++++++++++++ DynamicProgramming/CountNumBinaryStrings | 97 +++++++++++++++++ DynamicProgramming/EditDistance.java | 79 ++++++++++++++ DynamicProgramming/EggDropping.java | 49 +++++++++ DynamicProgramming/Fibonacci.java | 100 ++++++++++++++++++ DynamicProgramming/FordFulkerson.java | 72 +++++++++++++ DynamicProgramming/KadaneAlgorithm.java | 55 ++++++++++ DynamicProgramming/Knapsack.java | 39 +++++++ .../LongestCommonSubsequence.java | 68 ++++++++++++ DynamicProgramming/SubsetSum.java | 46 ++++++++ 11 files changed, 761 insertions(+) create mode 100644 DynamicProgramming/BoardPath.java create mode 100644 DynamicProgramming/CoinChange.java create mode 100644 DynamicProgramming/CountNumBinaryStrings create mode 100644 DynamicProgramming/EditDistance.java create mode 100644 DynamicProgramming/EggDropping.java create mode 100644 DynamicProgramming/Fibonacci.java create mode 100644 DynamicProgramming/FordFulkerson.java create mode 100644 DynamicProgramming/KadaneAlgorithm.java create mode 100644 DynamicProgramming/Knapsack.java create mode 100644 DynamicProgramming/LongestCommonSubsequence.java create mode 100644 DynamicProgramming/SubsetSum.java diff --git a/DynamicProgramming/BoardPath.java b/DynamicProgramming/BoardPath.java new file mode 100644 index 0000000..938ee62 --- /dev/null +++ b/DynamicProgramming/BoardPath.java @@ -0,0 +1,77 @@ +package DynamicProgramming; +/* +* this is an important Algo in which +* we have starting and ending of board and we have to reach +* we have to count no. of ways +* that help to reach end point i.e number by rolling dice +* which have 1 to 6 digits + +Test Case: +here target is 10 + +int n=10; + startAlgo(); + System.out.println(bpR(0,n)); + System.out.println(endAlgo()+"ms"); + int[] strg=new int [n+1]; + startAlgo(); + System.out.println(bpRS(0,n,strg)); + System.out.println(endAlgo()+"ms"); + startAlgo(); + System.out.println(bpIS(0,n,strg)); + System.out.println(endAlgo()+"ms"); + + + +*/ +public class BoardPath { + public static long startTime; + public static long endTime; + public static void startAlgo() { + startTime=System.currentTimeMillis(); + } + public static long endAlgo() { + endTime=System.currentTimeMillis(); + return endTime-startTime; + } + public static int bpR(int start,int end){ + if(start==end) { + return 1; + } + else if(start>end) + return 0; + int count=0; + for(int dice=1;dice<=6;dice++) { + count+=bpR(start+dice,end); + } + return count; + } + public static int bpRS(int curr,int end,int strg[]){ + if(curr==end) { + return 1; + } + else if(curr>end) + return 0; + if(strg[curr]!=0) + return strg[curr]; + int count=0; + for(int dice=1;dice<=6;dice++) { + count+=bpRS(curr+dice,end,strg); + } + strg[curr]=count; + return count; + } + public static int bpIS(int curr,int end,int[]strg){ + strg[end]=1; + for(int i=end-1;i>=0;i--) { + int count=0; + for(int dice=1;dice<=6&&dice+i + * Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another, + * by counting the minimum number of operations required to transform one string into the other. The + * distance operations are the removal, insertion, or substitution of a character in the string. + *

+ *

+ * The Distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the former into the latter is: + *

+ * kitten → sitten (substitution of "s" for "k") + * sitten → sittin (substitution of "i" for "e") + * sittin → sitting (insertion of "g" at the end). + * + * @author SUBHAM SANGHAI + **/ + +import java.util.Scanner; + +public class EditDistance { + + public static int minDistance(String word1, String word2) { + int len1 = word1.length(); + int len2 = word2.length(); + // len1+1, len2+1, because finally return dp[len1][len2] + int[][] dp = new int[len1 + 1][len2 + 1]; + /* If second string is empty, the only option is to + insert all characters of first string into second*/ + for (int i = 0; i <= len1; i++) { + dp[i][0] = i; + } + /* If first string is empty, the only option is to + insert all characters of second string into first*/ + for (int j = 0; j <= len2; j++) { + dp[0][j] = j; + } + //iterate though, and check last char + for (int i = 0; i < len1; i++) { + char c1 = word1.charAt(i); + for (int j = 0; j < len2; j++) { + char c2 = word2.charAt(j); + //if last two chars equal + if (c1 == c2) { + //update dp value for +1 length + dp[i + 1][j + 1] = dp[i][j]; + } else { + /* if two characters are different , + then take the minimum of the various operations(i.e insertion,removal,substitution)*/ + int replace = dp[i][j] + 1; + int insert = dp[i][j + 1] + 1; + int delete = dp[i + 1][j] + 1; + + int min = replace > insert ? insert : replace; + min = delete > min ? min : delete; + dp[i + 1][j + 1] = min; + } + } + } + /* return the final answer , after traversing through both the strings*/ + return dp[len1][len2]; + } + + + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + String s1, s2; + System.out.println("Enter the First String"); + s1 = input.nextLine(); + System.out.println("Enter the Second String"); + s2 = input.nextLine(); + //ans stores the final Edit Distance between the two strings + int ans = minDistance(s1, s2); + System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans); + input.close(); + } +} diff --git a/DynamicProgramming/EggDropping.java b/DynamicProgramming/EggDropping.java new file mode 100644 index 0000000..f6e2ab7 --- /dev/null +++ b/DynamicProgramming/EggDropping.java @@ -0,0 +1,49 @@ +package DynamicProgramming; + +/** + * DynamicProgramming solution for the Egg Dropping Puzzle + */ +public class EggDropping { + + // min trials with n eggs and m floors + + private static int minTrials(int n, int m) { + + int[][] eggFloor = new int[n + 1][m + 1]; + int result, x; + + for (int i = 1; i <= n; i++) { + eggFloor[i][0] = 0; // Zero trial for zero floor. + eggFloor[i][1] = 1; // One trial for one floor + } + + // j trials for only 1 egg + + for (int j = 1; j <= m; j++) + eggFloor[1][j] = j; + + // Using bottom-up approach in DP + + for (int i = 2; i <= n; i++) { + for (int j = 2; j <= m; j++) { + eggFloor[i][j] = Integer.MAX_VALUE; + for (x = 1; x <= j; x++) { + result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); + + // choose min of all values for particular x + if (result < eggFloor[i][j]) + eggFloor[i][j] = result; + } + } + } + + return eggFloor[n][m]; + } + + public static void main(String args[]) { + int n = 2, m = 4; + // result outputs min no. of trials in worst case for n eggs and m floors + int result = minTrials(n, m); + System.out.println(result); + } +} diff --git a/DynamicProgramming/Fibonacci.java b/DynamicProgramming/Fibonacci.java new file mode 100644 index 0000000..e623a0a --- /dev/null +++ b/DynamicProgramming/Fibonacci.java @@ -0,0 +1,100 @@ +package DynamicProgramming; + +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +/** + * @author Varun Upadhyay (https://github.com/varunu28) + */ + +public class Fibonacci { + + private static Map map = new HashMap<>(); + + + public static void main(String[] args) { + + // Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...] + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + + System.out.println(fibMemo(n)); + System.out.println(fibBotUp(n)); + System.out.println(fibOptimized(n)); + sc.close(); + } + + /** + * This method finds the nth fibonacci number using memoization technique + * + * @param n The input n for which we have to determine the fibonacci number + * Outputs the nth fibonacci number + **/ + public static int fibMemo(int n) { + if (map.containsKey(n)) { + return map.get(n); + } + + int f; + + if (n <= 1) { + f = n; + } else { + f = fibMemo(n - 1) + fibMemo(n - 2); + map.put(n, f); + } + return f; + } + + /** + * This method finds the nth fibonacci number using bottom up + * + * @param n The input n for which we have to determine the fibonacci number + * Outputs the nth fibonacci number + **/ + public static int fibBotUp(int n) { + + Map fib = new HashMap<>(); + + for (int i = 0; i <= n; i++) { + int f; + if (i <= 1) { + f = i; + } else { + f = fib.get(i - 1) + fib.get(i - 2); + } + fib.put(i, f); + } + + return fib.get(n); + } + + + /** + * This method finds the nth fibonacci number using bottom up + * + * @param n The input n for which we have to determine the fibonacci number + * Outputs the nth fibonacci number + *

+ * This is optimized version of Fibonacci Program. Without using Hashmap and recursion. + * It saves both memory and time. + * Space Complexity will be O(1) + * Time Complexity will be O(n) + *

+ * Whereas , the above functions will take O(n) Space. + * @author Shoaib Rayeen (https://github.com/shoaibrayeen) + **/ + public static int fibOptimized(int n) { + if (n == 0) { + return 0; + } + int prev = 0, res = 1, next; + for (int i = 2; i <= n; i++) { + next = prev + res; + prev = res; + res = next; + } + return res; + } +} diff --git a/DynamicProgramming/FordFulkerson.java b/DynamicProgramming/FordFulkerson.java new file mode 100644 index 0000000..f061d89 --- /dev/null +++ b/DynamicProgramming/FordFulkerson.java @@ -0,0 +1,72 @@ +package DynamicProgramming; + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Vector; + +public class FordFulkerson { + final static int INF = 987654321; + // edges + static int V; + static int[][] capacity, flow; + + public static void main(String[] args) { + System.out.println("V : 6"); + V = 6; + capacity = new int[V][V]; + + capacity[0][1] = 12; + capacity[0][3] = 13; + capacity[1][2] = 10; + capacity[2][3] = 13; + capacity[2][4] = 3; + capacity[2][5] = 15; + capacity[3][2] = 7; + capacity[3][4] = 15; + capacity[4][5] = 17; + + System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5)); + } + + private static int networkFlow(int source, int sink) { + flow = new int[V][V]; + int totalFlow = 0; + while (true) { + Vector parent = new Vector<>(V); + for (int i = 0; i < V; i++) + parent.add(-1); + Queue q = new LinkedList<>(); + parent.set(source, source); + q.add(source); + while (!q.isEmpty() && parent.get(sink) == -1) { + int here = q.peek(); + q.poll(); + for (int there = 0; there < V; ++there) + if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) { + q.add(there); + parent.set(there, here); + } + } + if (parent.get(sink) == -1) + break; + + int amount = INF; + String printer = "path : "; + StringBuilder sb = new StringBuilder(); + for (int p = sink; p != source; p = parent.get(p)) { + amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount); + sb.append(p + "-"); + } + sb.append(source); + for (int p = sink; p != source; p = parent.get(p)) { + flow[parent.get(p)][p] += amount; + flow[p][parent.get(p)] -= amount; + } + totalFlow += amount; + printer += sb.reverse() + " / max flow : " + totalFlow; + System.out.println(printer); + } + + return totalFlow; + } +} diff --git a/DynamicProgramming/KadaneAlgorithm.java b/DynamicProgramming/KadaneAlgorithm.java new file mode 100644 index 0000000..3b8051f --- /dev/null +++ b/DynamicProgramming/KadaneAlgorithm.java @@ -0,0 +1,55 @@ +package DynamicProgramming; + +import java.util.Scanner; + +/** + * Program to implement Kadane’s Algorithm to + * calculate maximum contiguous subarray sum of an array + * Time Complexity: O(n) + * + * @author Nishita Aggarwal + */ + +public class KadaneAlgorithm { + + /** + * This method implements Kadane's Algorithm + * + * @param arr The input array + * @return The maximum contiguous subarray sum of the array + */ + static int largestContiguousSum(int arr[]) { + int i, len = arr.length, cursum = 0, maxsum = Integer.MIN_VALUE; + if (len == 0) //empty array + return 0; + for (i = 0; i < len; i++) { + cursum += arr[i]; + if (cursum > maxsum) { + maxsum = cursum; + } + if (cursum <= 0) { + cursum = 0; + } + } + return maxsum; + } + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n, arr[], i; + n = sc.nextInt(); + arr = new int[n]; + for (i = 0; i < n; i++) { + arr[i] = sc.nextInt(); + } + int maxContSum = largestContiguousSum(arr); + System.out.println(maxContSum); + sc.close(); + } + +} diff --git a/DynamicProgramming/Knapsack.java b/DynamicProgramming/Knapsack.java new file mode 100644 index 0000000..1dda48b --- /dev/null +++ b/DynamicProgramming/Knapsack.java @@ -0,0 +1,39 @@ +package DynamicProgramming; + +/** + * A DynamicProgramming based solution for 0-1 Knapsack problem + */ + +public class Knapsack { + + private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArgumentException { + if(wt == null || val == null) + throw new IllegalArgumentException(); + int i, w; + int rv[][] = new int[n + 1][W + 1]; //rv means return value + + // Build table rv[][] in bottom up manner + for (i = 0; i <= n; i++) { + for (w = 0; w <= W; w++) { + if (i == 0 || w == 0) + rv[i][w] = 0; + else if (wt[i - 1] <= w) + rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]); + else + rv[i][w] = rv[i - 1][w]; + } + } + + return rv[n][W]; + } + + + // Driver program to test above function + public static void main(String args[]) { + int val[] = new int[]{50, 100, 130}; + int wt[] = new int[]{10, 20, 40}; + int W = 50; + int n = val.length; + System.out.println(knapSack(W, wt, val, n)); + } +} diff --git a/DynamicProgramming/LongestCommonSubsequence.java b/DynamicProgramming/LongestCommonSubsequence.java new file mode 100644 index 0000000..1ab5700 --- /dev/null +++ b/DynamicProgramming/LongestCommonSubsequence.java @@ -0,0 +1,68 @@ +package DynamicProgramming; + +class LongestCommonSubsequence { + + public static String getLCS(String str1, String str2) { + + //At least one string is null + if (str1 == null || str2 == null) + return null; + + //At least one string is empty + if (str1.length() == 0 || str2.length() == 0) + return ""; + + String[] arr1 = str1.split(""); + String[] arr2 = str2.split(""); + + //lcsMatrix[i][j] = LCS of first i elements of arr1 and first j characters of arr2 + int[][] lcsMatrix = new int[arr1.length + 1][arr2.length + 1]; + + for (int i = 0; i < arr1.length + 1; i++) + lcsMatrix[i][0] = 0; + for (int j = 1; j < arr2.length + 1; j++) + lcsMatrix[0][j] = 0; + for (int i = 1; i < arr1.length + 1; i++) { + for (int j = 1; j < arr2.length + 1; j++) { + if (arr1[i - 1].equals(arr2[j - 1])) { + lcsMatrix[i][j] = lcsMatrix[i - 1][j - 1] + 1; + } else { + lcsMatrix[i][j] = lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1] ? lcsMatrix[i - 1][j] : lcsMatrix[i][j - 1]; + } + } + } + return lcsString(str1, str2, lcsMatrix); + } + + public static String lcsString(String str1, String str2, int[][] lcsMatrix) { + StringBuilder lcs = new StringBuilder(); + int i = str1.length(), + j = str2.length(); + while (i > 0 && j > 0) { + if (str1.charAt(i - 1) == str2.charAt(j - 1)) { + lcs.append(str1.charAt(i - 1)); + i--; + j--; + } else if (lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1]) { + i--; + } else { + j--; + } + } + return lcs.reverse().toString(); + } + + public static void main(String[] args) { + String str1 = "DSGSHSRGSRHTRD"; + String str2 = "DATRGAGTSHS"; + String lcs = getLCS(str1, str2); + + //Print LCS + if (lcs != null) { + System.out.println("String 1: " + str1); + System.out.println("String 2: " + str2); + System.out.println("LCS: " + lcs); + System.out.println("LCS length: " + lcs.length()); + } + } +} \ No newline at end of file diff --git a/DynamicProgramming/SubsetSum.java b/DynamicProgramming/SubsetSum.java new file mode 100644 index 0000000..cab94b1 --- /dev/null +++ b/DynamicProgramming/SubsetSum.java @@ -0,0 +1,46 @@ +package DynamicProgramming; + +public class SubsetSum { + + /** + * Driver Code + */ + public static void main(String[] args) { + int[] arr = new int[]{50, 4, 10, 15, 34}; + assert subsetSum(arr, 64); /* 4 + 10 + 15 + 34 = 64 */ + assert subsetSum(arr, 99); /* 50 + 15 + 34 = 99 */ + assert !subsetSum(arr, 5); + assert !subsetSum(arr, 66); + } + + /** + * Test if a set of integers contains a subset that sum to a given integer. + * + * @param arr the array contains integers. + * @param sum target sum of subset. + * @return {@code true} if subset exists, otherwise {@code false}. + */ + private static boolean subsetSum(int[] arr, int sum) { + int n = arr.length; + boolean[][] isSum = new boolean[n + 2][sum + 1]; + + isSum[n + 1][0] = true; + for (int i = 1; i <= sum; i++) { + isSum[n + 1][i] = false; + } + + for (int i = n; i > 0; i--) { + isSum[i][0] = true; + for (int j = 1; j <= arr[i - 1] - 1; j++) { + if (j <= sum) { + isSum[i][j] = isSum[i + 1][j]; + } + } + for (int j = arr[i - 1]; j <= sum; j++) { + isSum[i][j] = (isSum[i + 1][j] || isSum[i + 1][j - arr[i - 1]]); + } + } + + return isSum[1][sum]; + } +} \ No newline at end of file From 10812558539be68fa8190615cc094d5e4a77c397 Mon Sep 17 00:00:00 2001 From: Kushal Das <61356005+Kushal997-das@users.noreply.github.com> Date: Sat, 3 Oct 2020 16:23:46 +0530 Subject: [PATCH 02/10] added readme --- DynamicProgramming/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 DynamicProgramming/README.md diff --git a/DynamicProgramming/README.md b/DynamicProgramming/README.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/DynamicProgramming/README.md @@ -0,0 +1 @@ + From cffd2bdbf3bcd26a34f6b6e9d521483b890eb488 Mon Sep 17 00:00:00 2001 From: Kushal Das <61356005+Kushal997-das@users.noreply.github.com> Date: Sat, 3 Oct 2020 16:24:04 +0530 Subject: [PATCH 03/10] add comment --- DynamicProgramming/README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/DynamicProgramming/README.md b/DynamicProgramming/README.md index 8b13789..2857932 100644 --- a/DynamicProgramming/README.md +++ b/DynamicProgramming/README.md @@ -1 +1,18 @@ +# DynamicProgramming(using Java)
+ +|Problem's| Solution | +|:---------:|:----------:| +|BoardPath|[BoardPath.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/BoardPath.java)| +|CoinChange|[CoinChange.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/CoinChange.java)| +|EditDistance|[EditDistance.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/EditDistance.java)| +|EggDropping|[EggDropping.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/EggDropping.java)| +|Fibonacci|[Fibonacci.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/Fibonacci.java)| +|FordFulkerson|[FordFulkerson.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/FordFulkerson.java)| +|KadaneAlgorithm|[KadaneAlgorithm.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/KadaneAlgorithm.java)| +|Knapsack|[Knapsack.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/Knapsack.java)| +|SubsetSum|[SubsetSum.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/SubsetSum.java) +|CountNumBinaryStrings|[CountNumBinaryStrings.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/CountNumBinaryStrings)| +|LongestCommonSubsequence|[LongestCommonSubsequence.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/LongestCommonSubsequence.java)| +|LongestIncreasingSubsequence|[LongestIncreasingSubsequence.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/LongestIncreasingSubsequence.java)| +|LongestValidParentheses|[LongestValidParentheses.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/LongestValidParentheses.java)| From 829f26dd6b5c478d7a87fa240151edf9a4de1cb0 Mon Sep 17 00:00:00 2001 From: Kushal Das <61356005+Kushal997-das@users.noreply.github.com> Date: Sat, 3 Oct 2020 16:24:49 +0530 Subject: [PATCH 04/10] add1 --- DynamicProgramming/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DynamicProgramming/README.md b/DynamicProgramming/README.md index 2857932..0f65713 100644 --- a/DynamicProgramming/README.md +++ b/DynamicProgramming/README.md @@ -3,7 +3,7 @@ |Problem's| Solution | |:---------:|:----------:| -|BoardPath|[BoardPath.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/BoardPath.java)| +|BoardPath|[BoardPath.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/BoardPath.java)| |CoinChange|[CoinChange.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/CoinChange.java)| |EditDistance|[EditDistance.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/EditDistance.java)| |EggDropping|[EggDropping.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/EggDropping.java)| From cb98317675d92a1432ae3a3ed75a03e162557889 Mon Sep 17 00:00:00 2001 From: Kushal Das <61356005+Kushal997-das@users.noreply.github.com> Date: Sat, 3 Oct 2020 16:26:07 +0530 Subject: [PATCH 05/10] Rename CountNumBinaryStrings to CountNumBinaryStrings.java --- .../{CountNumBinaryStrings => CountNumBinaryStrings.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename DynamicProgramming/{CountNumBinaryStrings => CountNumBinaryStrings.java} (100%) diff --git a/DynamicProgramming/CountNumBinaryStrings b/DynamicProgramming/CountNumBinaryStrings.java similarity index 100% rename from DynamicProgramming/CountNumBinaryStrings rename to DynamicProgramming/CountNumBinaryStrings.java From 25e7490e935a6d838d45d4a2980d08d3f4341137 Mon Sep 17 00:00:00 2001 From: Kushal Das <61356005+Kushal997-das@users.noreply.github.com> Date: Sat, 3 Oct 2020 16:30:04 +0530 Subject: [PATCH 06/10] added links --- DynamicProgramming/README.md | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/DynamicProgramming/README.md b/DynamicProgramming/README.md index 0f65713..72ab87c 100644 --- a/DynamicProgramming/README.md +++ b/DynamicProgramming/README.md @@ -4,15 +4,13 @@ |Problem's| Solution | |:---------:|:----------:| |BoardPath|[BoardPath.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/BoardPath.java)| -|CoinChange|[CoinChange.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/CoinChange.java)| -|EditDistance|[EditDistance.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/EditDistance.java)| -|EggDropping|[EggDropping.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/EggDropping.java)| -|Fibonacci|[Fibonacci.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/Fibonacci.java)| -|FordFulkerson|[FordFulkerson.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/FordFulkerson.java)| -|KadaneAlgorithm|[KadaneAlgorithm.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/KadaneAlgorithm.java)| -|Knapsack|[Knapsack.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/Knapsack.java)| +|CoinChange|[CoinChange.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/CoinChange.java)| +|EditDistance|[EditDistance.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/EditDistance.java)| +|EggDropping|[EggDropping.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/EggDropping.java)| +|Fibonacci|[Fibonacci.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/Fibonacci.java)| +|FordFulkerson|[FordFulkerson.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/FordFulkerson.java)| +|KadaneAlgorithm|[KadaneAlgorithm.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/KadaneAlgorithm.java)| +|Knapsack|[Knapsack.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/Knapsack.java)| |SubsetSum|[SubsetSum.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/SubsetSum.java) -|CountNumBinaryStrings|[CountNumBinaryStrings.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/CountNumBinaryStrings)| -|LongestCommonSubsequence|[LongestCommonSubsequence.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/LongestCommonSubsequence.java)| -|LongestIncreasingSubsequence|[LongestIncreasingSubsequence.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/LongestIncreasingSubsequence.java)| -|LongestValidParentheses|[LongestValidParentheses.java](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/LongestValidParentheses.java)| +|CountNumBinaryStrings|[CountNumBinaryStrings.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/CountNumBinaryStrings.java)| +|LongestCommonSubsequence|[LongestCommonSubsequence.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/LongestCommonSubsequence.java)| From 833dd4d98e86a4b0206dffbb3f777813866e236f Mon Sep 17 00:00:00 2001 From: Kushal Das <61356005+Kushal997-das@users.noreply.github.com> Date: Sat, 3 Oct 2020 16:37:19 +0530 Subject: [PATCH 07/10] added readme --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 48735ab..cbc7bca 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,10 @@ Code library for competitive programming purposes. - Aho Corasick - Z Algorithm - Manacher + +- [DynamicProgramming](DynamicProgramming) + + - Other Algorithms ### Related Material From 4e3daded69809e7f84e54ace23440a2bac0fcfa6 Mon Sep 17 00:00:00 2001 From: Kushal Das <61356005+Kushal997-das@users.noreply.github.com> Date: Sat, 3 Oct 2020 16:39:00 +0530 Subject: [PATCH 08/10] update 1 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cbc7bca..6b5fb52 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Code library for competitive programming purposes. - Manacher - [DynamicProgramming](DynamicProgramming) - + - [BoardPath.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/BoardPath.java) - Other Algorithms From 70060a2e90dcfea0d09f24bbe4fa01f5c51a629d Mon Sep 17 00:00:00 2001 From: Kushal Das <61356005+Kushal997-das@users.noreply.github.com> Date: Sat, 3 Oct 2020 16:47:49 +0530 Subject: [PATCH 09/10] updated readme --- README.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6b5fb52..9adf6ad 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,19 @@ Code library for competitive programming purposes. - Manacher - [DynamicProgramming](DynamicProgramming) - - [BoardPath.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/BoardPath.java) + - [readme](DynamicProgramming/README.md) + - [BoardPath.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/BoardPath.java) + - [coinChange.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/CoinChange.java) + - [CountNumBinaryStrings.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/CountNumBinaryStrings.java) + - [EditDistance.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/EditDistance.java) + - [EggDropping.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/EggDropping.java) + - [Fibonacci.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/Fibonacci.java) + - [FordFulkerson.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/FordFulkerson.java) + - [KadaneAlgorithm.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/KadaneAlgorithm.java) + - [Knapsack.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/Knapsack.java) + - [LongestCommonSubsequence.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/LongestCommonSubsequence.java) + - [SubsetSum.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/SubsetSum.java) + - Other Algorithms From cf22434a421cbac4bf7fd0db3025d4debc02ed96 Mon Sep 17 00:00:00 2001 From: Ayushi Doshi <55248015+legendarygirl56@users.noreply.github.com> Date: Sat, 3 Oct 2020 18:17:22 +0530 Subject: [PATCH 10/10] imp algos --- 2stack.cpp | 85 +++++++++++++++++++ AVLTree.cpp | 133 +++++++++++++++++++++++++++++ add del link list.cpp | 108 +++++++++++++++++++++++ adjacency matrix.cpp | 37 ++++++++ adjlist.cpp | 41 +++++++++ alter 1.cpp | 49 +++++++++++ bfs.cpp | 76 +++++++++++++++++ check tree is BST or not.cpp | 52 ++++++++++++ circular linked list.cpp | 160 +++++++++++++++++++++++++++++++++++ contigous sum kadane's.cpp | 34 ++++++++ contigous sum naive.cpp | 34 ++++++++ 11 files changed, 809 insertions(+) create mode 100644 2stack.cpp create mode 100644 AVLTree.cpp create mode 100644 add del link list.cpp create mode 100644 adjacency matrix.cpp create mode 100644 adjlist.cpp create mode 100644 alter 1.cpp create mode 100644 bfs.cpp create mode 100644 check tree is BST or not.cpp create mode 100644 circular linked list.cpp create mode 100644 contigous sum kadane's.cpp create mode 100644 contigous sum naive.cpp diff --git a/2stack.cpp b/2stack.cpp new file mode 100644 index 0000000..7df99e0 --- /dev/null +++ b/2stack.cpp @@ -0,0 +1,85 @@ +#include +using namespace std; +#define ll long long + +class t2stack +{ +ll *a; +ll size,top1,top2; +public: + t2stack(ll n) + { + size=n; + a=new ll[n]; + top1=-1; + top2=size; + } + + void push1(ll n) + { + if(top1+1=0) + { + cout< +using namespace std; + +struct Node{ + int data; + Node *left; + Node *right; + int height; +}*Root = NULL; + +Node* new_Node(int DATA) +{ + Node* node = new Node(); + node->data = DATA; + node->left = NULL; + node->right = NULL; + node->height = 1; + return(node); +} + +int height(Node *a) +{ + if(a==NULL) + return 0; + return a->height; +} +int balance(Node *a) +{ + if(a==NULL) + return 0; + int lh = height(a->left); + int rh = height(a->right); + return (lh-rh); +} +Node *RR(Node *y) +{ + Node *x = y->left; + Node *T2 = x->right; + x->right = y; + y->left = T2; + y->height = max(height(y->left), + height(y->right)) + 1; + x->height = max(height(x->left), + height(x->right)) + 1; + return x; +} + +Node *LL(Node *x) +{ + Node *y = x->right; + Node *T2 = y->left; + y->left = x; + x->right = T2; + x->height = max(height(x->left), + height(x->right)) + 1; + y->height = max(height(y->left), + height(y->right)) + 1; + return y; +} +Node* insertToAVL(Node* root, int data) +{ + if(root==NULL) + { + Node* Nodes = new_Node(data); + return(Nodes); + } + if(root->data>data) + { + root->left = insertToAVL(root->left,data); + } + else if(root->dataright = insertToAVL(root->right,data); + } + else + return root; + + root->height = max(height(root->left),height(root->right)) + 1; + + int factor = balance(root); + + if(factor > 1 && root->left->data > data) + { + return RR(root); + } + if(factor < -1 && root->right->data < data) + { + return LL(root); + } + if (factor > 1 && data > root->left->data) + { + root->left = LL(root->left); + return RR(root); + } + if (factor < -1 && data < root->right->data) + { + root->right = RR(root->right); + return LL(root); + } + return root; +} +void inorder(Node* root) +{ + if(root != NULL) + { + inorder(root->left); + cout << root->data << " "; + inorder(root->right); + } +} +int main() +{ + int size; + cout << "\nEnter num of node :- "; + cin >> size; + vector vec; + cout << "\nEnter values :- "; + for(int i = 0; i < size; i++) + { + int x; + cin >> x; + vec.push_back(x); + } + Root = insertToAVL(Root, vec[0]); + for(int i = 1; i < size; i++) { + Root = insertToAVL(Root, vec[i]); + } + cout << "\nInOrder Traversal is:- \n"; + inorder(Root); + cout<< "\nRoot Node is:- \n"; + cout<data<<"\n"; + return 0; +} diff --git a/add del link list.cpp b/add del link list.cpp new file mode 100644 index 0000000..53790c9 --- /dev/null +++ b/add del link list.cpp @@ -0,0 +1,108 @@ +#include +using namespace std; +#define ll long long + +class node +{ + public: + int data; + node *next; +}; + +void add_node(node ** head,int n) //inserts at the front +{ + node *temp=new node; + temp->data=n; + temp->next=*head; + *head=temp; +} +void add(node ** head,int n) +{ + node *temp=new node(); + node *l=*head; + temp->data=n; + temp->next=NULL; + if(*head==NULL) + { + *head=temp; + } + else + { + while(l->next!=NULL) + { + l=l->next; + } + l->next=temp; + } +} +void display(node ** k) +{ + while((*k)!=NULL) + { + cout<<(*k)->data<<" "; + (*k)=(*k)->next; + } +} +void delfront(node **head) +{ + if(*head==NULL) + cout<<"Nothing to delete \n"; + else + (*head) = (*head)->next; +} +void delend(node **head) +{ + if(*head==NULL) + cout<<"Nothing to delete\n"; + else + { + if((*head)->next==NULL) + delete(*head); + node *second = *head; + while(second->next->next!=NULL) + { + second = second->next; + } + delete(second->next); + second->next = NULL; + } +} +int main() +{ + node *head=NULL; + int i,n; + cin>>n; + for(i=0;i>y; + if(y==1 || y==2) + { + cout<<"Enter the number to be inserted"<>x; + if(y==1) + { + add_node(&head,x); //insertion from front + } + + else if(y==2) //insertion from end + { + add(&head, x); + } + } + else + { + if(y==3) //deletion from front + { + delfront(&head); + } + else if(y==4) //deletion from end + { + delend(&head); + } + } + } + cout<<"The final linked list is"< +using namespace std; +#define ll long long +int adj[5][5]; +void add(int u,int v) +{ + adj[u][v]=1; + adj[v][u]=1; +} +void display(int n) +{ + for(int i=0;i +using namespace std; +#define ll long long +void add(vector l[],int u,int v) +{ + l[u].push_back(v); + l[v].push_back(u); +} +void printgraph(vector l[],int n) +{ + for(int i=0;i"< l[V]; + add(l,0,1); + add(l,0,4); + add(l,1,2); + add(l,1,3); + add(l,1,4); + add(l,2,3); + add(l,3,4); + printgraph(l, V); + + + return 0; +} \ No newline at end of file diff --git a/alter 1.cpp b/alter 1.cpp new file mode 100644 index 0000000..3873731 --- /dev/null +++ b/alter 1.cpp @@ -0,0 +1,49 @@ +#include +using namespace std; +#define ll long long +int main(){ + #ifndef ONLINE_JUDGE + freopen("input.txt","r",stdin); + freopen("output.txt","w",stdout); + #endif + ll n; + cin>>n; + ll a[n]; + for(ll i=0;i>a[i]; + } + for(ll i=0;i=0) + { + a[i]=1; + } + else + { + a[i]=-1; + } + } + bool flag=0; + ll sum=0; + for(ll i=0;i +using namespace std; +#define ll long long +class graph +{ + int V; + list *adj; +public: + graph(int V); + void add(int u,int v); + void BFS(int v); +}; + +graph::graph(int V) +{ + this->V=V; + adj=new list[V]; +} + +void graph::add(int u,int v) +{ + adj[u].push_back(v); +} +void graph::BFS(int s) +{ + bool *visited=new bool[V]; + for(int i=0;i queue; + + visited[s]=true; + queue.push_back(s); + + + list::iterator i; + + + while(!queue.empty()) + { + s=queue.front(); + cout< + +#define ll long long int +#define llu unsigned long long int +#define f(n) for(ll i=0;i=0;i--) +#define endl "\n" +#define mod 1000000007 + +using namespace std; + +class node +{ +public: + ll data; + node* left; + node* right; + + node(ll data) + { + this->data = data; + this->left = NULL; + this->right = NULL; + } +}; + +ll isThisBST(node* node, ll min, ll max) +{ + if (node==NULL) + return 1; + + if (node->data < min || node->data > max) + return 0; + + return isThisBST(node->left, min, node->data-1) && isThisBST(node->right, node->data+1, max); +} + +int main() +{ + node *root = new node(4); + root->left = new node(2); + root->right = new node(5); + root->left->left = new node(1); + root->left->right = new node(3); + + if(isThisBST(root,INT_MIN,INT_MAX)) + cout<<"Is BST"; + else + cout<<"Not a BST"; + + return 0; +} diff --git a/circular linked list.cpp b/circular linked list.cpp new file mode 100644 index 0000000..0b7724f --- /dev/null +++ b/circular linked list.cpp @@ -0,0 +1,160 @@ +#include +using namespace std; +struct Node { + int data; + Node* next; +}; +Node* last; + +//Node* create(Node* last , int d); +void insertBeg( int d) +{ + if(last==NULL) + { + Node* temp = new Node(); + temp->data = d; + last = temp; + temp->next = last; + + } + else + { + Node* temp = new Node(); + temp->data = d; + temp->next = last->next; + last->next = temp; + + } +} +Node* append(Node* last , int d) +{ + if(last ==NULL) + { + Node*temp = new Node(); + temp->data = d; + last = temp; + temp->next = last; + return last; + } + else + { + Node* temp = new Node(); + temp->data = d; + temp->next = last->next; + last->next = temp; + last = temp; + return last; + } + +} +//Node* between(Node* last , int d , int item); +void del(int d) +{ + if(last == NULL) + { + cout<<"List is empty "<next; + Node* temp; + if(last-> next == last && last->data == d) + { + //only node + temp = last; + last = NULL; + delete(temp); + return; + } + if(last->next->data == d) + { + //first node + temp = last->next; + last->next = temp->next; + delete(temp); + return; + } + while(p->next != last) + { + //nth node + if(p->next->data == d) + { + temp = p->next; + p->next = temp->next; + delete(temp); + + } + p = p->next; + } + if(last->data == d) + { + //last node + temp = last; + } + +} +void display() +{ + Node* temp = last; + if(temp == NULL) + { + cout<<"List is empty "<next; + do + { + cout<data<<" "; + p = p->next; + } + while(p != temp->next); + cout<>z; + switch(z) + { + case 1: + cout<<"Enter the no of elements to be entered "<>n; + cout<<"Enter the element of list "<>d; + insertBeg(d); + } + display(); + break; + + case 2: + cout<<"Enter the no of elements to be entered "<>n; + cout<<"Enter the element of list "<>d; + last = append(last,d); + } + display(); + break; + + case 3: + return 0; + + default: + cout<<"Wrong choice"; + } + } + return 0; +} diff --git a/contigous sum kadane's.cpp b/contigous sum kadane's.cpp new file mode 100644 index 0000000..9afbe05 --- /dev/null +++ b/contigous sum kadane's.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; +#define ll long long +int main(){ + #ifndef ONLINE_JUDGE + freopen("input.txt","r",stdin); + freopen("output.txt","w",stdout); + #endif + + //using KADANE'S ALGO + //Initialise two variable. + ll overall_max=INT_MIN; + ll current_max=0; + ll n; cin>>n; + ll a[n]; + for(ll i=0;i>a[i]; + } + for(ll i=0;ioverall_max) + { + overall_max=current_max; + } + if(current_max<0) + { + current_max=0; + } + } + cout< +using namespace std; +#define ll long long +int main(){ + #ifndef ONLINE_JUDGE + freopen("input.txt","r",stdin); + freopen("output.txt","w",stdout); + #endif + + ll n; + cin>>n; + ll a[n]; + + for(ll i=0;i>a[i]; + } + ll max=INT_MIN; + for(ll i=0;i