├── other_algorithms ├── Shuffle.java ├── Precomputation.java ├── ConvexHullOptimization2.java ├── ConvexHullOptimization1.java ├── Scanner.java └── LIS.java ├── data_structures ├── snippets │ ├── FenwickTree.md │ └── SegmentTree.md ├── SQRT_Decomposition.java ├── linear │ └── Bitmask.java ├── sortings │ └── MergeSort.java ├── UnionFind.java ├── SparseTable.java ├── trees │ ├── FenwickTree.java │ ├── PersistentSegmentTree.java │ ├── SegmentTree.java │ └── SegmentTree2D.java ├── MoAlgorithm.java ├── SkipList.java └── TreapSet.java ├── strings ├── Z_Algorithm.java ├── SuffixTrie.java ├── Manacher.java ├── PrefixAutomaton.java ├── SuffixAutomaton.java ├── SuffixArray.java └── AhoCorasick.java ├── math ├── combinatorics │ ├── Fibonacci.java │ ├── BinomialCoefficient.java │ └── InclusionExclusionPrinciple.java ├── number_theory │ ├── ExtendedEuclid.java │ ├── ModifiedSieve.java │ ├── PrimeFactorization.java │ └── PrimeNumbers.java ├── Polynomial.java ├── game_theory │ ├── GamesOnGeneralGraphs.java │ └── PoliceAndThief.java ├── NewtonMethod.java ├── Exponentiation.java └── Permutations.java ├── geometry ├── LineSegment.java ├── Vector.java ├── Rectangle.java ├── Geometry.java ├── Line.java ├── LineSweep.java ├── Circle.java ├── Triangle.java ├── Point.java └── Polygon.java ├── contigous sum naive.cpp ├── adjacency matrix.cpp ├── contigous sum kadane's.cpp ├── adjlist.cpp ├── alter 1.cpp ├── curriculum ├── outlines │ ├── graphs │ │ ├── mst.md │ │ ├── sssp.md │ │ ├── basic_algos.md │ │ └── graph_traversal.md │ ├── data_structures │ │ ├── linear_ds_supps.md │ │ ├── dsu.md │ │ ├── sortings.md │ │ └── nonlinear_ds.md │ ├── solving_techniques │ │ ├── sliding_window.md │ │ ├── binary_search.md │ │ └── greedy.md │ ├── getting_started │ │ ├── cp_environment.md │ │ ├── adhoc.md │ │ └── io_tutorial.md │ ├── outline_format.md │ └── general │ │ ├── pupils_gpsets.md │ │ └── specialists_gpsets.md ├── readme.md └── expert-plan.md ├── graphs ├── trees │ ├── EulerWalk.java │ ├── TreeTraversal.java │ ├── LCA.java │ └── TreeDiameter.java ├── mst │ ├── MST_Prim.java │ └── MST_Kruskal.java ├── shortest_path │ ├── APSP.java │ └── SSSP.java ├── traversal │ ├── StronglyConnectedComponents1.java │ ├── KosarajuAlgorithm.java │ ├── ArticulationPointsAndBridges.java │ ├── BridgeTree.java │ ├── BiconnectedComponents.java │ ├── articulation-points-and-bridges.md │ ├── BridgesOnline.java │ └── GraphTraversal.java ├── max_flow │ ├── MaxFlow1.java │ ├── MaxFlow2.java │ └── MaxFlow3.java └── special │ ├── EulerTour.java │ └── MCBM.java ├── check tree is BST or not.cpp ├── DynamicProgramming ├── Knapsack.java ├── SubsetSum.java ├── EggDropping.java ├── KadaneAlgorithm.java ├── README.md ├── BoardPath.java ├── CountNumBinaryStrings.java ├── LongestCommonSubsequence.java ├── FordFulkerson.java ├── CoinChange.java ├── Fibonacci.java └── EditDistance.java ├── 2stack.cpp ├── bfs.cpp ├── add del link list.cpp ├── AVLTree.cpp └── circular linked list.cpp /other_algorithms/Shuffle.java: -------------------------------------------------------------------------------- 1 | package other_algorithms; 2 | 3 | public class Shuffle { 4 | 5 | static void shuffle(int[] a) 6 | { 7 | int n = a.length; 8 | for(int i = 0; i < n; i++) 9 | { 10 | int r = i + (int)(Math.random() * (n - i)); 11 | int tmp = a[i]; 12 | a[i] = a[r]; 13 | a[r] = tmp; 14 | } 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /data_structures/snippets/FenwickTree.md: -------------------------------------------------------------------------------- 1 | Update 2D Binary-Indexed Tree 2 | ```java 3 | int ft[][], maxX, maxY; 4 | 5 | void update(int x, int y, int val) 6 | { 7 | int y1; 8 | while(x <= maxX) 9 | { 10 | y1 = y; 11 | while(y1 <= maxY) 12 | { 13 | ft[x][y1] += val; 14 | y1 += y1 & -y1; 15 | } 16 | x += x & -x; 17 | } 18 | } 19 | ``` 20 | -------------------------------------------------------------------------------- /strings/Z_Algorithm.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class Z_Algorithm { 4 | 5 | static int[] zAlgo(char[] s) 6 | { 7 | int n = s.length; 8 | int[] z = new int[n]; 9 | for(int i = 1, l = 0, r = 0; i < n; ++i) 10 | { 11 | if(i <= r) 12 | z[i] = Math.min(r - i + 1, z[i - l]); 13 | while(i + z[i] < n && s[z[i]] == s[i + z[i]]) 14 | ++z[i]; 15 | if(i + z[i] - 1 > r) 16 | r = i + z[l = i] - 1; 17 | } 18 | return z; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /math/combinatorics/Fibonacci.java: -------------------------------------------------------------------------------- 1 | package math.combinatorics; 2 | 3 | public class Fibonacci { 4 | 5 | static int fib[]; 6 | 7 | static int fibonacci(int n) //O(log n) 8 | { 9 | if (n == 0) 10 | return 0; 11 | if (n <= 2) 12 | return 1; 13 | if (fib[n] != -1) 14 | return fib[n]; 15 | 16 | int k = n >> 1; 17 | int a = fibonacci(k), b = fibonacci(k+1); 18 | 19 | if (n%2 == 0) 20 | return fib[n] = a * (2 * b - a); 21 | return fib[n] = b * b + a * a; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /geometry/LineSegment.java: -------------------------------------------------------------------------------- 1 | package geometry; 2 | 3 | public class LineSegment { 4 | 5 | Point p, q; 6 | 7 | LineSegment(Point a, Point b) { p = a; q = b; } 8 | 9 | 10 | boolean intersect(LineSegment ls) 11 | { 12 | Line l1 = new Line(p, q), l2 = new Line(ls.p, ls.q); 13 | if(l1.parallel(l2)) 14 | { 15 | if(l1.same(l2)) 16 | return p.between(ls.p, ls.q) || q.between(ls.p, ls.q) || ls.p.between(p, q) || ls.q.between(p, q); 17 | return false; 18 | } 19 | Point c = l1.intersect(l2); 20 | return c.between(p, q) && c.between(ls.p, ls.q); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /contigous sum naive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long 4 | int main(){ 5 | #ifndef ONLINE_JUDGE 6 | freopen("input.txt","r",stdin); 7 | freopen("output.txt","w",stdout); 8 | #endif 9 | 10 | ll n; 11 | cin>>n; 12 | ll a[n]; 13 | 14 | for(ll i=0;i>a[i]; 17 | } 18 | ll max=INT_MIN; 19 | for(ll i=0;i 2 | using namespace std; 3 | #define ll long long 4 | int main(){ 5 | #ifndef ONLINE_JUDGE 6 | freopen("input.txt","r",stdin); 7 | freopen("output.txt","w",stdout); 8 | #endif 9 | 10 | //using KADANE'S ALGO 11 | //Initialise two variable. 12 | ll overall_max=INT_MIN; 13 | ll current_max=0; 14 | ll n; cin>>n; 15 | ll a[n]; 16 | for(ll i=0;i>a[i]; 19 | } 20 | for(ll i=0;ioverall_max) 24 | { 25 | overall_max=current_max; 26 | } 27 | if(current_max<0) 28 | { 29 | current_max=0; 30 | } 31 | } 32 | cout< 2 | using namespace std; 3 | #define ll long long 4 | void add(vector l[],int u,int v) 5 | { 6 | l[u].push_back(v); 7 | l[v].push_back(u); 8 | } 9 | void printgraph(vector l[],int n) 10 | { 11 | for(int i=0;i"< l[V]; 30 | add(l,0,1); 31 | add(l,0,4); 32 | add(l,1,2); 33 | add(l,1,3); 34 | add(l,1,4); 35 | add(l,2,3); 36 | add(l,3,4); 37 | printgraph(l, V); 38 | 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /alter 1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long 4 | int main(){ 5 | #ifndef ONLINE_JUDGE 6 | freopen("input.txt","r",stdin); 7 | freopen("output.txt","w",stdout); 8 | #endif 9 | ll n; 10 | cin>>n; 11 | ll a[n]; 12 | for(ll i=0;i>a[i]; 15 | } 16 | for(ll i=0;i=0) 19 | { 20 | a[i]=1; 21 | } 22 | else 23 | { 24 | a[i]=-1; 25 | } 26 | } 27 | bool flag=0; 28 | ll sum=0; 29 | for(ll i=0;i= ll.x && p.y <= ur.y + EPS && p.y + EPS >= ll.y; 16 | } 17 | 18 | Rectangle intersect(Rectangle r) 19 | { 20 | Point ll = new Point(Math.max(this.ll.x, r.ll.x), Math.max(this.ll.y, r.ll.y)); 21 | Point ur = new Point(Math.min(this.ur.x, r.ur.x), Math.min(this.ur.y, r.ur.y)); 22 | if(Math.abs(ur.x - ll.x) > EPS && Math.abs(ur.y - ll.y) > EPS && this.contains(ll) && this.contains(ur) && r.contains(ll) && r.contains(ur)) 23 | return new Rectangle(ll, ur); 24 | return null; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /curriculum/outlines/graphs/mst.md: -------------------------------------------------------------------------------- 1 | # Minimum Spanning Tree 2 | --- 3 | ## Outline 4 | 1. Problem Definition 5 | 2. Kruskal's Algorithm 6 | 3. Prim's Algorithm 7 | 4. Variants 8 | - Max Spanning Tree 9 | - Min Spanning Subgraph 10 | - Min Spanning Forest 11 | - Second Best Spanning Tree 12 | - Minimax and Maximin 13 | 14 | --- 15 | 16 | ## Material Resources 17 | | Resource | Points Covered | 18 | |:------------------------- |:--------------------------------| 19 | | CP Section 4.4.3 | All outline points | 20 | 21 | --- 22 | ## Problem Sets 23 | ### Problem Set #1 24 | 25 | | Problem | Tags | Notes | Solution | 26 | |:------------- |:-------------|:-----|:--------| 27 | | | | | |UVa [11631, 11733, 1235, 10099, 1234] 28 | | | | | | 29 | | | | | | 30 | | | | | | 31 | | | | | | 32 | | | | | | 33 | | | | | | 34 | | | | | | 35 | | | | | | 36 | | | | | | 37 | -------------------------------------------------------------------------------- /data_structures/SQRT_Decomposition.java: -------------------------------------------------------------------------------- 1 | package data_structures; 2 | 3 | public class SQRT_Decomposition { 4 | 5 | // Query Type: find sum of subarray [L, R] 6 | 7 | static int[] preprocess(int[] a, int n) 8 | { 9 | int s = (int) Math.sqrt(n) + 1; 10 | int[] b = new int[(n + s - 1)/ s]; 11 | for(int i = 0; i < n; ++i) 12 | b[i / s] += a[i]; 13 | return b; 14 | } 15 | 16 | static int query(int[] a, int[] b, int s, int l, int r) 17 | { 18 | int sum = 0, block_l = l / s, block_r = r / s; 19 | 20 | if(block_l == block_r) 21 | for(int i = l; i <= r; ++i) 22 | sum += a[i]; 23 | else 24 | { 25 | for(int i = l, end = (block_l+1) * s - 1; i <= end; ++i) 26 | sum += a[i]; 27 | for(int i = block_l + 1; i <= block_r - 1; ++i) 28 | sum += b[i]; 29 | for(int i = block_r * s; i <= r; ++i) 30 | sum += a[i]; 31 | } 32 | 33 | return sum; 34 | } 35 | 36 | 37 | } 38 | 39 | -------------------------------------------------------------------------------- /graphs/trees/EulerWalk.java: -------------------------------------------------------------------------------- 1 | package graphs.trees; 2 | 3 | import java.util.*; 4 | 5 | class EulerWalk { // Euler walk on a rooted tree 6 | 7 | static ArrayList[] children; 8 | static int[] E, L, tin, tout; 9 | static int N, t; 10 | 11 | static void dfs(int u, int depth) 12 | { 13 | tin[u] = t; 14 | E[t] = u; 15 | L[t++] = depth; 16 | for(int v: children[u]) 17 | { 18 | dfs(v, depth + 1); 19 | E[t] = u; 20 | L[t++] = depth; 21 | } 22 | tout[u] = t - 1; 23 | } 24 | 25 | static void eulerWalk(int root) 26 | { 27 | t = 0; 28 | E = new int[N<<1]; // E[i] = node visited at t = i 29 | L = new int[N<<1]; // L[i] = level of E[i] 30 | tin = new int[N]; // tin[u] = earliest time node i is visited 31 | tout = new int[N]; // tout[u] = last time node i is visited 32 | Arrays.fill(tin, -1); 33 | Arrays.fill(tout, -1); 34 | dfs(root, 0); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /data_structures/linear/Bitmask.java: -------------------------------------------------------------------------------- 1 | package data_structures.linear; 2 | 3 | public class Bitmask { 4 | 5 | static int setBit(int S, int j) { return S | 1 << j; } 6 | 7 | static int clearBit(int S, int j) { return S & ~(1 << j); } 8 | 9 | static int toggleBit(int S, int j) { return S ^ 1 << j; } 10 | 11 | static boolean isOn(int S, int j) { return (S & 1 << j) != 0; } 12 | 13 | static int turnOnLastZero(int S) { return S | S + 1; } 14 | 15 | static int turnOnLastConsecutiveZeroes(int S) { return S | S - 1; } 16 | 17 | static int turnOffLastBit(int S) { return S & S - 1; } 18 | 19 | static int turnOffLastConsecutiveBits(int S) { return S & S + 1; } 20 | 21 | static int lowBit(int S) { return S & -S; } 22 | 23 | static int setAll(int N) { return (1 << N) - 1; } 24 | 25 | static int modulo(int S, int N) { return (S & N - 1); } //S%N, N is a power of 2 26 | 27 | static boolean isPowerOfTwo(int S) { return (S & S - 1) == 0; } 28 | } 29 | -------------------------------------------------------------------------------- /math/number_theory/ExtendedEuclid.java: -------------------------------------------------------------------------------- 1 | package math.number_theory; 2 | 3 | public class ExtendedEuclid { 4 | 5 | /* 6 | * Extended Euclid Algorithm for Solving Linear Diophantine Equation 7 | * Solve: ax + by = c. Let d = gcd(a, b). 8 | * If d | c, then it has infinite number of solutions. Otherwise, it has no solution. 9 | * 10 | * The solution derived is one of the minimal pairs of the equation solutions 11 | * i.e. |X| + |Y| is minimized 12 | * 13 | * The following algorithm derives one solution (x0, y0). Other solutions can be drived by: 14 | * x = x0 + n * (b / d), y = y0 - n * (a / d) 15 | * 16 | * For first non-negative x and y, -x0 * d / b <= n <= y0 * d / a 17 | */ 18 | 19 | static int x, y, d; 20 | 21 | void extendedEuclid(int a, int b) 22 | { 23 | if(b == 0) { x = 1; y = 0; d = a; return; } 24 | extendedEuclid(b, a % b); 25 | int x1 = y; 26 | int y1 = x - a / b * y; 27 | x = x1; y = y1; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /graphs/mst/MST_Prim.java: -------------------------------------------------------------------------------- 1 | package graphs.mst; 2 | 3 | import java.util.ArrayList; 4 | import java.util.PriorityQueue; 5 | 6 | public class MST_Prim { 7 | 8 | static ArrayList[] adjList; 9 | static int V; 10 | 11 | static int prim() //O(E log E) 12 | { 13 | int mst = 0; 14 | boolean[] visited = new boolean[V]; 15 | PriorityQueue pq = new PriorityQueue(); 16 | pq.add(new Edge(0, 0)); 17 | while(!pq.isEmpty()) 18 | { 19 | Edge cur = pq.remove(); 20 | if(visited[cur.node]) 21 | continue; 22 | visited[cur.node] = true; 23 | mst += cur.cost; 24 | for(Edge nxt: adjList[cur.node]) 25 | if(!visited[nxt.node]) 26 | pq.add(nxt); 27 | } 28 | return mst; 29 | } 30 | 31 | static class Edge implements Comparable 32 | { 33 | int node, cost; 34 | 35 | Edge(int a, int b) { node = a; cost = b; } 36 | 37 | public int compareTo(Edge e) { return cost - e.cost; } 38 | 39 | } 40 | 41 | } 42 | 43 | -------------------------------------------------------------------------------- /strings/Manacher.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class Manacher { 4 | 5 | static int[][] manacher(char[] s) 6 | { 7 | int n = s.length, d1[] = new int[n], d2[] = new int[n]; 8 | 9 | //Calculation of odd-length palindromes 10 | for(int i = 0, l = 0, r = -1; i < n; ++i) 11 | { 12 | int k = i > r ? 1 : Math.min(r - i + 1, d1[l + r - i]); 13 | while(i + k < n && i - k >= 0 && s[i + k] == s[i - k]) 14 | ++k; 15 | d1[i] = k--; 16 | if(i + k > r) { l = i - k; r = i + k; } 17 | } 18 | 19 | //Calculation of even-length palindromes 20 | //you may insert # between characters of s to get rid of the following part 21 | for(int i = 0, l = 0, r = -1; i < n; ++i) 22 | { 23 | int k = i > r ? 0 : Math.min(r - i + 1, d2[l + r - i + 1]); 24 | while(i + k < n && i - k - 1 >= 0 && s[i + k] == s[i - k - 1]) 25 | ++k; 26 | d2[i] = k--; 27 | if(i + k > r) { l = i - k - 1; r = i + k; } 28 | } 29 | 30 | return new int[][] { d1, d2 }; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /data_structures/snippets/SegmentTree.md: -------------------------------------------------------------------------------- 1 | Build and Combine for Segment trees with nodes carrying more than one variable. The example below is on a segment tree that can find maximum and its frequency in a given interval [L, R] 2 | 3 | ```java 4 | static class Node 5 | { 6 | int max, freq; 7 | 8 | Node(int a, int b) 9 | { 10 | max = a; 11 | freq = b; 12 | } 13 | } 14 | 15 | 16 | Node[] sTree; 17 | int[] array; 18 | 19 | void build(int node, int b, int e) 20 | { 21 | if(b == e) 22 | { 23 | sTree[node] = new Node(array[b], 1); 24 | return; 25 | } 26 | int mid = b + e >> 1; 27 | build(node<<1, b, mid); 28 | build((node<<1) + 1, mid + 1, e); 29 | sTree[node] = combine(sTree[node<<1], sTree[(node<<1) + 1]); 30 | } 31 | 32 | 33 | Node combine(Node a, Node b) 34 | { 35 | if(a.max > b.max) 36 | return new Node(a.max, a.freq); 37 | else if(a.max < b.max) 38 | return new Node(b.max, b.freq); 39 | return new Node(a.max, a.freq + b.freq); 40 | } 41 | ``` 42 | -------------------------------------------------------------------------------- /graphs/shortest_path/APSP.java: -------------------------------------------------------------------------------- 1 | package graphs.shortest_path; 2 | 3 | /* 4 | * All-Pairs Shortest Path 5 | */ 6 | public class APSP { 7 | 8 | static int[][] adjMatrix; 9 | static int[][] p; 10 | static int V; 11 | 12 | static void floyd() 13 | { 14 | //adjMatrix contains: directed edges, zero for i=j, INF (1B) otherwise 15 | 16 | p = new int[V][V]; //to find the parent on the shortest path 17 | for(int i = 0; i < V; i++) 18 | for(int j = 0; j < V; j++) 19 | p[i][j] = i; 20 | 21 | for(int k = 0; k < V; k++) 22 | for(int i = 0; i < V; i++) 23 | for(int j = 0; j < V; j++) 24 | if(adjMatrix[i][j] > adjMatrix[i][k] + adjMatrix[k][j]) 25 | { 26 | adjMatrix[i][j] = adjMatrix[i][k] + adjMatrix[k][j]; 27 | p[i][j] = p[k][j]; 28 | } 29 | } 30 | 31 | static void printPath(int i, int j) 32 | { 33 | if(i != j) // use (P[i][j] != i) in case adjMat[i][i] != 0 34 | printPath(i,p[i][j]); // i.e. paths of the form 1, 2, 3, 1 are allowed 35 | System.out.print(j+" "); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /data_structures/sortings/MergeSort.java: -------------------------------------------------------------------------------- 1 | package data_structures.sortings; 2 | 3 | public class MergeSort 4 | { 5 | /* 6 | * - Complexity O(n log n) 7 | * - Stable sort algorithm 8 | * - Can be used to compute inversion index 9 | */ 10 | static final int INF = Integer.MAX_VALUE; 11 | 12 | static void mergeSort(int[] a, int b, int e) 13 | { 14 | if(b < e) 15 | { 16 | int q = (b + e) / 2; 17 | mergeSort(a, b, q); 18 | mergeSort(a, q + 1, e); 19 | merge(a, b, q, e); 20 | } 21 | } 22 | 23 | 24 | static void merge(int[] a, int b, int mid, int e) 25 | { 26 | int n1 = mid - b + 1; 27 | int n2 = e - mid; 28 | int[] L = new int[n1+1], R = new int[n2+1]; 29 | 30 | for(int i = 0; i < n1; i++) L[i] = a[b + i]; 31 | for(int i = 0; i < n2; i++) R[i] = a[mid + 1 + i]; 32 | L[n1] = R[n2] = INF; 33 | 34 | for(int k = b, i = 0, j = 0; k <= e; k++) 35 | if(L[i] <= R[j]) 36 | a[k] = L[i++]; 37 | else 38 | a[k] = R[j++]; 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /geometry/Geometry.java: -------------------------------------------------------------------------------- 1 | package geometry; 2 | 3 | public class Geometry { 4 | 5 | static final double INF = 1e9, EPS = 1e-9; // better use 1e-11 for large coordinates and 1e-15 if infinite precision is required 6 | 7 | static double degToRad(double d) { return d * Math.PI / 180.0; } 8 | 9 | static double radToDeg(double r) { return r * 180.0 / Math.PI; } 10 | 11 | static double round(double x) { return Math.round(x * 1000) / 1000.0; } //use it because of -0.000 12 | 13 | //Volume of Tetrahedron WXYZ, sides order: WX, WY, WZ, XY, XZ, YZ 14 | static double vTetra(double[] sides) 15 | { 16 | double[] coff = new double[3]; 17 | for(int i = 0; i < 3; i++) 18 | coff[i] = sides[(i+1)%3] * sides[(i+1)%3] + sides[(i+2)%3] * sides[(i+2)%3] - sides[5 - i] * sides[5 - i]; 19 | 20 | double sqrt = 4 * sides[0] * sides[0] * sides[1] * sides[1] * sides[2] * sides[2]; 21 | for(int i = 0; i < 3; i++) 22 | sqrt -= coff[i] * coff[i] * sides[i] * sides[i]; 23 | sqrt += coff[0] * coff[1] * coff[2]; 24 | 25 | return 1 / 12.0 * Math.sqrt(sqrt); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /strings/PrefixAutomaton.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class PrefixAutomaton { 4 | 5 | //Prefix Function: pi[k] = length of longest proper prefix matching a suffix ending at k 6 | static int[] prefixFunction(char[] s) // O(n) 7 | { 8 | int n = s.length, pi[] = new int[n]; 9 | for(int i = 1, j = 0; i < n; ++i) //j = pi[i-1] at the beginning of every iteration 10 | { 11 | while(j > 0 && s[i] != s[j]) 12 | j = pi[j-1]; 13 | if(s[i] == s[j]) 14 | ++j; 15 | pi[i] = j; 16 | } 17 | return pi; 18 | } 19 | 20 | //prefix Automaton 21 | static final int k = 26; //alphabet size; 22 | 23 | static int[][] prefixAutomaton(char[] s) //ends with a delimiter 24 | { 25 | int n = s.length; 26 | int[] pi = prefixFunction(s); 27 | int[][] aut = new int[k][n]; // aut[c][piOld] = piNew 28 | 29 | for(int c = 0; c < k; ++c) 30 | for(int i = 0; i < n; ++i) 31 | if(i > 0 && c != s[i] - 'a') 32 | aut[c][i] = aut[c][pi[i - 1]]; 33 | else 34 | aut[c][i] = i + (c == s[i] - 'a' ? 1 : 0); 35 | return aut; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /math/Polynomial.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | public class Polynomial { 4 | 5 | static final double EPS = 1e-9; 6 | 7 | int degree, coeffs[]; 8 | 9 | Polynomial(int[] c) { degree = c.length - 1; coeffs = c; } 10 | 11 | double evaluate(double x) // O(degree) 12 | { 13 | double res = 0.0; 14 | for(int i = degree; i >= 0; --i) 15 | res = res * x + coeffs[i]; 16 | return res; 17 | } 18 | 19 | Polynomial derivative() // O(degree) 20 | { 21 | if(degree == 0) 22 | return new Polynomial(new int[1]); 23 | int[] c = new int[degree]; 24 | for(int i = 0; i < degree; ++i) 25 | c[i] = coeffs[i + 1] * (i + 1); 26 | return new Polynomial(c); 27 | } 28 | 29 | double findGreatestRoot() 30 | { 31 | Polynomial d = derivative(); 32 | double x1 = 1e6; // initial guess must be greater than greatest root 33 | while(true) // may make a for loop for polynomials with no roots 34 | { 35 | double x2 = x1 - evaluate(x1) / d.evaluate(x1); 36 | if(Math.abs(x1 - x2) < EPS) 37 | break; 38 | x1 = x2; 39 | } 40 | return x1; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /strings/SuffixAutomaton.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.TreeMap; 4 | 5 | public class SuffixAutomaton { 6 | 7 | int[] link, len; 8 | TreeMap[] next; 9 | int lst, idx; 10 | 11 | SuffixAutomaton(char[] s) 12 | { 13 | int n = s.length; 14 | link = new int[n<<1]; 15 | len = new int[n<<1]; 16 | next = new TreeMap[n<<1]; 17 | next[0] = new TreeMap<>(); 18 | for(char c: s) 19 | addLetter(c); 20 | } 21 | 22 | void addLetter(char c) 23 | { 24 | int cur = ++idx, p = lst; 25 | while(!next[p].containsKey(c)) { next[p].put(c, cur); p = link[p]; } 26 | 27 | int q = next[p].get(c); 28 | if(q != cur) 29 | if(len[q] == len[p] + 1) 30 | link[cur] = q; 31 | else 32 | { 33 | int clone = ++idx; 34 | len[clone] = len[p] + 1; 35 | link[clone] = link[q]; 36 | next[clone] = new TreeMap<>(next[q]); 37 | link[cur] = link[q] = clone; 38 | while(next[p].get(c) == q) { next[p].put(c, clone); p = link[p]; } 39 | } 40 | len[cur] = len[lst] + 1; 41 | next[cur] = new TreeMap<>(); 42 | lst = cur; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /graphs/trees/TreeTraversal.java: -------------------------------------------------------------------------------- 1 | package graphs.trees; 2 | 3 | //Build the tree using the in-order and post-order traversals 4 | public class TreeTraversal { 5 | 6 | 7 | static class Node { int val; Node left, right; Node(int x) { val = x; } } 8 | 9 | //idxOf is the idx of the specified node in the in[] array 10 | static Node buildTree(int[] post, int[] in, int[] idxOf) 11 | { 12 | return buildTree(post, in, idxOf, 0, post.length - 1, 0, post.length - 1); //returns the root of the tree 13 | } 14 | 15 | 16 | static Node buildTree(int[] post, int[] in, int[] idxOf, int b_post, int e_post, int b_in, int e_in) 17 | { 18 | if(b_post > e_post || b_in > e_in) 19 | return null; 20 | int idx = idxOf[post[e_post]]; 21 | Node root = new Node(post[e_post]); 22 | 23 | int rightChildren = e_in - idx, leftChildren = idx - b_in; 24 | 25 | root.right = buildTree(post, in, idxOf, e_post - rightChildren, e_post - 1, idx + 1, e_in); 26 | root.left = buildTree(post, in, idxOf, b_post, b_post + leftChildren - 1, b_in, idx - 1); 27 | 28 | return root; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /curriculum/outlines/data_structures/linear_ds_supps.md: -------------------------------------------------------------------------------- 1 | # Linear DS: Supplementary Material 2 | --- 3 | ### Static Arrays 4 | - Accessing time of an array is O(1). However, the constant factor is a little bit higher than basic operations (such as addition or multiplication). 5 | - [Trick] Array dimensions initialization: You can make different sizes for different rows in a 2D static array. 6 | * Example: `int[][] a = new int[2][]; a[0] = new int[10]; a[1] = new int[15];` 7 | - [Pitfall] Static Arrays are objects: `int[] a, b; a = b = new int[10];`. a and b point to same array (any change in a will be reflected in b). 8 | 9 | ### BitSets 10 | - Core idea behind BitSets: BitSets are actually an array of bitmasks. That is, it is an array of integers where each integer represents an array of booleans. This makes BitSets better than boolean arrays from a memory complexity perspective. However, BitSets may perform worse in practice due to the overhead of calling functions (we call `get(x)` to do some stuff that finally gets a specific bit in an internal array of integers) instead of accessing a single boolean array cell. 11 | -------------------------------------------------------------------------------- /data_structures/UnionFind.java: -------------------------------------------------------------------------------- 1 | package data_structures; 2 | 3 | //Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics 4 | public class UnionFind { 5 | int[] p, rank, setSize; 6 | int numSets; 7 | 8 | public UnionFind(int N) 9 | { 10 | p = new int[numSets = N]; 11 | rank = new int[N]; 12 | setSize = new int[N]; 13 | for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; } 14 | } 15 | 16 | public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } 17 | 18 | public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } 19 | 20 | public void unionSet(int i, int j) 21 | { 22 | if (isSameSet(i, j)) 23 | return; 24 | numSets--; 25 | int x = findSet(i), y = findSet(j); 26 | if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } 27 | else 28 | { p[x] = y; setSize[y] += setSize[x]; 29 | if(rank[x] == rank[y]) rank[y]++; 30 | } 31 | } 32 | 33 | public int numDisjointSets() { return numSets; } 34 | 35 | public int sizeOfSet(int i) { return setSize[findSet(i)]; } 36 | } -------------------------------------------------------------------------------- /curriculum/outlines/data_structures/dsu.md: -------------------------------------------------------------------------------- 1 | # Disjoint-Sets Union 2 | --- 3 | ## Outline 4 | - Main functionalities 5 | - Construction 6 | - Naive implementation 7 | - Improvements by heuristics: 8 | - union by size 9 | - union by rank 10 | - path compression 11 | - Complexity for different implementations 12 | - Applications 13 | - Connected components in a graph 14 | - Additional information in the set 15 | - example: storing list of elements for each set 16 | - Online bipartite check 17 | - Distance to set leader 18 | - Parity of path length to leader 19 | --- 20 | ## Material Resources 21 | | Resource | Points Covered | 22 | |:------------------------- |:--------------------------------| 23 | | [Maximal](http://e-maxx.ru/algo/dsu) | All outline points | 24 | | CP 2.4.2 | | 25 | --- 26 | ## Problem Sets 27 | ### Problem Set #1 28 | 29 | | Problem | Tags | Notes | Solution | 30 | |:------------- |:-------------|:-----|:--------| 31 | 32 | ### Problem Set #2 33 | 34 | | Problem | Tags | Notes | Solution | 35 | |:------------- |:-------------|:-----|:--------| 36 | -------------------------------------------------------------------------------- /other_algorithms/ConvexHullOptimization2.java: -------------------------------------------------------------------------------- 1 | package other_algorithms; 2 | 3 | /* 4 | * Convex Hull Optimization 5 | * dp[i] = min(j < i){ dp[j] + a[i] * b[j] } where b[j] >= b[j + 1] 6 | * 7 | * Original Complexity: O(n^2) 8 | * Optimized Complexity: O(n log n) or O(n) if a[i] <= a[i + 1] 9 | * 10 | * Following operations are used within the DP function 11 | * 12 | * Overflow avoided assuming integer x coordinates required for queries (slower due to divisions) 13 | */ 14 | public class ConvexHullOptimization2 { 15 | 16 | long[] A, B, lst; //initialized with size n 17 | int head, end; 18 | 19 | void addLine(long a, long b) // O(n) with amortized complexity 20 | { 21 | while(end - head > 0) 22 | { 23 | lst[end - 1] = Math.floorDiv(b - B[end - 1], A[end - 1] - a); 24 | if(end - head == 1 || lst[end - 1] > lst[end - 2]) 25 | break; 26 | --end; 27 | } 28 | A[end] = a; 29 | B[end] = b; 30 | lst[end] = Long.MAX_VALUE; 31 | ++end; 32 | } 33 | 34 | long queryPointer(long x) // O(n), queries must be performed in increasing order 35 | { 36 | while(lst[head] < x) 37 | ++head; 38 | return A[head] * x + B[head]; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /check tree is BST or not.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define ll long long int 4 | #define llu unsigned long long int 5 | #define f(n) for(ll i=0;i=0;i--) 7 | #define endl "\n" 8 | #define mod 1000000007 9 | 10 | using namespace std; 11 | 12 | class node 13 | { 14 | public: 15 | ll data; 16 | node* left; 17 | node* right; 18 | 19 | node(ll data) 20 | { 21 | this->data = data; 22 | this->left = NULL; 23 | this->right = NULL; 24 | } 25 | }; 26 | 27 | ll isThisBST(node* node, ll min, ll max) 28 | { 29 | if (node==NULL) 30 | return 1; 31 | 32 | if (node->data < min || node->data > max) 33 | return 0; 34 | 35 | return isThisBST(node->left, min, node->data-1) && isThisBST(node->right, node->data+1, max); 36 | } 37 | 38 | int main() 39 | { 40 | node *root = new node(4); 41 | root->left = new node(2); 42 | root->right = new node(5); 43 | root->left->left = new node(1); 44 | root->left->right = new node(3); 45 | 46 | if(isThisBST(root,INT_MIN,INT_MAX)) 47 | cout<<"Is BST"; 48 | else 49 | cout<<"Not a BST"; 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /graphs/traversal/StronglyConnectedComponents1.java: -------------------------------------------------------------------------------- 1 | package graphs.traversal; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Stack; 5 | 6 | /* 7 | * Strongly Connected Components (Directed Graphs) - Tarjan's Algorithm (DFS Variant) 8 | */ 9 | public class StronglyConnectedComponents1 { 10 | 11 | static ArrayList[] adjList; 12 | static int V, counter, SCC, dfs_num[], dfs_low[]; 13 | static boolean[] inSCC; 14 | static Stack stack; 15 | 16 | 17 | static void tarjanSCC() //O(V + E) 18 | { 19 | for(int i = 0; i < V; ++i) 20 | if(dfs_num[i] == 0) 21 | tarjanSCC(i); 22 | } 23 | 24 | static void tarjanSCC(int u) 25 | { 26 | dfs_num[u] = dfs_low[u] = ++counter; 27 | stack.push(u); 28 | 29 | for(int v: adjList[u]) 30 | { 31 | if(dfs_num[v] == 0) 32 | tarjanSCC(v); 33 | if(!inSCC[v]) 34 | dfs_low[u] = Math.min(dfs_low[u], dfs_low[v]); 35 | } 36 | if(dfs_num[u] == dfs_low[u]) 37 | { 38 | //SCC found 39 | SCC++; 40 | while(true) 41 | { 42 | int v = stack.pop(); 43 | inSCC[v] = true; 44 | if(v == u) 45 | break; 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /data_structures/SparseTable.java: -------------------------------------------------------------------------------- 1 | package data_structures; 2 | 3 | // static Range Minimum Query, DP Solution 4 | public class SparseTable { 5 | 6 | int A[], SpT[][]; 7 | 8 | SparseTable(int[] A) 9 | { 10 | int n = A.length; this.A = A; 11 | int k = (int)Math.floor(Math.log(n) / Math.log(2)) + 1; 12 | SpT = new int[n][k]; 13 | 14 | for (int i = 0; i < n; i++) 15 | SpT[i][0] = i; // RMQ of sub array starting at index i and of length 2^0=1 16 | 17 | //overall time complexity = O(n log n) 18 | for (int j = 1; (1<[] adjList, adjListR, graph; 12 | static Stack stack; 13 | static boolean[] visited; 14 | static int SCC; 15 | 16 | 17 | public static int SCC() 18 | { 19 | stack = new Stack(); 20 | visited = new boolean[N]; 21 | graph = adjList; 22 | for(int i = 0; i < N; ++i) 23 | if(!visited[i]) 24 | dfs(i, true); 25 | 26 | visited = new boolean[N]; 27 | graph = adjListR; 28 | SCC = 0; 29 | while(!stack.isEmpty()) 30 | { 31 | int u = stack.pop(); 32 | if(!visited[u]) 33 | { 34 | SCC++; 35 | dfs(u, false); 36 | } 37 | //if visited then this vertex belongs to the SCC of the vertex which visited it 38 | } 39 | 40 | return SCC; 41 | } 42 | 43 | public static void dfs(int u, boolean fillingStack) 44 | { 45 | visited[u] = true; 46 | for(int v: graph[u]) 47 | if(!visited[v]) 48 | dfs(v, fillingStack); 49 | if(fillingStack) 50 | stack.push(u); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /math/game_theory/GamesOnGeneralGraphs.java: -------------------------------------------------------------------------------- 1 | package math.game_theory; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.Queue; 6 | 7 | /* 8 | * Algorithm for finding winning, losing and draw positions in games 9 | * that can represented by a directed graph (possibly with cycles) 10 | */ 11 | public class GamesOnGeneralGraphs { 12 | 13 | static boolean[] win, lose, vis; 14 | static int[] deg; //out degree for all nodes in original graph 15 | static ArrayList[] adjList; //reverse of original graph 16 | static int V; 17 | 18 | static void go() // O(V + E) 19 | { 20 | vis = new boolean[V]; 21 | win = new boolean[V]; 22 | lose = new boolean[V]; 23 | Queue q = new LinkedList(); 24 | /* 25 | * Initially insert in the queue all nodes known to be winning or losing 26 | * and mark them in vis and either in win or lose. 27 | */ 28 | while(!q.isEmpty()) 29 | { 30 | int v = q.remove(); 31 | for(int u: adjList[v]) 32 | if(!vis[u]) 33 | { 34 | if(lose[v]) 35 | win[u] = true; 36 | else if(--deg[u] == 0) 37 | lose[u] = true; 38 | else 39 | continue; 40 | vis[u] = true; 41 | q.add(u); 42 | } 43 | } 44 | 45 | // !win[u] & !lose[u] -> draw[u] 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /graphs/mst/MST_Kruskal.java: -------------------------------------------------------------------------------- 1 | package graphs.mst; 2 | 3 | import java.util.Arrays; 4 | 5 | public class MST_Kruskal { 6 | 7 | static Edge[] edgeList; 8 | static int V; 9 | 10 | static int kruskal() //O(E log E) 11 | { 12 | int mst = 0; 13 | Arrays.sort(edgeList); 14 | UnionFind uf = new UnionFind(V); 15 | 16 | for(Edge e: edgeList) 17 | if(uf.union(e.u, e.v)) 18 | mst += e.w; 19 | return mst; 20 | } 21 | 22 | static class Edge implements Comparable 23 | { 24 | int u, v, w; 25 | 26 | Edge(int a, int b, int c) { u = a; v = b; w = c; } 27 | 28 | public int compareTo(Edge e) { return w - e.w; } 29 | } 30 | 31 | static class UnionFind { 32 | int[] p, rank; 33 | 34 | UnionFind(int N) 35 | { 36 | p = new int[N]; 37 | rank = new int[N]; 38 | for (int i = 0; i < N; i++) 39 | p[i] = i; 40 | } 41 | 42 | int findSet(int x) { return p[x] == x ? x : (p[x] = findSet(p[x])); } 43 | 44 | boolean union(int x, int y) 45 | { 46 | x = findSet(x); 47 | y = findSet(y); 48 | if(x == y) 49 | return false; 50 | 51 | if (rank[x] > rank[y]) 52 | p[y] = x; 53 | else 54 | { 55 | p[x] = y; 56 | if(rank[x] == rank[y]) 57 | ++rank[y]; 58 | } 59 | return true; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /strings/SuffixArray.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class SuffixArray { 4 | 5 | int[] SA; 6 | 7 | SuffixArray(char[] s) //has a terminating character (e.g. '$') 8 | { 9 | int n = s.length, RA[] = new int[n]; 10 | SA = new int[n]; 11 | 12 | for(int i = 0; i < n; ++i) { RA[i] = s[i]; SA[i] = i; } 13 | 14 | for(int k = 1; k < n; k <<= 1) 15 | { 16 | sort(SA, RA, n, k); 17 | sort(SA, RA, n, 0); 18 | int[] tmp = new int[n]; 19 | 20 | for(int i = 1, r = 0, s1 = SA[0], s2; i < n; ++i) 21 | { 22 | s2 = SA[i]; 23 | tmp[s2] = RA[s1] == RA[s2] && RA[s1 + k] == RA[s2 + k] ? r : ++r; 24 | s1 = s2; 25 | } 26 | for(int i = 0; i < n; ++i) 27 | RA[i] = tmp[i]; 28 | 29 | if(RA[SA[n-1]] == n - 1) 30 | break; 31 | } 32 | } 33 | 34 | void sort(int[] SA, int[] RA, int n, int k) 35 | { 36 | int maxi = Math.max(256, n), c[] = new int[maxi]; 37 | for(int i = 0; i < n; ++i) 38 | c[i + k < n ? RA[i + k] : 0]++; 39 | for(int i = 0, sum = 0; i < maxi; ++i) 40 | { 41 | int t = c[i]; 42 | c[i] = sum; 43 | sum += t; 44 | } 45 | int[] tmp = new int[n]; 46 | for(int i = 0; i < n; ++i) 47 | { 48 | int j = SA[i] + k; 49 | tmp[c[j < n ? RA[j] : 0]++] = SA[i]; 50 | } 51 | 52 | for(int i = 0; i < n; ++i) 53 | SA[i] = tmp[i]; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /strings/AhoCorasick.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.Arrays; 4 | 5 | public class AhoCorasick { 6 | 7 | static final int k = 26; 8 | 9 | static class Node 10 | { 11 | int p, c, link = -1; 12 | boolean leaf; 13 | 14 | Node(int a, int b) { p = a; c = b; } 15 | 16 | int[] next = new int[26], go = new int[26]; 17 | { 18 | Arrays.fill(next, -1); 19 | Arrays.fill(go, -1); 20 | } 21 | } 22 | 23 | Node[] nodes; 24 | int nodeCount; 25 | 26 | AhoCorasick(int maxNodes) 27 | { 28 | nodes = new Node[maxNodes]; 29 | nodes[nodeCount++] = new Node(0, -1); 30 | } 31 | 32 | void addString(char[] s) 33 | { 34 | int cur = 0; 35 | for(char ch: s) 36 | { 37 | int c = ch - 'a'; 38 | if(nodes[cur].next[c] == -1) 39 | { 40 | nodes[nodeCount] = new Node(cur, c); 41 | nodes[cur].next[c] = nodeCount++; 42 | } 43 | cur = nodes[cur].next[c]; 44 | } 45 | nodes[cur].leaf = true; 46 | } 47 | 48 | int link(int vIdx) 49 | { 50 | Node v = nodes[vIdx]; 51 | if(v.link == -1) 52 | v.link = v.p == 0 ? 0 : go(link(v.p), v.c); 53 | return v.link; 54 | } 55 | 56 | int go(int vIdx, int c) 57 | { 58 | Node v = nodes[vIdx]; 59 | if(v.go[c] == -1) 60 | v.go[c] = v.next[c] != -1 ? v.next[c] : vIdx == 0 ? 0 : go(link(vIdx), c); 61 | return v.go[c]; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /curriculum/outlines/graphs/sssp.md: -------------------------------------------------------------------------------- 1 | # Single-Source Shortest Path 2 | --- 3 | ## Outline 4 | 1. Problem Definition 5 | 2. SSSP on Unweighted Graphs: BFS Algorithm 6 | - Graph with constant similar weights - multiply answer by that constant 7 | - Graph with small weights - duplicate the nodes 8 | - 0-1 weighted graph - modified bfs 9 | - Multi-source variant 10 | - State-space search 11 | 3. SSSP on Weighted Graphs: Dijkstra Algorithm 12 | - Multi-source variant 13 | - State-space search 14 | - Failure on negative weights 15 | 16 | --- 17 | 18 | ## Material Resources 19 | | Resource | Points Covered | 20 | |:------------------------- |:--------------------------------| 21 | | CP Section 4.4.1-3 | All outline points | 22 | | CP Section 8.2.3 | State-space search | 23 | | [Maximal: Dijkstra 1](http://e-maxx.ru/algo/dijkstra) | Extra | 24 | | [Maximal: Dijkstra 2](http://e-maxx.ru/algo/dijkstra_sparse) | Extra | 25 | 26 | --- 27 | ## Problem Sets 28 | ### Problem Set #1 29 | 30 | | Problem | Tags | Notes | Solution | 31 | |:------------- |:-------------|:-----|:--------| 32 | | | | | |UVa [10986, 1112, 12160, 11487, 10356] 33 | | | | | | 34 | | | | | | 35 | | | | | | 36 | | | | | | 37 | | | | | | 38 | | | | | | 39 | | | | | | 40 | | | | | | 41 | | | | | | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /DynamicProgramming/Knapsack.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | /** 4 | * A DynamicProgramming based solution for 0-1 Knapsack problem 5 | */ 6 | 7 | public class Knapsack { 8 | 9 | private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArgumentException { 10 | if(wt == null || val == null) 11 | throw new IllegalArgumentException(); 12 | int i, w; 13 | int rv[][] = new int[n + 1][W + 1]; //rv means return value 14 | 15 | // Build table rv[][] in bottom up manner 16 | for (i = 0; i <= n; i++) { 17 | for (w = 0; w <= W; w++) { 18 | if (i == 0 || w == 0) 19 | rv[i][w] = 0; 20 | else if (wt[i - 1] <= w) 21 | rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]); 22 | else 23 | rv[i][w] = rv[i - 1][w]; 24 | } 25 | } 26 | 27 | return rv[n][W]; 28 | } 29 | 30 | 31 | // Driver program to test above function 32 | public static void main(String args[]) { 33 | int val[] = new int[]{50, 100, 130}; 34 | int wt[] = new int[]{10, 20, 40}; 35 | int W = 50; 36 | int n = val.length; 37 | System.out.println(knapSack(W, wt, val, n)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /graphs/traversal/ArticulationPointsAndBridges.java: -------------------------------------------------------------------------------- 1 | package graphs.traversal; 2 | 3 | import java.util.ArrayList; 4 | 5 | /* 6 | * Articulation Points and Bridges in Undirected Graphs - Tarjan's Algorithm (DFS Variant) 7 | */ 8 | public class ArticulationPointsAndBridges { 9 | 10 | static ArrayList[] adjList; 11 | static int[] dfs_low, dfs_num, parent; 12 | static int V, counter, root, rootChildren; 13 | static boolean[] artPoints; 14 | 15 | static void findArtPointsAndBridges() //O(V + E) 16 | { 17 | for(int i = 0; i < V; ++i) 18 | if(dfs_num[i] == 0) 19 | { 20 | root = i; 21 | rootChildren = 0; 22 | dfs(i); 23 | if(rootChildren <= 1) //special case 24 | artPoints[i] = false; 25 | } 26 | } 27 | 28 | static void dfs(int u) 29 | { 30 | dfs_num[u] = dfs_low[u] = ++counter; 31 | for(int v: adjList[u]) 32 | if(dfs_num[v] == 0) 33 | { 34 | parent[v] = u; 35 | if(u == root) 36 | ++rootChildren; 37 | dfs(v); 38 | if(dfs_low[v] >= dfs_num[u]) 39 | artPoints[u] = true; 40 | if(dfs_low[v] > dfs_num[u]) 41 | System.out.printf("Bridge between %d %d%n", u, v); 42 | dfs_low[u] = Math.min(dfs_low[v], dfs_low[u]); 43 | } 44 | else 45 | if(parent[u] != v) 46 | dfs_low[u] = Math.min(dfs_low[u], dfs_num[v]); 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /2stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long 4 | 5 | class t2stack 6 | { 7 | ll *a; 8 | ll size,top1,top2; 9 | public: 10 | t2stack(ll n) 11 | { 12 | size=n; 13 | a=new ll[n]; 14 | top1=-1; 15 | top2=size; 16 | } 17 | 18 | void push1(ll n) 19 | { 20 | if(top1+1=0) 44 | { 45 | cout< 0) { sum += ft[b]; b -= b & -b;} //min? 14 | return sum; 15 | } 16 | 17 | int rsq(int a, int b) { return rsq(b) - rsq(a-1); } 18 | 19 | void point_update(int k, int val) //O(log n), update = increment 20 | { 21 | while(k <= n) { ft[k] += val; k += k & -k; } //min? 22 | } 23 | 24 | int point_query(int idx) // c * O(log n), c < 1 25 | { 26 | int sum = ft[idx]; 27 | if(idx > 0) 28 | { 29 | int z = idx ^ (idx & -idx); 30 | --idx; 31 | while(idx != z) 32 | { 33 | sum -= ft[idx]; 34 | idx ^= idx & -idx; 35 | } 36 | } 37 | return sum; 38 | } 39 | 40 | void scale(int c) { for(int i = 1; i <= n; ++i) ft[i] *= c; } 41 | 42 | int findIndex(int cumFreq) 43 | { 44 | int msk = n; 45 | while((msk & (msk - 1)) != 0) 46 | msk ^= msk & -msk; //msk will contain the MSB of n 47 | 48 | int idx = 0; 49 | while(msk != 0) 50 | { 51 | int tIdx = idx + msk; 52 | if(tIdx <= n && cumFreq >= ft[tIdx]) 53 | { 54 | idx = tIdx; 55 | cumFreq -= ft[tIdx]; 56 | } 57 | msk >>= 1; 58 | } 59 | if(cumFreq != 0) 60 | return -1; 61 | return idx; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /math/NewtonMethod.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | import java.math.BigInteger; 4 | 5 | public class NewtonMethod { 6 | 7 | /* 8 | * Newton's Method: Xn+1 = Xn - f(Xn) / f'(Xn) 9 | * Purpose: Find roots of a real-valued function, i.e. solve f(x) = 0 10 | */ 11 | 12 | static final double EPS = 1e-15; 13 | 14 | /* 15 | * 1. Find square root of n 16 | */ 17 | static double sqrt(double n) 18 | { 19 | double x = 1; 20 | while(true) 21 | { 22 | double nx = (x + n / x) / 2; 23 | if(Math.abs(nx - x) < EPS) 24 | break; 25 | x = nx; 26 | } 27 | return x; 28 | } 29 | 30 | /* 31 | * 2. Find largest integer x where x^2 <= n 32 | */ 33 | static int nearestInteger(int n) 34 | { 35 | int x = 1; 36 | boolean dec = false; 37 | while(true) 38 | { 39 | int nx = x + n / x >> 1; 40 | if(x == nx || nx > x && dec) 41 | break; 42 | dec = nx < x; 43 | x = nx; 44 | } 45 | return x; 46 | } 47 | 48 | /* 49 | * 3. Find largest integer x where x^2 <= n, better initial approximation for long arithmetic 50 | */ 51 | static BigInteger nearestInteger(BigInteger n) 52 | { 53 | BigInteger x = BigInteger.ONE.shiftLeft(n.bitLength() >> 1); 54 | boolean dec = false; 55 | while(true) 56 | { 57 | BigInteger nx = x.add(n.divide(x)).shiftRight(1); 58 | int cmp = nx.compareTo(x); 59 | if(cmp == 0 || cmp > 0 && dec) 60 | break; 61 | dec = cmp < 0; 62 | x = nx; 63 | } 64 | return x; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /bfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long 4 | class graph 5 | { 6 | int V; 7 | list *adj; 8 | public: 9 | graph(int V); 10 | void add(int u,int v); 11 | void BFS(int v); 12 | }; 13 | 14 | graph::graph(int V) 15 | { 16 | this->V=V; 17 | adj=new list[V]; 18 | } 19 | 20 | void graph::add(int u,int v) 21 | { 22 | adj[u].push_back(v); 23 | } 24 | void graph::BFS(int s) 25 | { 26 | bool *visited=new bool[V]; 27 | for(int i=0;i queue; 32 | 33 | visited[s]=true; 34 | queue.push_back(s); 35 | 36 | 37 | list::iterator i; 38 | 39 | 40 | while(!queue.empty()) 41 | { 42 | s=queue.front(); 43 | cout< q.left) add(a[--L]); 33 | while(L < q.left) remove(a[L++]); 34 | while(R > q.right) remove(a[R--]); 35 | res[q.idx] = ans; 36 | } 37 | return res; 38 | } 39 | 40 | static class Query implements Comparable 41 | { 42 | static int s; // length of a block , s = sqrt(n) 43 | int left, right, idx; 44 | 45 | Query(int a, int b, int c) 46 | { 47 | left = a; right = b; idx = c; 48 | } 49 | 50 | public int compareTo(Query q) 51 | { 52 | if(left / s != q.left / s) 53 | return left / s - q.left / s; 54 | return right - q.right; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /graphs/max_flow/MaxFlow1.java: -------------------------------------------------------------------------------- 1 | package graphs.max_flow; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | /* 9 | * Max Flow: Edmonds Karp's Algorithm 10 | */ 11 | public class MaxFlow1 { 12 | 13 | static final int INF = (int)1e9; 14 | static int V, s, t; //s != t 15 | static ArrayList[] adjList; 16 | static int[][] res; //instead of res, you can use c[][], f[][] so as not to destroy the graph 17 | static int[] p; //res (residual) = c (capacity) - f (flow) 18 | 19 | static int edmondsKarp() //O(min(VE^2, flow * E)) for adjList, O(V^3E) 20 | { 21 | int mf = 0; 22 | while(true) 23 | { 24 | Queue q = new LinkedList(); 25 | p = new int[V]; 26 | Arrays.fill(p, -1); 27 | q.add(s); 28 | p[s] = s; 29 | while(!q.isEmpty()) 30 | { 31 | int u = q.remove(); 32 | if(u == t) 33 | break; 34 | for(int v: adjList[u]) 35 | if(res[u][v] > 0 && p[v] == -1) 36 | { 37 | p[v] = u; 38 | q.add(v); 39 | } 40 | } 41 | 42 | if(p[t] == -1) 43 | break; 44 | mf += augment(t, INF); 45 | } 46 | return mf; 47 | } 48 | 49 | static int augment(int v, int flow) 50 | { 51 | if(v == s) 52 | return flow; 53 | flow = augment(p[v], Math.min(flow, res[p[v]][v])); 54 | res[p[v]][v] -= flow; 55 | res[v][p[v]] += flow; 56 | 57 | return flow; 58 | } 59 | } 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /math/number_theory/ModifiedSieve.java: -------------------------------------------------------------------------------- 1 | package math.number_theory; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ModifiedSieve { 6 | 7 | /* 8 | * 1. Modified sieve for number of prime factors 9 | */ 10 | static void numPF(int N) 11 | { 12 | int[] pf = new int[N]; 13 | for(int i = 2; i < N; ++i) 14 | if(pf[i] == 0) 15 | for(int j = i; j < N; j += i) 16 | { 17 | int p = 0, k = j; 18 | while(k % i == 0) 19 | { 20 | k /= i; 21 | ++p; 22 | } 23 | pf[j] += p; 24 | } 25 | } 26 | 27 | /* 28 | * 2. Modified sieve for phi function 29 | */ 30 | static void phi(int N) 31 | { 32 | int[] phi = new int[N]; 33 | for(int i = 1; i < N; ++i) 34 | phi[i] = i; 35 | 36 | for(int i = 2; i < N; ++i) 37 | if(phi[i] == i) 38 | for(int j = i; j < N; j += i) 39 | phi[j] -= phi[j] / i; 40 | } 41 | 42 | /* 43 | * 3. Modified sieve for square-free numbers (prime factorization doesn't include a factor with power > 1) 44 | * Useful in inclusion-exclusion problems that need divisibility counting 45 | */ 46 | static void squareFree(int N) 47 | { 48 | boolean[] prime = new boolean[N]; 49 | Arrays.fill(prime, true); 50 | 51 | boolean[] squareFree = new boolean[N]; 52 | Arrays.fill(squareFree, true); 53 | 54 | for(int i = 2; i <= N; ++i) 55 | if(prime[i]) 56 | for(int j = 2; i * j <= N; ++j) 57 | { 58 | prime[i*j] = false; 59 | if(j % i == 0) 60 | squareFree[i*j] = false; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /graphs/traversal/BridgeTree.java: -------------------------------------------------------------------------------- 1 | package graphs.traversal; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Stack; 5 | 6 | public class BridgeTree { 7 | 8 | static ArrayList[] adjList, tree; 9 | static Stack stack; 10 | static int[] dfs_low, dfs_num, bridgeComp; 11 | static int V, counter; 12 | 13 | static void bridgeTree() 14 | { 15 | counter = 0; 16 | dfs_low = new int[V]; 17 | dfs_num = new int[V]; 18 | bridgeComp = new int[V]; 19 | stack = new Stack(); 20 | tree = new ArrayList[V]; 21 | for(int i = 0; i < V; ++i) 22 | tree[i] = new ArrayList(); 23 | for(int i = 0; i < V; ++i) 24 | if(dfs_num[i] == 0) 25 | dfs(i, -1); 26 | for(int u = 0; u < V; ++u) 27 | for(int v: adjList[u]) 28 | { 29 | int x = bridgeComp[u], y = bridgeComp[v]; 30 | if(x != y) 31 | tree[x].add(y); 32 | } 33 | } 34 | 35 | static void dfs(int u, int p) 36 | { 37 | dfs_num[u] = dfs_low[u] = ++counter; 38 | stack.push(u); 39 | for(int v: adjList[u]) 40 | if(v != p) 41 | if(dfs_num[v] == 0) 42 | { 43 | dfs(v, u); 44 | dfs_low[u] = Math.min(dfs_low[u], dfs_low[v]); 45 | if(dfs_low[v] > dfs_num[u]) 46 | extract(v); 47 | } 48 | else 49 | dfs_low[u] = Math.min(dfs_low[u], dfs_num[v]); 50 | if(p == -1) 51 | extract(u); 52 | } 53 | 54 | static void extract(int u) 55 | { 56 | while(true) 57 | { 58 | int v = stack.pop(); 59 | bridgeComp[v] = u; 60 | if(v == u) 61 | break; 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /graphs/special/EulerTour.java: -------------------------------------------------------------------------------- 1 | package graphs.special; 2 | import java.util.ArrayList; 3 | import java.util.LinkedList; 4 | import java.util.ListIterator; 5 | 6 | /* 7 | * Printing Euler Tour in an Eulerian Graph 8 | */ 9 | public class EulerTour { 10 | 11 | static class Edge 12 | { 13 | int node; 14 | boolean used; 15 | 16 | Edge(int x) { node = x; } 17 | } 18 | 19 | static ArrayList[] adjList; 20 | static LinkedList tour; 21 | 22 | static void eulerTour(ListIterator itr, int u) 23 | { 24 | for(Edge nxt: adjList[u]) 25 | if(!nxt.used) 26 | { 27 | nxt.used = true; 28 | for(Edge rev: adjList[nxt.node]) 29 | if(rev.node == u && !rev.used) 30 | { 31 | rev.used = true; 32 | break; 33 | } 34 | itr.add(u); 35 | eulerTour(itr, nxt.node); 36 | itr.previous(); 37 | } 38 | } 39 | 40 | static void addEdge(int u, int v) 41 | { 42 | adjList[u].add(new Edge(v)); 43 | adjList[v].add(new Edge(u)); 44 | } 45 | 46 | public static void main(String[] args) 47 | { 48 | adjList = new ArrayList[7]; 49 | for(int i = 0; i < 7; ++i) 50 | adjList[i] = new ArrayList(); 51 | addEdge(6, 3); addEdge(3, 4); addEdge(4, 5); addEdge(5, 6); 52 | addEdge(6, 0); addEdge(0, 1); addEdge(1, 2); addEdge(2, 6); 53 | addEdge(0, 2); addEdge(0, 5); addEdge(2, 3); addEdge(5, 3); 54 | 55 | tour = new LinkedList(); 56 | eulerTour(tour.listIterator(), 6); //the tour will start from vertex 6 57 | tour.add(6); 58 | 59 | System.out.println(tour); 60 | } 61 | } -------------------------------------------------------------------------------- /other_algorithms/ConvexHullOptimization1.java: -------------------------------------------------------------------------------- 1 | package other_algorithms; 2 | 3 | /* 4 | * Convex Hull Optimization 5 | * dp[i] = min(j < i){ dp[j] + a[i] * b[j] } where b[j] >= b[j + 1] 6 | * 7 | * Original Complexity: O(n^2) 8 | * Optimized Complexity: O(n log n) or O(n) if a[i] <= a[i + 1] 9 | * 10 | * Following operations are used within the DP function 11 | * 12 | * Can be trapped in overflow 13 | */ 14 | public class ConvexHullOptimization1 { 15 | 16 | long[] A, B; //initialized with size n 17 | int ptr, len; 18 | 19 | void addLine(long a, long b) // O(n) with amortized complexity 20 | { 21 | while(len >= 2 && 22 | (A[len - 2] - A[len - 1]) * (b - B[len - 1]) <= (A[len - 1] - a) * (B[len - 1] - B[len - 2])) 23 | --len; 24 | A[len] = a; 25 | B[len] = b; 26 | ++len; 27 | } 28 | 29 | long queryPointer(long x) // O(n), queries must be performed in increasing order 30 | { 31 | ptr = Math.min(ptr, len - 1); 32 | while(ptr < len - 1 && A[ptr + 1] * x + B[ptr + 1] <= A[ptr] * x + B[ptr]) 33 | ++ptr; 34 | return A[ptr] * x + B[ptr]; 35 | } 36 | 37 | long queryBS(long x) // O(n log n) -- TODO needs testing 38 | { 39 | int ans = 0; 40 | int lo = 1, hi = len - 1; 41 | while(lo <= hi) 42 | { 43 | int mid = lo + hi >> 1; 44 | // if intersect_x(mid, mid - 1) <= x, then ans = mid & search for higher 45 | if(B[mid] - B[mid - 1] <= x * (A[mid - 1] - A[mid])) 46 | { 47 | ans = cur; 48 | lo = mid + 1; 49 | } 50 | else 51 | hi = mid - 1; 52 | } 53 | return A[ans] * x + B[ans]; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /data_structures/trees/PersistentSegmentTree.java: -------------------------------------------------------------------------------- 1 | package data_structures.trees; 2 | 3 | public class PersistentSegmentTree { 4 | 5 | class Node 6 | { 7 | Node left, right; int sum; 8 | 9 | Node(int x) { sum = x; } 10 | 11 | Node(Node left, Node right) 12 | { 13 | this.left = left; 14 | this.right = right; 15 | if(left != null) 16 | sum += left.sum; 17 | if(right != null) 18 | sum += right.sum; 19 | } 20 | } 21 | 22 | Node build(int[] a, int l, int r) // returns root of the initial version, a is a power of 2 and 0-based 23 | { 24 | if(l == r) 25 | return new Node(a[l - 1]); 26 | int mid = (l + r) >> 1; 27 | return new Node(build(a, l, mid), build(a, mid + 1, r)); 28 | } 29 | 30 | int query(Node v, int l, int r, int b, int e) 31 | { 32 | if(e < l || r < b) 33 | return 0; 34 | if(b <= l && r <= e) 35 | return v.sum; 36 | int mid = (l + r) >> 1; 37 | return query(v.left, l, mid, b, e) + query(v.right, mid + 1, r, b, e); 38 | } 39 | 40 | Node update(Node v, int l, int r, int idx, int val) // returns root of new version, idx is 1-basd 41 | { 42 | if(l == r) 43 | return new Node(val); 44 | int mid = (l + r) >> 1; 45 | if(idx <= mid) 46 | return new Node(update(v.left, l, mid, idx, val), v.right); 47 | else 48 | return new Node(v.left, update(v.right, mid + 1, r, idx, val)); 49 | } 50 | } -------------------------------------------------------------------------------- /DynamicProgramming/SubsetSum.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | public class SubsetSum { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | int[] arr = new int[]{50, 4, 10, 15, 34}; 10 | assert subsetSum(arr, 64); /* 4 + 10 + 15 + 34 = 64 */ 11 | assert subsetSum(arr, 99); /* 50 + 15 + 34 = 99 */ 12 | assert !subsetSum(arr, 5); 13 | assert !subsetSum(arr, 66); 14 | } 15 | 16 | /** 17 | * Test if a set of integers contains a subset that sum to a given integer. 18 | * 19 | * @param arr the array contains integers. 20 | * @param sum target sum of subset. 21 | * @return {@code true} if subset exists, otherwise {@code false}. 22 | */ 23 | private static boolean subsetSum(int[] arr, int sum) { 24 | int n = arr.length; 25 | boolean[][] isSum = new boolean[n + 2][sum + 1]; 26 | 27 | isSum[n + 1][0] = true; 28 | for (int i = 1; i <= sum; i++) { 29 | isSum[n + 1][i] = false; 30 | } 31 | 32 | for (int i = n; i > 0; i--) { 33 | isSum[i][0] = true; 34 | for (int j = 1; j <= arr[i - 1] - 1; j++) { 35 | if (j <= sum) { 36 | isSum[i][j] = isSum[i + 1][j]; 37 | } 38 | } 39 | for (int j = arr[i - 1]; j <= sum; j++) { 40 | isSum[i][j] = (isSum[i + 1][j] || isSum[i + 1][j - arr[i - 1]]); 41 | } 42 | } 43 | 44 | return isSum[1][sum]; 45 | } 46 | } -------------------------------------------------------------------------------- /graphs/max_flow/MaxFlow2.java: -------------------------------------------------------------------------------- 1 | package graphs.max_flow; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | //Try to test the implementation with some input of your choice 8 | public class MaxFlow2 { 9 | 10 | static final int INF = (int)1e9; 11 | static int V, s, t, res[][]; //input 12 | static ArrayList[] adjList; //input 13 | static int[] ptr, dist; 14 | 15 | static int dinic() //O(V^2E) 16 | { 17 | int mf = 0; 18 | while(bfs()) 19 | { 20 | ptr = new int[V]; 21 | int f; 22 | while((f = dfs(s, INF)) != 0) 23 | mf += f; 24 | } 25 | return mf; 26 | } 27 | 28 | 29 | static boolean bfs() 30 | { 31 | dist = new int[V]; 32 | Arrays.fill(dist, -1); 33 | dist[s] = 0; 34 | Queue q = new LinkedList(); 35 | q.add(s); 36 | while(!q.isEmpty()) 37 | { 38 | int u = q.remove(); 39 | if(u == t) 40 | return true; 41 | for(int v: adjList[u]) 42 | if(dist[v] == -1 && res[u][v] > 0) 43 | { 44 | dist[v] = dist[u] + 1; 45 | q.add(v); 46 | } 47 | } 48 | return false; 49 | } 50 | 51 | static int dfs(int u, int flow) 52 | { 53 | if(u == t) 54 | return flow; 55 | for(int i = ptr[u]; i < adjList[u].size(); i = ++ptr[u]) 56 | { 57 | int v = adjList[u].get(i); 58 | if(dist[v] == dist[u] + 1 && res[u][v] > 0) 59 | { 60 | int f = dfs(v, Math.min(flow, res[u][v])); 61 | if(f > 0) 62 | { 63 | res[u][v] -= f; 64 | res[v][u] += f; 65 | return f; 66 | } 67 | } 68 | } 69 | return 0; 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /other_algorithms/Scanner.java: -------------------------------------------------------------------------------- 1 | package other_algorithms; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | import java.util.StringTokenizer; 8 | 9 | class Scanner 10 | { 11 | StringTokenizer st; 12 | BufferedReader br; 13 | 14 | public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} 15 | 16 | public String next() throws IOException 17 | { 18 | while (st == null || !st.hasMoreTokens()) 19 | st = new StringTokenizer(br.readLine()); 20 | return st.nextToken(); 21 | } 22 | 23 | public int nextInt() throws IOException {return Integer.parseInt(next());} 24 | 25 | public long nextLong() throws IOException {return Long.parseLong(next());} 26 | 27 | public String nextLine() throws IOException {return br.readLine();} 28 | 29 | public double nextDouble() throws IOException 30 | { 31 | String x = next(); 32 | StringBuilder sb = new StringBuilder("0"); 33 | double res = 0, f = 1; 34 | boolean dec = false, neg = false; 35 | int start = 0; 36 | if(x.charAt(0) == '-') 37 | { 38 | neg = true; 39 | start++; 40 | } 41 | for(int i = start; i < x.length(); i++) 42 | if(x.charAt(i) == '.') 43 | { 44 | res = Long.parseLong(sb.toString()); 45 | sb = new StringBuilder("0"); 46 | dec = true; 47 | } 48 | else 49 | { 50 | sb.append(x.charAt(i)); 51 | if(dec) 52 | f *= 10; 53 | } 54 | res += Long.parseLong(sb.toString()) / f; 55 | return res * (neg?-1:1); 56 | } 57 | 58 | public boolean ready() throws IOException {return br.ready();} 59 | 60 | 61 | } -------------------------------------------------------------------------------- /DynamicProgramming/EggDropping.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | /** 4 | * DynamicProgramming solution for the Egg Dropping Puzzle 5 | */ 6 | public class EggDropping { 7 | 8 | // min trials with n eggs and m floors 9 | 10 | private static int minTrials(int n, int m) { 11 | 12 | int[][] eggFloor = new int[n + 1][m + 1]; 13 | int result, x; 14 | 15 | for (int i = 1; i <= n; i++) { 16 | eggFloor[i][0] = 0; // Zero trial for zero floor. 17 | eggFloor[i][1] = 1; // One trial for one floor 18 | } 19 | 20 | // j trials for only 1 egg 21 | 22 | for (int j = 1; j <= m; j++) 23 | eggFloor[1][j] = j; 24 | 25 | // Using bottom-up approach in DP 26 | 27 | for (int i = 2; i <= n; i++) { 28 | for (int j = 2; j <= m; j++) { 29 | eggFloor[i][j] = Integer.MAX_VALUE; 30 | for (x = 1; x <= j; x++) { 31 | result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); 32 | 33 | // choose min of all values for particular x 34 | if (result < eggFloor[i][j]) 35 | eggFloor[i][j] = result; 36 | } 37 | } 38 | } 39 | 40 | return eggFloor[n][m]; 41 | } 42 | 43 | public static void main(String args[]) { 44 | int n = 2, m = 4; 45 | // result outputs min no. of trials in worst case for n eggs and m floors 46 | int result = minTrials(n, m); 47 | System.out.println(result); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /DynamicProgramming/KadaneAlgorithm.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Program to implement Kadane’s Algorithm to 7 | * calculate maximum contiguous subarray sum of an array 8 | * Time Complexity: O(n) 9 | * 10 | * @author Nishita Aggarwal 11 | */ 12 | 13 | public class KadaneAlgorithm { 14 | 15 | /** 16 | * This method implements Kadane's Algorithm 17 | * 18 | * @param arr The input array 19 | * @return The maximum contiguous subarray sum of the array 20 | */ 21 | static int largestContiguousSum(int arr[]) { 22 | int i, len = arr.length, cursum = 0, maxsum = Integer.MIN_VALUE; 23 | if (len == 0) //empty array 24 | return 0; 25 | for (i = 0; i < len; i++) { 26 | cursum += arr[i]; 27 | if (cursum > maxsum) { 28 | maxsum = cursum; 29 | } 30 | if (cursum <= 0) { 31 | cursum = 0; 32 | } 33 | } 34 | return maxsum; 35 | } 36 | 37 | /** 38 | * Main method 39 | * 40 | * @param args Command line arguments 41 | */ 42 | public static void main(String[] args) { 43 | Scanner sc = new Scanner(System.in); 44 | int n, arr[], i; 45 | n = sc.nextInt(); 46 | arr = new int[n]; 47 | for (i = 0; i < n; i++) { 48 | arr[i] = sc.nextInt(); 49 | } 50 | int maxContSum = largestContiguousSum(arr); 51 | System.out.println(maxContSum); 52 | sc.close(); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /math/combinatorics/BinomialCoefficient.java: -------------------------------------------------------------------------------- 1 | package math.combinatorics; 2 | 3 | public class BinomialCoefficient { 4 | 5 | /* 6 | * 1. Pascal's Rule: recursive | Top-down approach 7 | */ 8 | static long[][] comb; //may need BigInteger, if the numbers are large, use a treemap 9 | 10 | static long nCr1(int n , int k) 11 | { 12 | if(n < k) 13 | return 0; 14 | if(k == 0 || k == n) 15 | return 1; 16 | if(comb[n][k] != -1) 17 | return comb[n][k]; 18 | if(n - k < k) 19 | return comb[n][k] = nCr1(n, n - k); 20 | return comb[n][k] = nCr1(n - 1, k - 1) + nCr1(n - 1, k); 21 | } 22 | 23 | /* 24 | * 2. Pascal's Rule: iterative | Bottom-up approach 25 | */ 26 | static void nCr2(int N) // O(N * N) 27 | { 28 | comb = new long[N][N]; 29 | comb[0][0] = 1; 30 | for (int i = 1; i < N; i++) 31 | { 32 | comb[i][0] = 1; 33 | for (int j = 1; j <= i; j++) 34 | comb[i][j] = (comb[i-1][j] + comb[i-1][j-1]); //may use mod 35 | } 36 | } 37 | 38 | /* 39 | * 3. Multiplicative formula: recursive | Top-down approach 40 | */ 41 | static long nCr3(int n, int k) // O(n * k) 42 | { 43 | if(n < k) 44 | return 0; 45 | if(k == 0 || k == n) //may add k == 1 as a base case for fast calculations 46 | return 1; 47 | if(comb[n][k] != -1) 48 | return comb[n][k]; 49 | if(n - k < k) 50 | return comb[n][k] = nCr3(n, n - k); //reduce k to n - k 51 | return comb[n][k] = n * nCr3(n - 1, k - 1) / k; 52 | } 53 | 54 | 55 | /* 56 | * 4. Multiplicative formula: iterative 57 | */ 58 | static int nCr4(int N, int K) // O(K) 59 | { 60 | if(K > N) 61 | return 0; 62 | int res = 1; 63 | for(int i = 1; i <= K; ++i) 64 | res = (N - K + i) * res / i; 65 | return res; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /geometry/LineSweep.java: -------------------------------------------------------------------------------- 1 | package geometry; 2 | import java.io.IOException; 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.Scanner; 6 | import java.util.TreeSet; 7 | 8 | public class LineSweep 9 | { 10 | static final double EPS = 1e-9; 11 | 12 | public static void main(String[] args) throws NumberFormatException, IOException 13 | { 14 | Scanner sc = new Scanner(System.in); 15 | TreeSet cands = new TreeSet(); 16 | 17 | int n = sc.nextInt(); 18 | Point[] points = new Point[n]; 19 | for(int i = 0; i < n; i++) 20 | points[i] = new Point(sc.nextInt(), sc.nextInt()); 21 | Arrays.sort(points, new X()); 22 | 23 | double d = 1e9; 24 | for(int i = 0, left = 0; i < points.length; i++) 25 | { 26 | int px = points[i].x, py = points[i].y; 27 | while(left < i && px - points[left].x > d + EPS) cands.remove(points[left++]); 28 | 29 | Point down = new Point(px, py - (int)Math.ceil(d)); 30 | Point up = new Point(px, py + (int)Math.floor(d)); 31 | 32 | for(Point p: cands.subSet(down, up)) 33 | if(p.dist(points[i]) + EPS < d) 34 | d = p.dist(points[i]); //closest pair 35 | cands.add(points[i]); 36 | } 37 | sc.close(); 38 | } 39 | 40 | static class Point implements Comparable 41 | { 42 | int x,y; 43 | 44 | Point(int a, int b) {x = a; y = b;} 45 | 46 | public int compareTo(Point p) { if(y != p.y) return y - p.y; return x - p.x; } 47 | 48 | double dist(Point p) { return Math.sqrt((long)(x - p.x) * (x - p.x) + (long)(y - p.y) * (y - p.y)); } 49 | } 50 | 51 | static class X implements Comparator 52 | { 53 | public int compare(Point o1, Point o2) { if(o1.x != o2.x) return o1.x - o2.x; return o1.y - o2.y; } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /DynamicProgramming/README.md: -------------------------------------------------------------------------------- 1 | # DynamicProgramming(using Java)
2 | 3 | 4 | |Problem's| Solution | 5 | |:---------:|:----------:| 6 | |BoardPath|[BoardPath.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/BoardPath.java)| 7 | |CoinChange|[CoinChange.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/CoinChange.java)| 8 | |EditDistance|[EditDistance.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/EditDistance.java)| 9 | |EggDropping|[EggDropping.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/EggDropping.java)| 10 | |Fibonacci|[Fibonacci.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/Fibonacci.java)| 11 | |FordFulkerson|[FordFulkerson.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/FordFulkerson.java)| 12 | |KadaneAlgorithm|[KadaneAlgorithm.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/KadaneAlgorithm.java)| 13 | |Knapsack|[Knapsack.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/Knapsack.java)| 14 | |SubsetSum|[SubsetSum.java ](https://github.com/Kushal997-das/CODE/blob/master/DynamicProgramming/SubsetSum.java) 15 | |CountNumBinaryStrings|[CountNumBinaryStrings.java](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/CountNumBinaryStrings.java)| 16 | |LongestCommonSubsequence|[LongestCommonSubsequence.java ](https://github.com/Kushal997-das/Competitive-programming-library/blob/master/DynamicProgramming/LongestCommonSubsequence.java)| 17 | -------------------------------------------------------------------------------- /graphs/max_flow/MaxFlow3.java: -------------------------------------------------------------------------------- 1 | package graphs.max_flow; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | //Try to test the implementation with some input of your choice 7 | public class MaxFlow3 { 8 | 9 | static final int INF = (int)1e9; 10 | static int V, s, t, c[][]; //input 11 | 12 | static int pushRelabel() //O(V^3) 13 | { 14 | int[] h = new int[V], e = new int[V], f[] = new int[V][V]; 15 | h[s] = V - 1; 16 | 17 | Queue q = new LinkedList(); 18 | q.add(t); 19 | while(!q.isEmpty()) 20 | { 21 | int u = q.remove(); 22 | for(int v = 0; v < V; ++v) 23 | if(v != t && v != s && h[v] == 0) 24 | { 25 | h[v] = h[u] + 1; 26 | q.add(v); 27 | } 28 | } 29 | 30 | boolean[] isActive = new boolean[V]; 31 | for(int i = 0; i < V; ++i) 32 | { 33 | f[i][s] = -(f[s][i] = e[i] = c[s][i]); 34 | if(i != s && i != t && e[i] > 0) 35 | { 36 | isActive[i] = true; 37 | q.add(i); 38 | } 39 | } 40 | 41 | while(!q.isEmpty()) 42 | { 43 | int u = q.peek(); 44 | boolean pushed = false; 45 | for(int v = 0; v < V && e[u] != 0; ++v) 46 | if(h[u] == h[v] + 1 && c[u][v] - f[u][v] > 0) 47 | { 48 | int df = Math.min(e[u], c[u][v] - f[u][v]); 49 | f[u][v] += df; f[v][u] -= df; 50 | e[u] -= df; e[v] += df; 51 | if(v != s && v != t && !isActive[v]) 52 | { 53 | isActive[v] = true; 54 | q.add(v); 55 | } 56 | pushed = true; 57 | } 58 | 59 | if(e[u] == 0) 60 | { 61 | isActive[u] = false; 62 | q.remove(); 63 | } 64 | 65 | if(!pushed) 66 | { 67 | h[u] = INF; 68 | for(int v = 0; v < V; ++v) 69 | if(h[v] + 1 < h[u] && c[u][v] - f[u][v] > 0) 70 | h[u] = h[v] + 1; 71 | } 72 | } 73 | 74 | return e[t]; 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /graphs/trees/LCA.java: -------------------------------------------------------------------------------- 1 | package graphs.trees; 2 | 3 | import java.util.Arrays; 4 | 5 | /* 6 | * Lowest Common Ancestor in a Rooted Tree 7 | * 8 | * Algorithm 1: Parent Sparse Table 9 | * Algorithm 2: Euler Walk + RMQ 10 | */ 11 | public class LCA { 12 | 13 | /* 14 | * Algorithm 1: Parent Sparse Table 15 | */ 16 | static int N, L[], P[][]; // P[i][j] --> the 2^j th ancestor of node i 17 | 18 | static void preprocessParents(int root, int[] T) // O(n log n) 19 | { 20 | int k = 0; while(1<= 0; --i) 49 | if (L[p] - (1<= L[q]) 50 | p = P[p][i]; 51 | 52 | if (p == q) 53 | return p; 54 | 55 | //go up to lowest (non-common) ancestors for p and q 56 | for (int i = k; i >= 0; --i) 57 | if (P[p][i] != -1 && P[p][i] != P[q][i]) 58 | { 59 | p = P[p][i]; q = P[q][i]; 60 | } 61 | 62 | return P[p][0]; 63 | } 64 | 65 | /* 66 | * Algorithm 2: Euler Walk + RMQ 67 | * ============================= 68 | * 69 | * LCA(u, v) = E[rmq on L (tin[u], tin[v])] 70 | */ 71 | } 72 | -------------------------------------------------------------------------------- /math/number_theory/PrimeFactorization.java: -------------------------------------------------------------------------------- 1 | package math.number_theory; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class PrimeFactorization { 6 | 7 | static ArrayList primes; // generated by sieve 8 | 9 | /* 10 | * 1. Generating a list of prime factors of N 11 | */ 12 | static ArrayList primeFactors(int N) // O(sqrt(N) / ln sqrt(N)) 13 | { 14 | ArrayList factors = new ArrayList(); //take abs(N) in case of -ve integers 15 | int idx = 0, p = primes.get(idx); 16 | 17 | while(p * p <= N) 18 | { 19 | while(N % p == 0) { factors.add(p); N /= p; } 20 | p = primes.get(++idx); 21 | } 22 | 23 | if(N != 1) // last prime factor may be > sqrt(N) 24 | factors.add(N); // for integers whose largest prime factor has a power of 1 25 | return factors; 26 | } 27 | 28 | /* 29 | * 2. Sum of divisors of N 30 | */ 31 | static long sumDiv(int N) 32 | { 33 | int idx = 0, p = primes.get(0); 34 | long ans = 1; 35 | while(p * p <= N) 36 | { 37 | int e = 0; 38 | while(N % p == 0) { N /= p; ++e; } 39 | ans *= (pow(p, e + 1) - 1) / (p - 1); 40 | p = primes.get(++idx); 41 | } 42 | if(N != 1) 43 | ans *= (pow(N, 2) - 1) / (N - 1); 44 | return ans; 45 | } 46 | 47 | /* 48 | * 3. Euler's Totient Function (Number of positive integers < N relatively prime to N) 49 | */ 50 | static int phi(int N) 51 | { 52 | int ans = N, idx = 0, p = primes.get(0); 53 | while(p * p <= N) 54 | { 55 | if(N % p == 0) 56 | ans -= ans / p; 57 | while(N % p == 0) 58 | N /= p; 59 | p = primes.get(++idx); 60 | } 61 | 62 | if(N != 1) 63 | ans -= ans / N; 64 | return ans; 65 | } 66 | 67 | static long pow(long a, int n) 68 | { 69 | long res = 1; 70 | while(n != 0) 71 | { 72 | if((n & 1) == 1) 73 | res *= a; 74 | a *= a; 75 | n >>= 1; 76 | } 77 | return res; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /math/Exponentiation.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | public class Exponentiation { 4 | 5 | /* 6 | * 1. Binary Exponentiation 7 | */ 8 | static int pow(int a, int e) // O(log e) 9 | { 10 | int res = 1; 11 | while(e > 0) 12 | { 13 | if((e & 1) == 1) 14 | res *= a; 15 | a *= a; 16 | e >>= 1; 17 | } 18 | return res; 19 | } 20 | 21 | /* 22 | * 2. Fast Exponentiation 23 | */ 24 | static int modPow(int a, int e, int mod) // O(log e) 25 | { 26 | a %= mod; 27 | int res = 1; 28 | while(e > 0) 29 | { 30 | if((e & 1) == 1) 31 | res = (res * a) % mod; 32 | a = (a * a) % mod; 33 | e >>= 1; 34 | } 35 | return res; 36 | } 37 | 38 | /* 39 | * 3. Matrix Multiplication 40 | */ 41 | static int[][] matMul(int[][] A, int[][] B, int p, int q, int r) //C(p x r) = A(p x q) x (q x r) -- O(p x q x r) 42 | { 43 | int[][] C = new int[p][r]; 44 | for(int i = 0; i < p; ++i) 45 | for(int j = 0; j < r; ++j) 46 | for(int k = 0; k < q; ++k) 47 | C[i][j] += A[i][k] * B[k][j]; 48 | return C; 49 | } 50 | 51 | /* 52 | * 4. Square Matrix Exponentiation 53 | */ 54 | static int[][] matPow(int[][] base, int p) 55 | { 56 | int n = base.length; 57 | int[][] ans = new int[n][n]; 58 | for(int i = 0; i < n; i++) 59 | ans[i][i] = 1; 60 | while(p != 0) 61 | { 62 | if((p & 1) == 1) 63 | ans = matMul(ans, base, n, n, n); 64 | base = matMul(base, base, n, n, n); 65 | p >>= 1; 66 | } 67 | 68 | return ans; 69 | } 70 | 71 | // 5. Power of big numbers 72 | static String powBig(int a, int b) 73 | { 74 | int[] ret = new int[5000]; 75 | ret[4999] = 1; 76 | while(b-->0) 77 | { 78 | int c = 0; 79 | for(int j = 4999; j >= 0; --j) 80 | { 81 | int p = c + a * ret[j]; 82 | c = p/10; 83 | ret[j] = p%10; 84 | 85 | } 86 | } 87 | String s = ""; 88 | for(int i = 0; i < ret.length; ++i) 89 | if(!s.isEmpty() || ret[i] != 0) 90 | s += ret[i]; 91 | return s; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /math/combinatorics/InclusionExclusionPrinciple.java: -------------------------------------------------------------------------------- 1 | package math.combinatorics; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | 6 | public class InclusionExclusionPrinciple { 7 | 8 | /* 9 | * 1. Count the number of numbers in the range [1, r] that are coprime with n 10 | */ 11 | static int countCoprime(int n, int r) // O(sqrt(n)) 12 | { 13 | ArrayList primes = new ArrayList(); 14 | for(int i = 2; i * i <= n; ++i) 15 | if(n%i == 0) 16 | { 17 | primes.add(i); 18 | while(n%i == 0) n /= i; 19 | } 20 | if(n > 1) 21 | primes.add(n); 22 | int sum = 0, size = primes.size(); 23 | for(int msk = 1, end = 1< 1 50 | int[] deg = new int[n + 1]; //deg[i] = # of primes comprising i 51 | 52 | int bad = 0; 53 | for(int i = 2; i <= n; ++i) 54 | { 55 | if(divisor[i]) 56 | { 57 | if(deg[i] == 0) 58 | deg[i] = 1; 59 | for(int j = 1; j * i <= n; ++j) 60 | { 61 | if(j > 1 && deg[i] == 1) 62 | if(j % i == 0) 63 | divisor[i*j] = false; //cross out multiples of squares of primes 64 | else 65 | ++deg[i*j]; 66 | cnt[i*j] += n / i * (deg[i]%2 == 1 ? 1 : -1); 67 | } 68 | } 69 | bad += (cnt[i] - 1) * (n - 1 - cnt[i]); 70 | } 71 | 72 | return (n - 1) * (n - 2) * (n - 3) / 6 - bad / 2; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /math/number_theory/PrimeNumbers.java: -------------------------------------------------------------------------------- 1 | package math.number_theory; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class PrimeNumbers { 6 | 7 | /* 8 | * 1. Sieve of Eratosthenes: generate all primes in [2, N] 9 | */ 10 | static ArrayList primes; 11 | static int[] isComposite; 12 | 13 | static void sieve(int N) // O(N log log N) 14 | { 15 | isComposite = new int[N+1]; 16 | isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number 17 | primes = new ArrayList(); 18 | 19 | for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) 20 | if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance 21 | { 22 | primes.add(i); 23 | if(1l * i * i <= N) 24 | for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve 25 | isComposite[j] = 1; 26 | } 27 | } 28 | 29 | /* 30 | * 2. Primality Test 31 | * 32 | * Preprocessing: call sieve with sqrt(N), O(sqrt(N) log log sqrt(N)) 33 | * Query: best case O(1), worst case O(sqrt(N) / log sqrt(N)) 34 | */ 35 | static boolean isPrime(int N) 36 | { 37 | if(N < isComposite.length) 38 | return isComposite[N] == 0; 39 | for(int p: primes) //may stop if p * p > N 40 | if(N%p==0) 41 | return false; 42 | return true; 43 | } 44 | 45 | /* 46 | * 3. Sieve of Eratostheses in linear time 47 | */ 48 | static void sieveLinear(int N) 49 | { 50 | ArrayList primes = new ArrayList(); 51 | int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i 52 | for(int i = 2; i <= N; ++i) 53 | { 54 | if(lp[i] == 0) 55 | { 56 | primes.add(i); 57 | lp[i] = i; 58 | } 59 | int curLP = lp[i]; 60 | for(int p: primes) 61 | if(p > curLP || p * i > N) 62 | break; 63 | else 64 | lp[p * i] = i; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /DynamicProgramming/BoardPath.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | /* 3 | * this is an important Algo in which 4 | * we have starting and ending of board and we have to reach 5 | * we have to count no. of ways 6 | * that help to reach end point i.e number by rolling dice 7 | * which have 1 to 6 digits 8 | 9 | Test Case: 10 | here target is 10 11 | 12 | int n=10; 13 | startAlgo(); 14 | System.out.println(bpR(0,n)); 15 | System.out.println(endAlgo()+"ms"); 16 | int[] strg=new int [n+1]; 17 | startAlgo(); 18 | System.out.println(bpRS(0,n,strg)); 19 | System.out.println(endAlgo()+"ms"); 20 | startAlgo(); 21 | System.out.println(bpIS(0,n,strg)); 22 | System.out.println(endAlgo()+"ms"); 23 | 24 | 25 | 26 | */ 27 | public class BoardPath { 28 | public static long startTime; 29 | public static long endTime; 30 | public static void startAlgo() { 31 | startTime=System.currentTimeMillis(); 32 | } 33 | public static long endAlgo() { 34 | endTime=System.currentTimeMillis(); 35 | return endTime-startTime; 36 | } 37 | public static int bpR(int start,int end){ 38 | if(start==end) { 39 | return 1; 40 | } 41 | else if(start>end) 42 | return 0; 43 | int count=0; 44 | for(int dice=1;dice<=6;dice++) { 45 | count+=bpR(start+dice,end); 46 | } 47 | return count; 48 | } 49 | public static int bpRS(int curr,int end,int strg[]){ 50 | if(curr==end) { 51 | return 1; 52 | } 53 | else if(curr>end) 54 | return 0; 55 | if(strg[curr]!=0) 56 | return strg[curr]; 57 | int count=0; 58 | for(int dice=1;dice<=6;dice++) { 59 | count+=bpRS(curr+dice,end,strg); 60 | } 61 | strg[curr]=count; 62 | return count; 63 | } 64 | public static int bpIS(int curr,int end,int[]strg){ 65 | strg[end]=1; 66 | for(int i=end-1;i>=0;i--) { 67 | int count=0; 68 | for(int dice=1;dice<=6&&dice+i= S 8 | - finding the window which optimizes an objective function given a fixed length L. 9 | * Example: the window of length L whose sum of elements is minimum 10 | - finding the value of a function for each possible window of a fixed length L. 11 | * Example: the minimum element in each window of length L 12 | 13 | --- 14 | 15 | ## Material Resources 16 | | Resource | Points Covered | 17 | |:------------------------- |:--------------------------------| 18 | | CP Section 9.31 | All | 19 | | [G4G tutorial](https://www.geeksforgeeks.org/window-sliding-technique/)| Extra | 20 | | [Blog](https://www.nayuki.io/page/sliding-window-minimum-maximum-algorithm) | Sliding Window Min Algo | 21 | 22 | --- 23 | ## Problem Sets 24 | ### Problem Set #1 25 | 26 | | Problem | Tags | Notes | Solution | 27 | |:------------- |:-------------|:-----|:--------| 28 | | [Smallest Sub-Array](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2531) | | constraints: K >= 1 | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v115/SmallestSubArray_UVa11536.java) | 29 | | [Subsequence](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3562) | | if no answer print 0 | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v011/Subsequence_UVa1121.java) | 30 | | [They Are Everywhere](http://codeforces.com/contest/701/problem/C) | | | [link](http://codeforces.com/contest/701/submission/21405657) | 31 | | [Subsegments](http://codeforces.com/contest/69/problem/E) | treemaps/sets | | [link](http://codeforces.com/contest/69/submission/20514562) | 32 | | [Largest Square](http://codeforces.com/gym/100008) | 2D Sliding Window | prefix sum on matrices | [link](https://ideone.com/fC81kp) | 33 | -------------------------------------------------------------------------------- /graphs/trees/TreeDiameter.java: -------------------------------------------------------------------------------- 1 | package graphs.trees; 2 | 3 | //1. Calculate the height of the tree rooted at node u for all nodes 4 | //2. find the proper root of a given tree 5 | 6 | import java.util.ArrayList; 7 | import java.util.LinkedList; 8 | import java.util.Queue; 9 | 10 | public class TreeDiameter { 11 | 12 | static ArrayList[] adjList; 13 | static int N, dp_down[][], dp_up[]; 14 | static boolean[] visited; 15 | 16 | //Part 1 17 | static void dfs1(int u) 18 | { 19 | visited[u] = true; 20 | for(int i = 0; i < adjList[u].size(); ++i) 21 | { 22 | int v = adjList[u].get(i); 23 | if(!visited[v]) 24 | { 25 | dfs1(v); 26 | if(dp_down[v][0] + 1> dp_down[u][1]) 27 | dp_down[u][1] = dp_down[v][0] + 1; 28 | if(dp_down[u][1] > dp_down[u][0]) 29 | swap(u); 30 | } 31 | } 32 | } 33 | 34 | static void dfs2(int u, int h) 35 | { 36 | visited[u] = true; 37 | dp_up[u] = h; 38 | for(int i = 0; i < adjList[u].size(); ++i) 39 | { 40 | int v = adjList[u].get(i); 41 | if(!visited[v]) 42 | { 43 | int h_nxt; 44 | if(dp_down[v][0] + 1 == dp_down[u][0]) 45 | h_nxt = dp_down[u][1] + 1; 46 | else 47 | h_nxt = dp_down[u][0] + 1; 48 | dfs2(v, Math.max(h + 1, h_nxt)); 49 | } 50 | } 51 | } 52 | 53 | static void swap(int u) 54 | { 55 | int x = dp_down[u][0], y = dp_down[u][1]; 56 | dp_down[u][0] = y; dp_down[u][1] = x; 57 | } 58 | 59 | static void go() 60 | { 61 | dp_down = new int[N][2]; 62 | dp_up = new int[N]; 63 | visited = new boolean[N]; 64 | dfs1(0); 65 | visited = new boolean[N]; 66 | dfs2(0, 0); 67 | } 68 | 69 | 70 | //Part 2 71 | static int findRoot() 72 | { 73 | int[] deg = new int[N]; 74 | Queue q = new LinkedList(); 75 | for(int i = 0; i < N; ++i) 76 | if((deg[i] = adjList[i].size()) == 1) 77 | q.add(i); 78 | int root = -1; 79 | while(!q.isEmpty()) 80 | { 81 | root = q.remove(); 82 | for(int i = 0; i < adjList[root].size(); ++i) 83 | { 84 | int v = adjList[root].get(i); 85 | if(--deg[v] == 1) 86 | q.add(v); 87 | } 88 | } 89 | return root; 90 | 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /graphs/shortest_path/SSSP.java: -------------------------------------------------------------------------------- 1 | package graphs.shortest_path; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.PriorityQueue; 6 | 7 | /* 8 | * Single-Source Shortest Path 9 | */ 10 | public class SSSP { 11 | 12 | static final int INF = (int)1e9; //don't increase, avoid overflow 13 | static ArrayList[] adjList; 14 | static int V; 15 | 16 | /* 17 | * 1. Dijkstra's Algorithm for SSSP on weighted graphs 18 | */ 19 | static int dijkstra(int S, int T) //O(E log E) 20 | { 21 | int[] dist = new int[V]; 22 | Arrays.fill(dist, INF); 23 | PriorityQueue pq = new PriorityQueue(); 24 | dist[S] = 0; 25 | pq.add(new Edge(S, 0)); //may add more in case of MSSP (Mult-Source) 26 | while(!pq.isEmpty()) 27 | { 28 | Edge cur = pq.remove(); 29 | if(cur.node == T) //remove if all computations are needed 30 | return dist[T]; 31 | if(cur.cost > dist[cur.node]) //lazy deletion 32 | continue; 33 | for(Edge nxt: adjList[cur.node]) 34 | if(cur.cost + nxt.cost < dist[nxt.node]) 35 | pq.add(new Edge(nxt.node, dist[nxt.node] = cur.cost + nxt.cost )); 36 | } 37 | return -1; 38 | } 39 | 40 | /* 41 | * 2. Bellman-Ford's Algorithms for SSSP on weighted graphs with negative cycles 42 | */ 43 | static boolean bellmanFord(int S) 44 | { 45 | int[] dist = new int[V]; 46 | Arrays.fill(dist, INF); 47 | dist[S] = 0; 48 | boolean modified = true; 49 | for(int k = 0; modified && k < V - 1; ++k) 50 | { 51 | modified = false; 52 | for(int u = 0; u < V; ++u) // these two loops run in O(E) in total 53 | for(Edge nxt: adjList[u]) 54 | if(dist[u] + nxt.cost < dist[nxt.node]) 55 | { 56 | modified = true; 57 | dist[nxt.node] = dist[u] + nxt.cost; 58 | } 59 | } 60 | 61 | boolean hasNegCycle = false; 62 | for(int u = 0; u < V; ++u) 63 | for(Edge nxt: adjList[u]) 64 | if(dist[u] + nxt.cost < dist[nxt.node]) 65 | hasNegCycle = true; 66 | return hasNegCycle; 67 | } 68 | 69 | static class Edge implements Comparable 70 | { 71 | int node, cost; 72 | 73 | Edge(int a, int b) { node = a; cost = b; } 74 | 75 | public int compareTo(Edge e){ return cost - e.cost; } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /other_algorithms/LIS.java: -------------------------------------------------------------------------------- 1 | package other_algorithms; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Stack; 6 | 7 | /* 8 | * Longest Increasing Subsequence - O(n log n) solution 9 | * 10 | * Main Variables 11 | * ============== 12 | * - A is the original array containing elements for which we need to find LIS 13 | * - L is built incrementaly, L[i] contains the smallest value (A[j] for some j) 14 | * that is an end for an increasing subsequence of length i + 1 15 | * - lis is the answer (length of the longest increasing subsequence in A) 16 | * 17 | * Printing the Solution Variables 18 | * =============================== 19 | * - lis_end is the index of an element in A which is the last element in LIS 20 | * i.e. LIS = { X1, X2, X3, ...., A[lis_end] } 21 | * 22 | * - P contains parents of every element in A for the LIS ending at that element 23 | * i.e. LIS_ending_at_x = { ........, A[P[P[x]]], A[P[x]], A[x] } 24 | * 25 | * - L_id maps every value in L to its index in A 26 | * i.e. L_id[3] = index in A which is at index 3 in L 27 | * Consequently, it is the index in A of the last element of an increasing subsequence of length 4 28 | * 29 | */ 30 | class LIS { 31 | 32 | static Stack stack; //contains the last solution in increasing order 33 | 34 | static int lis(int[] A, int n) // Can be implemented with TreeSet (lower, remove, add) 35 | { 36 | ArrayList L = new ArrayList(); 37 | int[] P = new int[n]; 38 | int[] L_id = new int[n]; 39 | 40 | int lis = 0, lis_end = -1; 41 | for(int i = 0; i < n; ++i) 42 | { 43 | int pos = Collections.binarySearch(L, A[i]); 44 | if (pos < 0) pos = -(pos + 1); 45 | 46 | if(pos >= L.size()) L.add(A[i]); 47 | else L.set(pos, A[i]); 48 | 49 | if(pos + 1 > lis) 50 | { 51 | lis = pos + 1; 52 | lis_end = i; 53 | } 54 | 55 | //lis_end and the following part for printing the solution 56 | L_id[pos] = i; 57 | P[i] = pos > 0 ? L_id[pos-1] : -1; 58 | } 59 | 60 | stack = new Stack(); 61 | while(lis_end != -1) 62 | { 63 | stack.push(A[lis_end]); 64 | lis_end = P[lis_end]; 65 | } 66 | return lis; 67 | } 68 | } 69 | 70 | -------------------------------------------------------------------------------- /add del link list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long 4 | 5 | class node 6 | { 7 | public: 8 | int data; 9 | node *next; 10 | }; 11 | 12 | void add_node(node ** head,int n) //inserts at the front 13 | { 14 | node *temp=new node; 15 | temp->data=n; 16 | temp->next=*head; 17 | *head=temp; 18 | } 19 | void add(node ** head,int n) 20 | { 21 | node *temp=new node(); 22 | node *l=*head; 23 | temp->data=n; 24 | temp->next=NULL; 25 | if(*head==NULL) 26 | { 27 | *head=temp; 28 | } 29 | else 30 | { 31 | while(l->next!=NULL) 32 | { 33 | l=l->next; 34 | } 35 | l->next=temp; 36 | } 37 | } 38 | void display(node ** k) 39 | { 40 | while((*k)!=NULL) 41 | { 42 | cout<<(*k)->data<<" "; 43 | (*k)=(*k)->next; 44 | } 45 | } 46 | void delfront(node **head) 47 | { 48 | if(*head==NULL) 49 | cout<<"Nothing to delete \n"; 50 | else 51 | (*head) = (*head)->next; 52 | } 53 | void delend(node **head) 54 | { 55 | if(*head==NULL) 56 | cout<<"Nothing to delete\n"; 57 | else 58 | { 59 | if((*head)->next==NULL) 60 | delete(*head); 61 | node *second = *head; 62 | while(second->next->next!=NULL) 63 | { 64 | second = second->next; 65 | } 66 | delete(second->next); 67 | second->next = NULL; 68 | } 69 | } 70 | int main() 71 | { 72 | node *head=NULL; 73 | int i,n; 74 | cin>>n; 75 | for(i=0;i>y; 80 | if(y==1 || y==2) 81 | { 82 | cout<<"Enter the number to be inserted"<>x; 84 | if(y==1) 85 | { 86 | add_node(&head,x); //insertion from front 87 | } 88 | 89 | else if(y==2) //insertion from end 90 | { 91 | add(&head, x); 92 | } 93 | } 94 | else 95 | { 96 | if(y==3) //deletion from front 97 | { 98 | delfront(&head); 99 | } 100 | else if(y==4) //deletion from end 101 | { 102 | delend(&head); 103 | } 104 | } 105 | } 106 | cout<<"The final linked list is"<> 6 | { 7 | 8 | class Node 9 | { 10 | Node next, down; 11 | int level; 12 | T value; 13 | 14 | public Node(T v, int l, Node n, Node d) 15 | { 16 | value = v; 17 | level = l; 18 | next = n; 19 | down = d; 20 | } 21 | } 22 | 23 | Node head; 24 | Random rand; 25 | 26 | final static double p = 0.5; 27 | 28 | public SkipList() 29 | { 30 | head = new Node(null, 0, null, null); 31 | rand = new Random(); 32 | } 33 | 34 | public int getRandomLevel() 35 | { 36 | int level = 0; 37 | while(level <= head.level && rand.nextDouble() < 0.5) 38 | level++; 39 | return level; 40 | } 41 | 42 | public boolean add(T v) 43 | { 44 | if (search(v)) 45 | return false; 46 | 47 | int lev = getRandomLevel(); 48 | if (lev > head.level) 49 | head = new Node(null, lev, null, head); 50 | 51 | Node cur = head, bottom = null; 52 | while(cur != null) 53 | { 54 | Node next = cur.next; 55 | if (next == null || next.value.compareTo(v) > 0) 56 | { 57 | if (cur.level <= lev) 58 | { 59 | Node nn = new Node(v, cur.level, next, null); 60 | cur.next = nn; 61 | if (bottom != null) 62 | bottom.down = nn; 63 | bottom = nn; 64 | } 65 | cur = cur.down; 66 | } 67 | else 68 | cur = cur.next; 69 | 70 | } 71 | return true; 72 | } 73 | 74 | public boolean search(T key) 75 | { 76 | Node cur = head; 77 | while(cur != null) 78 | { 79 | if (cur.value != null && cur.value.compareTo(key) == 0) 80 | return true; 81 | 82 | Node next = cur.next; 83 | if (next == null || next.value.compareTo(key) > 0) 84 | cur = cur.down; 85 | else 86 | cur = cur.next; 87 | } 88 | return false; 89 | } 90 | 91 | public void print() 92 | { 93 | Node h = head; 94 | while(h != null) 95 | { 96 | Node c = h; 97 | while(c != null) {System.out.print(c.value + ", ");c = c.next;} 98 | System.out.println(); 99 | h = h.down; 100 | } 101 | } 102 | 103 | } 104 | 105 | -------------------------------------------------------------------------------- /geometry/Circle.java: -------------------------------------------------------------------------------- 1 | package geometry; 2 | 3 | public class Circle { //equation: (x-c.x)^2 + (y-c.y)^2 = r^2 4 | 5 | static final double EPS = 1e-9; 6 | 7 | Point c; 8 | double r; 9 | 10 | Circle(Point p, double k) { c = p; r = k; } 11 | 12 | int inside(Point p) //1 for inside, 0 for border, -1 for outside 13 | { 14 | double d = p.dist(c); 15 | 16 | return d + EPS < r ? 1 : Math.abs(d - r) < EPS ? 0 : -1; 17 | } 18 | 19 | double circum() { return 2 * Math.PI * r; } 20 | 21 | double area() { return Math.PI * r * r; } 22 | 23 | double arcLength(double deg) { return deg / 360.0 * circum(); } //major and minor chords exist 24 | 25 | double chordLength(double deg) 26 | { 27 | return 2 * r * Math.sin(Geometry.degToRad(deg) / 2.0); 28 | } 29 | 30 | double sectorArea(double deg) { return deg / 360.0 * area(); } 31 | 32 | double segmentArea(double deg) 33 | { 34 | return sectorArea(deg) - r * r * Math.sin(Geometry.degToRad(deg)) / 2.0; 35 | } 36 | 37 | boolean intersect(Circle cir) 38 | { 39 | return c.dist(cir.c) <= r + cir.r + EPS && c.dist(cir.c) + EPS >= Math.abs(r - cir.r); 40 | } 41 | //returns true if the circle intersects with the line segment defined by p and q at one or two points 42 | boolean intersect(Point p, Point q) 43 | { 44 | Line l = new Line(p, q); 45 | if(Math.abs(l.b) < EPS) 46 | { 47 | if(l.c * l.c > r * r + EPS) 48 | return false; 49 | 50 | double y1 = Math.sqrt(Math.abs(r * r - l.c * l.c)), y2 = -y1; 51 | return new Point(-l.c, y1).between(p, q) && new Point(-l.c, y2).between(p, q); 52 | } 53 | double a = l.a * l.a + 1, b = 2 * l.a * l.c, c = l.c * l.c - r * r; 54 | if(b * b - 4 * a * c + EPS < 0) 55 | return false; 56 | 57 | double dis = b * b - 4 * a * c; 58 | 59 | double x1 = (-b + Math.sqrt(dis)) / (2.0 * a), x2 = (-b - Math.sqrt(dis)) / (2.0 * a); 60 | 61 | return new Point(x1, - l.a * x1 - l.c).between(p, q) || new Point(x2, - l.a * x2 - l.c).between(p, q); 62 | } 63 | 64 | static Point findCenter(Point p, Point q, double r) //for the other center, swap p and q 65 | { 66 | double d2 = (p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y); 67 | double det = r * r / d2 - 0.25; 68 | if(Math.abs(det) < EPS) 69 | det = 0.0; 70 | if(det < 0.0) 71 | return null; 72 | double h = Math.sqrt(det); 73 | return new Point((p.x + q.x) / 2.0 + (p.y - q.y) * h, (p.y + q.y) / 2.0 + (q.x - p.x) * h); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /curriculum/readme.md: -------------------------------------------------------------------------------- 1 | # ACM Curriculum 2 | 3 | This is a training plan for anyone who wants to excel in competitive programming regardless of their knowledge and experience. 4 | The plan is currently under development and being tested by the GUC ACM community. This plan is meant to be sufficient for 5 | anyone. Some communities may offer sessions to explain topics. However, links will be provided for online material. If you want 6 | to contribute to the plan to improve it, you can send me an email. 7 | 8 | We will divide ACMers into three different levels (inspired by Codeforces): 9 | 10 | - **[Pupil](https://github.com/AhmadElsagheer/Competitive-programming-library/blob/master/curriculum/pupil-plan.md)**: beginner with no prior knowledge or experience in competitive programming. The target of this plan to be able to solve 11 | CF-div2 AB(C) 12 | 13 | - **[Specialist](https://github.com/AhmadElsagheer/Competitive-programming-library/blob/master/curriculum/specialist-plan.md)**: has basic knowledge in most of the topics and good implementation skills. The target of this plan to be able to solve 14 | CF-div2 ABC(D) 15 | 16 | - **[Expert](https://github.com/AhmadElsagheer/Competitive-programming-library/blob/master/curriculum/expert-plan.md)**: masters basic algorithms/data structures and has good knowledge in most of the topics. The target of this plan to be able to solve 17 | CF-div2 ABCDE 18 | 19 | Problems without brackets should be solved regardless of their difficulty. Problems with brackets should be solved if they are 20 | the easy or medium ones. 21 | 22 | Let's define our own units, so the plan seems reasonable and fits our schedules. An acm day is a day at which you do nothing but practice, 23 | typically spending 16 hours in practice and sleeping/eating/doing other stuff in 8 hours. For sure, this is not reasonable for our daily lives, 24 | but we need to define such a day as it is suitable for feeling progressive. We will use this definition of day in the plan, however, it depends 25 | how it will be interpreted ([extreme] 1-4 [amateur] normal days). 26 | 27 | Attached with each plan, there will be a google spreadsheet. As you benefit from this plan, it would be nice if you can help others 28 | benefit from this plan. So, you can request access to the spreadsheet and a column will be assigned to you to fill with the time you spent on solving problems and finishing the reading tasks to make good estimates for the plan. 29 | -------------------------------------------------------------------------------- /graphs/traversal/BiconnectedComponents.java: -------------------------------------------------------------------------------- 1 | package graphs.traversal; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | import java.util.Stack; 6 | 7 | /* 8 | * Biconnected Components 9 | */ 10 | public class BiconnectedComponents { 11 | 12 | static ArrayList[] adjList, inBiComp; 13 | static int[] dfs_low, dfs_num; 14 | static int V, counter, biCompIdx; 15 | static Stack stack; 16 | static ArrayList> biconnectedComponents; 17 | 18 | static void biConnectedComponents() //O(V + E) 19 | { 20 | for(int i = 0; i < V; ++i) 21 | if(dfs_num[i] == 0) 22 | dfs(i, -1); 23 | } 24 | 25 | static void dfs(int u, int p) 26 | { 27 | dfs_num[u] = dfs_low[u] = ++counter; 28 | stack.push(u); 29 | for(int v: adjList[u]) 30 | if(v != p) 31 | if(dfs_num[v] == 0) 32 | { 33 | dfs(v, u); 34 | dfs_low[u] = Math.min(dfs_low[v], dfs_low[u]); 35 | if(dfs_low[v] >= dfs_num[u]) 36 | { 37 | ArrayList component = new ArrayList(); 38 | while(true) 39 | { 40 | int w = stack.pop(); 41 | component.add(w); 42 | inBiComp[w].add(biCompIdx); 43 | if(w == v) 44 | break; 45 | } 46 | component.add(u); 47 | inBiComp[u].add(biCompIdx); 48 | biconnectedComponents.add(component); 49 | ++biCompIdx; 50 | } 51 | } 52 | else 53 | dfs_low[u] = Math.min(dfs_low[u], dfs_num[v]); 54 | } 55 | 56 | static void go() 57 | { 58 | dfs_low = new int[V]; 59 | dfs_num = new int[V]; 60 | stack = new Stack(); 61 | biconnectedComponents = new ArrayList>(); 62 | inBiComp = new ArrayList[V]; 63 | for(int i = 0; i < V; ++i) 64 | inBiComp[i] = new ArrayList(); 65 | 66 | biConnectedComponents(); 67 | 68 | for(ArrayList x : biconnectedComponents) 69 | System.out.println(x); 70 | } 71 | 72 | public static void main(String[] args) 73 | { 74 | Scanner sc = new Scanner(System.in); 75 | 76 | V = sc.nextInt(); 77 | adjList = new ArrayList[V]; 78 | for(int i = 0; i < V; ++i) 79 | adjList[i] = new ArrayList(); 80 | int m = sc.nextInt(); 81 | while(m-->0) 82 | { 83 | int u = sc.nextInt(), v = sc.nextInt(); 84 | adjList[u].add(v); 85 | adjList[v].add(u); 86 | } 87 | 88 | go(); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /DynamicProgramming/CountNumBinaryStrings.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | /* 3 | * here is a important algo in this we have to count 4 | * maximum no. of different binary strings which doesnot have 5 | * consectuive 1s 6 | 7 | 8 | 9 | Test Case: 10 | 11 | int n=30; 12 | 13 | startAlgo(); 14 | System.out.println(numStrIS(n)); 15 | System.out.println(endAlgo()+"ms"); 16 | 17 | startAlgo(); 18 | CountNumBinaryStr out=new CountNumBinaryStr(); 19 | System.out.println(out.numStrR(n).ans); 20 | System.out.println(endAlgo()+"ms"); 21 | 22 | startAlgo(); 23 | System.out.println(countStrings(n,0)); 24 | System.out.println(endAlgo()+"ms"); 25 | 26 | 27 | 28 | */ 29 | public class CountNumBinaryStr { 30 | public static long startTime; 31 | public static long endTime; 32 | public static void startAlgo() { 33 | startTime=System.currentTimeMillis(); 34 | } 35 | public static long endAlgo() { 36 | endTime=System.currentTimeMillis(); 37 | return endTime-startTime; 38 | } 39 | public static int numStrIS(int n) { 40 | int[] zeros=new int[n]; 41 | int []ones=new int[n]; 42 | //seed 43 | zeros[0]=1; 44 | ones[0]=1; 45 | for(int i=1;i[] adjList; 20 | 21 | 22 | static void findWinner() 23 | { 24 | //'P' (police), 'T' (thief), '.' (empty), '#' (wall), 'E' (exit) 25 | 26 | for(int turn = 0; turn < 2; ++ turn) 27 | for(int p = 0; p < R * C; ++p) 28 | for(int t = 0; t < R * C; ++t) 29 | { 30 | int px = p / C, py = p % C, tx = t / C, ty = t % C; 31 | if(grid[px][py] == '*' || grid[tx][ty] == '*') 32 | continue; 33 | int state = mapState(p, t, turn); 34 | // Add winning and losing positions 35 | if(turn == POLICE) 36 | { 37 | win[state] = p == t; 38 | lose[state] = !win[state] && grid[tx][ty] == 'E'; 39 | } 40 | else 41 | { 42 | win[state] = grid[tx][ty] == 'E'; 43 | lose[state] = !win[state] && p == t; 44 | } 45 | 46 | if(win[state] || lose[state]) 47 | continue; 48 | 49 | // Add an edge for skipping move 50 | int nxtState = mapState(p, t, turn ^ 1); 51 | adjList[nxtState].add(state); 52 | deg[state] = 1; 53 | 54 | // Add edges for other moves 55 | int pk = turn == POLICE ? 1 : 0; 56 | int tk = turn == THIEF ? 1 : 0; 57 | for(int k = 1, end = turn == POLICE ? 8 : 4; k <= end; ++k) 58 | { 59 | 60 | int ppx = px + dx[k * pk], ppy = py + dy[k * pk]; 61 | int ttx = tx + dx[k * tk], tty = ty + dy[k * tk]; 62 | if(valid(ppx, ppy) && valid(ttx, tty)) 63 | { 64 | nxtState = mapState(ppx * C + ppy, ttx * C + tty, turn ^ 1); 65 | adjList[nxtState].add(state); 66 | ++deg[state]; 67 | } 68 | } 69 | } 70 | 71 | 72 | 73 | /* 74 | * run the algorithm (GamesOnGeneralGraphs) and check the state 75 | * (px, py, tx, ty, POLICE) 76 | */ 77 | } 78 | 79 | static boolean valid(int x, int y) { return x >= 0 && y >= 0 && x < R && y < C && grid[x][y] != '#'; } 80 | 81 | static int mapState(int p, int t, int turn) { return (p * R * C + t) * 2 + turn; } 82 | } 83 | -------------------------------------------------------------------------------- /geometry/Triangle.java: -------------------------------------------------------------------------------- 1 | package geometry; 2 | 3 | public class Triangle { 4 | 5 | static final double EPS = 1e-9; 6 | 7 | Point a, b, c; 8 | double ab, bc, ca; 9 | 10 | Triangle(Point p, Point q, Point r) //counter clockwise 11 | { 12 | a = p; 13 | if(Point.ccw(p, q, r)) { b = q; c = r; } 14 | else { b = r; c = q; } 15 | 16 | ab = a.dist(b); bc = b.dist(c); ca = c.dist(a); 17 | } 18 | 19 | double perm() 20 | { 21 | return ab + bc + ca; 22 | } 23 | 24 | double area() 25 | { 26 | double s = (ab + bc + ca) / 2.0; 27 | return Math.sqrt(s * (s - ab) * (s - bc) * (s - ca)); //take care of overflow 28 | } 29 | 30 | double area2() 31 | { return Math.abs(a.x * b.y - a.y * b.x + b.x * c.y - b.y * c.x + c.x * a.y - c.y * a.x) / 2.0; } 32 | /* 33 | * 1. We take the absolute value because the result could be negative which means that point q is on 34 | * the left of the line segment pr 35 | * 36 | * 2. If the area is zero, then the three points are collinear 37 | */ 38 | 39 | double area3() 40 | { 41 | return 0.5 * ((c.y - a.y) * (b.x - a.x) - (b.y - a.y) * (c.x - a.x)); 42 | } 43 | 44 | double rInCircle() 45 | { 46 | return area() / (perm() * 0.5); 47 | } 48 | 49 | Point inCenter() //intersection of the angle bisectors, center of inscribed circle 50 | { 51 | double p = perm(); 52 | double x = (a.x * bc + b.x * ca + c.x * ab) / p; 53 | double y = (a.y * bc + b.y * ca + c.y * ab) / p; 54 | return new Point(x, y); 55 | } 56 | 57 | double rCircumCircle() 58 | { 59 | return ab * bc * ca / (4.0 * area()); 60 | } 61 | 62 | Point circumCircle() 63 | { 64 | double bax = b.x - a.x, bay = b.y - a.y; 65 | double cax = c.x - a.x, cay = c.y - a.y; 66 | 67 | double e = bax * (a.x + b.x) + bay * (a.y + b.y); 68 | double f = cax * (a.x + c.x) + cay * (a.y + c.y); 69 | double g = 2.0 * (bax * (c.y - b.y) - bay * (c.x - b.x)); 70 | 71 | if (Math.abs(g) < EPS) return null; 72 | 73 | return new Point((cay*e - bay*f) / g, (bax*f - cax*e) / g); 74 | 75 | } 76 | 77 | static double areaMedians(double ma, double mb, double mc) //medians of the triangle 78 | { 79 | double s = (ma + mb + mc) / 2.0; //max(ma, mb, mc) < s 80 | return Math.sqrt(s * (s - ma) * (s - mb) * (s - mc)) * 4.0 / 3.0; 81 | } 82 | 83 | static double areaHeights(double ha, double hb, double hc) //heights of the triangle 84 | { 85 | double ha_1 = 1.0 / ha, hb_1 = 1.0 / hb, hc_1 = 1.0 / hc; 86 | double s = (ha_1 + hb_1 + hc_1) / 2.0; 87 | return 1.0 / (Math.sqrt(s * (s - ha_1) * (s - hb_1) * (s - hc_1)) * 4.0); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /DynamicProgramming/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | class LongestCommonSubsequence { 4 | 5 | public static String getLCS(String str1, String str2) { 6 | 7 | //At least one string is null 8 | if (str1 == null || str2 == null) 9 | return null; 10 | 11 | //At least one string is empty 12 | if (str1.length() == 0 || str2.length() == 0) 13 | return ""; 14 | 15 | String[] arr1 = str1.split(""); 16 | String[] arr2 = str2.split(""); 17 | 18 | //lcsMatrix[i][j] = LCS of first i elements of arr1 and first j characters of arr2 19 | int[][] lcsMatrix = new int[arr1.length + 1][arr2.length + 1]; 20 | 21 | for (int i = 0; i < arr1.length + 1; i++) 22 | lcsMatrix[i][0] = 0; 23 | for (int j = 1; j < arr2.length + 1; j++) 24 | lcsMatrix[0][j] = 0; 25 | for (int i = 1; i < arr1.length + 1; i++) { 26 | for (int j = 1; j < arr2.length + 1; j++) { 27 | if (arr1[i - 1].equals(arr2[j - 1])) { 28 | lcsMatrix[i][j] = lcsMatrix[i - 1][j - 1] + 1; 29 | } else { 30 | lcsMatrix[i][j] = lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1] ? lcsMatrix[i - 1][j] : lcsMatrix[i][j - 1]; 31 | } 32 | } 33 | } 34 | return lcsString(str1, str2, lcsMatrix); 35 | } 36 | 37 | public static String lcsString(String str1, String str2, int[][] lcsMatrix) { 38 | StringBuilder lcs = new StringBuilder(); 39 | int i = str1.length(), 40 | j = str2.length(); 41 | while (i > 0 && j > 0) { 42 | if (str1.charAt(i - 1) == str2.charAt(j - 1)) { 43 | lcs.append(str1.charAt(i - 1)); 44 | i--; 45 | j--; 46 | } else if (lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1]) { 47 | i--; 48 | } else { 49 | j--; 50 | } 51 | } 52 | return lcs.reverse().toString(); 53 | } 54 | 55 | public static void main(String[] args) { 56 | String str1 = "DSGSHSRGSRHTRD"; 57 | String str2 = "DATRGAGTSHS"; 58 | String lcs = getLCS(str1, str2); 59 | 60 | //Print LCS 61 | if (lcs != null) { 62 | System.out.println("String 1: " + str1); 63 | System.out.println("String 2: " + str2); 64 | System.out.println("LCS: " + lcs); 65 | System.out.println("LCS length: " + lcs.length()); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /graphs/traversal/articulation-points-and-bridges.md: -------------------------------------------------------------------------------- 1 | ### Articulation Points and Bridges 2 | 3 | (Supplement Material for CP3 section 4.2.8) 4 | 5 | To understand why the algorithm for articulation points and bridges work, you must get 3 concepts clearly. 6 | 7 | ##### DFS Spanning Tree 8 | 9 | Any graph can be converted to a DFS spanning tree which is a tree with two types of directed edges: 10 | 11 | 1. Tree edges: edges from _u_ to one of its children _v_. _u_ is visited before _v_ and _u_ is the direct parent of _v_. 12 | 2. Back edges: edges from _u_ to one of its ancestors _v_. _v_ is visited before _u_. 13 | 14 | A graph may have many different DFS spanning trees. To construct any of them, pick an arbitrary node and visit 15 | all the nodes one by one: 16 | 17 | - When the edge leads from EXPLORED node to UNVISITED node, then this edge is a tree edge. 18 | - When the edge leads from EXPLORED node to EXPLORED node, then this edge is a back edge. 19 | 20 | We only take tree edges while building the tree. Back edges are not taken. 21 | 22 | ##### DFS Num 23 | Every time we visit a node for the first time, we will assign to it a number _dfsNum_ which is the time at which we 24 | visited this node. Values for _dfsNum_ will range from 1 to _N_. We can use value 0 for initialization to represent 25 | unvisited nodes. 26 | 27 | Note that for each node, all its descendants have larger values for _dfsNum_ while all its anscestors has smaller values. 28 | 29 | ##### DFS Low 30 | For each node _u_, we want to know what is node with the lowest time this node can reach either through: 31 | 32 | - back edges from _u_. 33 | - any node in the subtree of _u_. If _v_ is in the subtree of _u_, then all nodes reachable from _v_ are also reachable from _u_. 34 | 35 | Let's call this lowest time for _u_ as _dfsLow[u]_ and it is initially equal to _dfsNum[u]_. Then it can be minimized using two ways: 36 | 37 | - For a back edge from _u_ to _v_, then it is minimized using _dfsNum[v]_. 38 | - For a tree edge from _u_ to _v_, then it is minimized using _dfsLow[v]_. 39 | 40 | ### How to find articulation points ? 41 | For node _u_, if there exists a child _v_ such that _dfsNum[u] <= dfsLow[v]_, then _v_ cannot visit nodes with time less than 42 | _dfsNum[u]_ if _u_ is removed from the graph. In this case, _u_ is an articulation point. 43 | 44 | Note that there is a special case when _u_ is the root of the tree. 45 | 46 | ### How to find bridges ? 47 | For node _u_, if there exists a child _v_ such that _dfsNum[u] < dfsLow[v]_, then _v_ cannot visit _u_ if the edge from 48 | _u_ -> _v_ is removed from the graph. In this case, edge _u_ -> _v_ is a bridge. 49 | 50 | -------------------------------------------------------------------------------- /curriculum/expert-plan.md: -------------------------------------------------------------------------------- 1 | # Expert Plan 2 | 3 | Duration: xx acm days 4 | 5 | Practice Style: 6 | - new topics . 7 | - medium problems on topics in pupil/specialist plan or topics discussed earlier in the current plan. 8 | - hard problems on topics with awesome new ideas and solutions. 9 | 10 | ### Content 11 | 12 | - Problem-Solving Paradigms 13 | - More on greedy 14 | - Huffman Codes 15 | - Bracket Matching 16 | - DP Speed-ups and tricks 17 | - Sliding Window 18 | - Data Structures 19 | - Sqrt Decomposition 20 | - Balanced BST 21 | - Randomized Heaps 22 | -Graphs 23 | - Biconnected Components and Block-cut tree 24 | - Centroid Decomposition 25 | - Bridge Tree 26 | - Minimum Cost Max Flow 27 | - Minimum Path Cover 28 | - Hungarian Algorithm 29 | - Mathematics 30 | - Combinatorics 31 | - Burnside's Lemma 32 | - Probability Theory 33 | - Game Theory 34 | - Decision trees and Min-max Strategy 35 | - Sprague-Grundy Theorem 36 | - Games on General Graphs 37 | - Cycle Finding 38 | - Numerical Methods 39 | - Newton's Method 40 | - Ruffini–Horner's method 41 | - Others 42 | - Canonical Form 43 | - Factorial Number System 44 | - String Processing 45 | - Hashing 46 | - Manacher's Algorithm 47 | - Aho-Corasick 48 | - Suffix Structures (tree/array/automaton) 49 | - Geometry 50 | - Maximum Triangle Area 51 | - Rare Topics 52 | - Composite Problems 53 | 54 | ### Notes 55 | - To find the problems: 56 | - For CF problems, if problem is 71A, then it's link will be "http://codeforces.com/problemset/problem/71/A". 57 | - For UVa problems, just google "UVA [problem id]" and you will get links for the problem. Make sure that the same id appears in the problem page written before the problem name. 58 | - - For extra problems about the mentioned topics, check CP or [problems sheet](https://docs.google.com/spreadsheets/d/1blSbPr1pAFZSzlAi2IVdTeytz2yO7Ejx9SeQWOSxY0w). 59 | 60 | - Resources: 61 | - CP is [Competitive Programming 3](https://cpbook.net/). 62 | - CLRS is [Introduction to Algorithms](https://mitpress.mit.edu/books/introduction-algorithms). 63 | - For extra resources, check [awesome-list](https://github.com/lnishan/awesome-competitive-programming) or [topics sheet](https://docs.google.com/spreadsheets/d/1tLEm58_2bQgM7qhATSjN0fGbdLLtaOCjUFnTGniHbjI). 64 | 65 | - Solutions and hints: 66 | - For CF problems, you can see other accepted submissions. 67 | - For UVa problems, check [this repo](https://github.com/AhmadElsagheer/UVa-Solutions) or google it. 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /DynamicProgramming/FordFulkerson.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | import java.util.Vector; 6 | 7 | public class FordFulkerson { 8 | final static int INF = 987654321; 9 | // edges 10 | static int V; 11 | static int[][] capacity, flow; 12 | 13 | public static void main(String[] args) { 14 | System.out.println("V : 6"); 15 | V = 6; 16 | capacity = new int[V][V]; 17 | 18 | capacity[0][1] = 12; 19 | capacity[0][3] = 13; 20 | capacity[1][2] = 10; 21 | capacity[2][3] = 13; 22 | capacity[2][4] = 3; 23 | capacity[2][5] = 15; 24 | capacity[3][2] = 7; 25 | capacity[3][4] = 15; 26 | capacity[4][5] = 17; 27 | 28 | System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5)); 29 | } 30 | 31 | private static int networkFlow(int source, int sink) { 32 | flow = new int[V][V]; 33 | int totalFlow = 0; 34 | while (true) { 35 | Vector parent = new Vector<>(V); 36 | for (int i = 0; i < V; i++) 37 | parent.add(-1); 38 | Queue q = new LinkedList<>(); 39 | parent.set(source, source); 40 | q.add(source); 41 | while (!q.isEmpty() && parent.get(sink) == -1) { 42 | int here = q.peek(); 43 | q.poll(); 44 | for (int there = 0; there < V; ++there) 45 | if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) { 46 | q.add(there); 47 | parent.set(there, here); 48 | } 49 | } 50 | if (parent.get(sink) == -1) 51 | break; 52 | 53 | int amount = INF; 54 | String printer = "path : "; 55 | StringBuilder sb = new StringBuilder(); 56 | for (int p = sink; p != source; p = parent.get(p)) { 57 | amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount); 58 | sb.append(p + "-"); 59 | } 60 | sb.append(source); 61 | for (int p = sink; p != source; p = parent.get(p)) { 62 | flow[parent.get(p)][p] += amount; 63 | flow[p][parent.get(p)] -= amount; 64 | } 65 | totalFlow += amount; 66 | printer += sb.reverse() + " / max flow : " + totalFlow; 67 | System.out.println(printer); 68 | } 69 | 70 | return totalFlow; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /math/Permutations.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | 6 | public class Permutations { 7 | 8 | /* 9 | * 1. Compute Next Permutation 10 | */ 11 | static boolean nextPermutation(char[] c) 12 | { 13 | // 1. finds the largest k, that c[k] < c[k+1] 14 | int first = getFirst(c); 15 | if(first == -1) 16 | return false; 17 | 18 | // 2. find last index toSwap, that c[k] < c[toSwap] 19 | int toSwap = c.length - 1; 20 | while (c[first] >= c[toSwap]) 21 | --toSwap; 22 | 23 | // 3. swap elements with indexes first and last 24 | swap(c, first++, toSwap); 25 | 26 | // 4. reverse sequence from k+1 to n (inclusive) 27 | toSwap = c.length - 1; 28 | while(first < toSwap) 29 | swap(c, first++, toSwap--); 30 | return true; 31 | } 32 | 33 | // finds the largest k, that c[k] < c[k+1] 34 | // if no such k exists (there is not greater permutation), return -1 35 | static int getFirst(char[] c) 36 | { 37 | for ( int i = c.length - 2; i >= 0; i--) 38 | if (c[i] < c[i + 1]) 39 | return i; 40 | return -1; 41 | } 42 | 43 | 44 | static void swap(char[] c,int i, int j) 45 | { 46 | char tmp = c[i]; 47 | c[i] = c[j]; 48 | c[j] = tmp; 49 | } 50 | 51 | 52 | /* 53 | * 2. Find Kth permutation (0-based, lexiographically, no duplicates) 54 | */ 55 | static char[] kthPermutation1(char[] s, int k) //O(n^2) where n = s.length 56 | { 57 | ArrayList rem = new ArrayList(); 58 | for(char c: s) 59 | rem.add(c); 60 | Collections.sort(rem); 61 | int[] facNum = new int[s.length]; 62 | for(int i = 1; i <= s.length; k /= i++) 63 | facNum[s.length - i] = k % i; 64 | 65 | char[] ret = new char[s.length]; 66 | for(int i = 0; i < s.length; ++i) 67 | { 68 | ret[i] = rem.get(facNum[i]); 69 | rem.remove(facNum[i]); 70 | } 71 | return ret; 72 | } 73 | 74 | /* 75 | * 3. Find Kth permutation (0-based, lexiographically, duplicates handled) 76 | */ 77 | static char[] kthPermutation2(char[] s, int k) //O(n * m) where n = s.length, m = alphabet size 78 | { 79 | int n = s.length; 80 | int[] f = new int[26]; 81 | for(char c: s) 82 | f[c-'a']++; 83 | 84 | int[] facNum = new int[n]; 85 | for(int i = 1; i <= n; k /= i++) 86 | facNum[n - i] = k % i; 87 | 88 | char[] ret = new char[n]; 89 | for(int i = 0; i < n; ++i) 90 | { 91 | int z = facNum[i]; 92 | for(int j = 0; j < 26; ++j) 93 | if(f[j] > z) 94 | { 95 | ret[i] = (char) (j + 'a'); 96 | f[j]--; 97 | break; 98 | } 99 | else 100 | z -= f[j]; 101 | } 102 | return ret; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /curriculum/outlines/data_structures/sortings.md: -------------------------------------------------------------------------------- 1 | # Sortings 2 | --- 3 | ## Outline 4 | 1. Counting Sort 5 | 1. When is it efficient ? (time and memory complexities). 6 | 2. Implementation. 7 | 3. The idea of the frequency array is commonly used. 8 | 9 | 2. Merge Sort 10 | 1. Implementation. 11 | 2. Time complexity. 12 | 3. Computing the inversion index in an array with/without using Merge Sort. 13 | * Problem: [Inversion Count](http://www.spoj.com/problems/INVCNT/) 14 | 4. Inner implementation of Arrays.sort() 15 | * Primitive vs Object arrays 16 | * How to get around QuickSort worst-case 17 | 5. Inner implementation of Collections.sort() 18 | * Time complexity for sorting LinkedList 19 | 20 | --- 21 | ## Material Resources 22 | | Resource | Points Covered | 23 | |:------------------------- |:--------------------------------| 24 | |[Hackerearth](https://www.hackerearth.com/practice/algorithms/sorting/counting-sort/tutorial/) | 1: Counting Sort | 25 | |[Hackerearth](https://www.hackerearth.com/practice/algorithms/sorting/merge-sort/tutorial/) | 2: Merge Sort | 26 | |[G4G](https://www.geeksforgeeks.org/counting-inversions/) | 2-ii:Counting Inversions using Merge Sort | 27 | 28 | --- 29 | ## Problem Sets 30 | ### Problem Set #1 31 | 32 | | Problem | Tags | Notes | Solution | 33 | |:------------- |:-------------|:-----:|:--------:| 34 | | [Larry's Array](https://www.hackerrank.com/contests/101hack35/challenges/larrys-array/problem) | Inversions | Check the parity of the number of inversions | [Link](https://ideone.com/Xalx7h) | 35 | | [Train Swapping](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=235) | Inversions | _ | [Link](https://ideone.com/rSeVOt) | 36 | | [Bubbles and Buckets](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2490) | Inversions | _ | [Link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v114/BubblesAndBuckets_UVa11495.java) | 37 | | [Age Sort](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2457) | Counting Sort | _ | [Link](https://ideone.com/XyNWLV) | 38 | | [z-sort](http://codeforces.com/contest/652/problem/B) | Sortings | _ | [Link](http://codeforces.com/contest/652/submission/34045843) | 39 | 40 | ### Problem Set #2 41 | | Problem | Tags | Notes | Solution | 42 | |:------------- |:-------------|:-----|:--------:| 43 | | [Enemy is weak](http://codeforces.com/problemset/problem/61/E) | inversions, counting, coordinate compression | count left/right inversions for each middle element in the triple | [Link](http://codeforces.com/contest/61/submission/33984110) | 44 | 45 | -------------------------------------------------------------------------------- /curriculum/outlines/getting_started/cp_environment.md: -------------------------------------------------------------------------------- 1 | # CP Environment 2 | --- 3 | ## Outline 4 | 1. Introduction to Competitive Programming 5 | 2. Online Judges and Submission System 6 | 3. Input reading and Output formatting 7 | --- 8 | ## Material Resources 9 | | Resource | Points Covered | 10 | |:------------------------- |:--------------------------------| 11 | |[TC tut1](https://www.topcoder.com/community/data-science/data-science-tutorials/the-importance-of-algorithms/) | Importance of Algos | 12 | | CP 1.1 - 1.3 | 1: Intro to CP | 13 | | [TC tut2](https://www.topcoder.com/community/data-science/data-science-tutorials/how-to-dissect-a-topcoder-problem-statement/) | 1: How to dissect a problem | 14 | | [ACP Youtube Video](https://www.youtube.com/watch?v=7y6jB16zVl8&list=PLPt2dINI2MIaNcU070HIAO8JWYBcafuyG&index=5) | 2: Using Codeforces | 15 | | [Supp Material](io_tutorial.md) | 3: I/O tutorial | 16 | 17 | --- 18 | ## Problem Sets 19 | 20 | ### Problem Set #1 21 | 22 | | Problem | Tags | Notes | Solution | 23 | |:------------- |:-------------|:-----|:--------| 24 | | [Hulk](http://codeforces.com/problemset/problem/705/A) | - | - | [link](http://codeforces.com/contest/705/submission/21388508) | 25 | | [Pangram](http://codeforces.com/problemset/problem/520/A) | - | - | [link](http://codeforces.com/contest/520/submission/15445288) | 26 | | [Wet Shark and Odd and Even](http://codeforces.com/problemset/problem/621/A) | - | `int` overflow | [link](http://codeforces.com/contest/621/submission/15737294) | 27 | | [Sub-prime](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2726) | - | simulation | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v116/SubPrimeUVa11679.java) | 28 | | [Burger Time](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=2708) | - | linear solution | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v116/BurgerTime_UVa11661.java) | 29 | 30 | ### Problem Set #2 31 | 32 | | Problem | Tags | Notes | Solution | 33 | |:------------- |:-------------|:-----|:--------| 34 | | [Next Round](http://codeforces.com/contest/158/problem/A) | | | [link](http://codeforces.com/contest/158/submission/9439064) | 35 | | [Buy a Shovel](http://codeforces.com/contest/732/problem/A) | | | [link](http://codeforces.com/contest/732/submission/21533265) | 36 | | [Beautiful Matrix](http://codeforces.com/contest/263/problem/A) | | | [link](http://codeforces.com/contest/263/submission/12431609) | 37 | | [Is it Rated?](http://codeforces.com/contest/807/problem/A) | | | [link](http://codeforces.com/contest/807/submission/26927293) | 38 | | [Beautiful Year](http://codeforces.com/problemset/problem/271/A) | | | [link](http://codeforces.com/contest/271/submission/14757983) | 39 | 40 | -------------------------------------------------------------------------------- /graphs/special/MCBM.java: -------------------------------------------------------------------------------- 1 | package graphs.special; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | // Maximum Cardinality Bipartite Matching 9 | // 1.Augmenting Path Algorithm 10 | // 2.Hopcroft Karp's Algorithm 11 | // 3.Max Flow based Solution 12 | public class MCBM { 13 | 14 | // 1.Augmenting Path Algorithm O(VE) 15 | static int V, n, m, match[]; //n(left) + m(right) = V 16 | static ArrayList[] adjList; //size = n, idx = [0, n-1], val = [0, m-1] 17 | static boolean[] vis; 18 | static int go() 19 | { 20 | //build unweighted bipartite graph with directed edges left->right set 21 | int matches = 0; 22 | match = new int[m]; 23 | Arrays.fill(match, -1); 24 | for(int i = 0; i < n; ++i) 25 | { 26 | vis = new boolean[n]; 27 | matches += aug(i); 28 | } 29 | return matches; 30 | } 31 | 32 | static int aug(int u) //returns 1 if an augment path is found 33 | { 34 | vis[u] = true; 35 | for(int v : adjList[u]) 36 | if(match[v] == -1 || !vis[match[v]] && aug(match[v]) == 1) 37 | { 38 | match[v] = u; 39 | return 1; 40 | } 41 | return 0; 42 | } 43 | 44 | // 2.Hopcroft Karp's Algorithm O(sqrt(V)E) 45 | // NOTE: vertices of left/right set start from 1 (u, v > 0) 46 | static int[] pair_U, pair_V, dist; 47 | static final int NIL = 0, INF = (int)1e9; 48 | static int hopcroftKarp() 49 | { 50 | pair_U = new int[n + 1]; //filled with NIL 51 | pair_V = new int[m + 1]; //filled with NIL 52 | dist = new int[n + 1]; 53 | 54 | int matching = 0; 55 | while(bfs()) 56 | for(int u = 1; u <= n; ++u) 57 | if(pair_U[u] == NIL && dfs(u)) 58 | ++matching; 59 | return matching; 60 | } 61 | static boolean bfs() 62 | { 63 | Queue q = new LinkedList(); 64 | for(int u = 1; u <= n; ++u) 65 | if(pair_U[u] == NIL) 66 | { 67 | dist[u] = 0; 68 | q.add(u); 69 | } 70 | else 71 | dist[u] = INF; 72 | dist[NIL] = INF; 73 | while(!q.isEmpty()) 74 | { 75 | int u = q.remove(); 76 | if(dist[u] < dist[NIL]) 77 | for(int v : adjList[u]) 78 | if(dist[pair_V[v]] == INF) 79 | { 80 | dist[pair_V[v]] = dist[u] + 1; 81 | q.add(pair_V[v]); 82 | } 83 | } 84 | return dist[NIL] != INF; 85 | } 86 | 87 | static boolean dfs(int u) 88 | { 89 | if(u == NIL) 90 | return true; 91 | 92 | for(int v : adjList[u]) 93 | if(dist[pair_V[v]] == dist[u] + 1 && dfs(pair_V[v])) 94 | { 95 | pair_U[u] = v; 96 | pair_V[v] = u; 97 | return true; 98 | } 99 | dist[u] = INF; 100 | return false; 101 | 102 | 103 | } 104 | 105 | 106 | 107 | // 3.Max Flow based Solution 108 | /* 109 | * -> add two virtual vertices s and t 110 | * -> make the graph directed from left to right 111 | * -> make the capacity of all edges = 1 112 | * -> max flow = MCBM 113 | */ 114 | } 115 | -------------------------------------------------------------------------------- /data_structures/trees/SegmentTree.java: -------------------------------------------------------------------------------- 1 | package data_structures.trees; 2 | 3 | import java.util.Scanner; 4 | 5 | // Range Sum Query (with lazy propagation) 6 | 7 | public class SegmentTree { // 1-based DS, OOP 8 | 9 | int N; //the number of elements in the array as a power of 2 (i.e. after padding) 10 | int[] array, sTree, lazy; 11 | 12 | SegmentTree(int[] in) 13 | { 14 | array = in; N = in.length - 1; 15 | sTree = new int[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero 16 | lazy = new int[N<<1]; 17 | build(1,1,N); 18 | } 19 | 20 | void build(int node, int b, int e) // O(n) 21 | { 22 | if(b == e) 23 | sTree[node] = array[b]; 24 | else 25 | { 26 | int mid = b + e >> 1; 27 | build(node<<1,b,mid); 28 | build(node<<1|1,mid+1,e); 29 | sTree[node] = sTree[node<<1]+sTree[node<<1|1]; 30 | } 31 | } 32 | 33 | 34 | void update_point(int index, int val) // O(log n) 35 | { 36 | index += N - 1; 37 | sTree[index] += val; 38 | while(index>1) 39 | { 40 | index >>= 1; 41 | sTree[index] = sTree[index<<1] + sTree[index<<1|1]; 42 | } 43 | } 44 | 45 | 46 | void update_range(int i, int j, int val) // O(log n) 47 | { 48 | update_range(1,1,N,i,j,val); 49 | } 50 | 51 | void update_range(int node, int b, int e, int i, int j, int val) 52 | { 53 | if(i > e || j < b) 54 | return; 55 | if(b >= i && e <= j) 56 | { 57 | sTree[node] += (e-b+1)*val; 58 | lazy[node] += val; 59 | } 60 | else 61 | { 62 | int mid = b + e >> 1; 63 | propagate(node, b, mid, e); 64 | update_range(node<<1,b,mid,i,j,val); 65 | update_range(node<<1|1,mid+1,e,i,j,val); 66 | sTree[node] = sTree[node<<1] + sTree[node<<1|1]; 67 | } 68 | 69 | } 70 | void propagate(int node, int b, int mid, int e) 71 | { 72 | lazy[node<<1] += lazy[node]; 73 | lazy[node<<1|1] += lazy[node]; 74 | sTree[node<<1] += (mid-b+1)*lazy[node]; 75 | sTree[node<<1|1] += (e-mid)*lazy[node]; 76 | lazy[node] = 0; 77 | } 78 | 79 | int query(int i, int j) 80 | { 81 | return query(1,1,N,i,j); 82 | } 83 | 84 | int query(int node, int b, int e, int i, int j) // O(log n) 85 | { 86 | if(i>e || j = i && e <= j) 89 | return sTree[node]; 90 | int mid = b + e >> 1; 91 | propagate(node, b, mid, e); 92 | int q1 = query(node<<1,b,mid,i,j); 93 | int q2 = query(node<<1|1,mid+1,e,i,j); 94 | return q1 + q2; 95 | 96 | } 97 | 98 | 99 | public static void main(String[] args) { 100 | 101 | Scanner sc = new Scanner(System.in); 102 | 103 | int n = sc.nextInt(); 104 | int N = 1; while(N < n) N <<= 1; //padding 105 | 106 | int[] in = new int[N + 1]; 107 | for(int i = 1; i <= n; i++) 108 | in[i] = sc.nextInt(); 109 | 110 | sc.close(); 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /DynamicProgramming/CoinChange.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | /** 4 | * @author Varun Upadhyay (https://github.com/varunu28) 5 | */ 6 | public class CoinChange { 7 | 8 | // Driver Program 9 | public static void main(String[] args) { 10 | 11 | int amount = 12; 12 | int[] coins = {2, 4, 5}; 13 | 14 | System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount)); 15 | System.out.println("Minimum number of coins required for amount :" + amount + " is: " + minimumCoins(coins, amount)); 16 | 17 | } 18 | 19 | /** 20 | * This method finds the number of combinations of getting change for a given amount and change coins 21 | * 22 | * @param coins The list of coins 23 | * @param amount The amount for which we need to find the change 24 | * Finds the number of combinations of change 25 | **/ 26 | public static int change(int[] coins, int amount) { 27 | 28 | int[] combinations = new int[amount + 1]; 29 | combinations[0] = 1; 30 | 31 | for (int coin : coins) { 32 | for (int i = coin; i < amount + 1; i++) { 33 | combinations[i] += combinations[i - coin]; 34 | } 35 | // Uncomment the below line to see the state of combinations for each coin 36 | // printAmount(combinations); 37 | } 38 | 39 | return combinations[amount]; 40 | } 41 | 42 | /** 43 | * This method finds the minimum number of coins needed for a given amount. 44 | * 45 | * @param coins The list of coins 46 | * @param amount The amount for which we need to find the minimum number of coins. 47 | * Finds the the minimum number of coins that make a given value. 48 | **/ 49 | public static int minimumCoins(int[] coins, int amount) { 50 | //minimumCoins[i] will store the minimum coins needed for amount i 51 | int[] minimumCoins = new int[amount + 1]; 52 | 53 | minimumCoins[0] = 0; 54 | 55 | for (int i = 1; i <= amount; i++) { 56 | minimumCoins[i] = Integer.MAX_VALUE; 57 | } 58 | for (int i = 1; i <= amount; i++) { 59 | for (int coin : coins) { 60 | if (coin <= i) { 61 | int sub_res = minimumCoins[i - coin]; 62 | if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i]) 63 | minimumCoins[i] = sub_res + 1; 64 | } 65 | } 66 | } 67 | // Uncomment the below line to see the state of combinations for each coin 68 | //printAmount(minimumCoins); 69 | return minimumCoins[amount]; 70 | } 71 | 72 | // A basic print method which prints all the contents of the array 73 | public static void printAmount(int[] arr) { 74 | for (int i = 0; i < arr.length; i++) { 75 | System.out.print(arr[i] + " "); 76 | } 77 | System.out.println(); 78 | } 79 | } -------------------------------------------------------------------------------- /curriculum/outlines/outline_format.md: -------------------------------------------------------------------------------- 1 | # Outline Checklist 2 | 3 | 1. Create a file in the following path `curriculum/outlines/[category]/[topic_name]`. 4 | - [category] and [topic_name] are specified in the preparation drafts. 5 | 2. Write the file title with the topic name. 6 | - use H1 followed by a horizontal line. 7 | 3. Make three sections with titles [Outline, Material Resources, Problem Sets]. 8 | - use H3 and separate them by horizontal lines. 9 | 4. Add all topic points, subpoints, examples... etc in the outline section. 10 | - use bullets and numbers. 11 | - don't get into details if they are well-explained in the material provided. 12 | - add the recommended in-session examples below correct subpoints, maybe link will be needed. 13 | 5. Add material resources. 14 | - make a table with two columns [Resource, Points covered]. 15 | - In resource, write a shorthand name for the link content. 16 | - In Points covered, write the point(s) number and optionally a shorthand point description. 17 | 6. Add the problem sets 18 | - Problem set Structure: 19 | - col 1: problem name and link 20 | - col 2: tags - all tags except the main tag (outline topic) 21 | - col 3: notes [VERY IMPORTANT] - hints, main outcome/idea, problems in the problem statement or its input. 22 | - col 4: solution link 23 | - Three problem sets are needed: 24 | - Problem Set 1: 25 | - must-solve problems. Every problem must add a new thing. 26 | - Must cover the content of the topic. 27 | - problems count >= 5 * acm_days. 28 | - Problem Set 2: 29 | - extra problems. These problems will be solved by hard-working trainees. 30 | - It’s strictly recommended that they have new ideas. 31 | - problems count <= 5 * acm_days. 32 | - Problem Set 3 (optional): 33 | - redundant ideas. These problems will be solved by trainees who solved problem set 1 but still not confident of this topic. 34 | - Use the problems in the old plans. If you want to remove any of them, please write them down in the merge request with the reason of their removal (a better version including the problem trick is added, doesn’t add a new thing… etc). 35 | - Extra problems that depend on other topics or are difficult at the current level, should be added in the general problems sheet. 36 | 7. Make a pull request! 37 | 38 | ### Tips and auxilary material 39 | - Markdown [cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). 40 | - See this [outline sample](https://github.com/AhmadElsagheer/Competitive-programming-library/blob/master/curriculum/outlines/data_structures/linear_ds.md). 41 | - You can use the [problems sheet](https://docs.google.com/spreadsheets/d/1blSbPr1pAFZSzlAi2IVdTeytz2yO7Ejx9SeQWOSxY0w/edit#gid=1542041463) and [topics sheet](https://docs.google.com/spreadsheets/d/1tLEm58_2bQgM7qhATSjN0fGbdLLtaOCjUFnTGniHbjI/edit#gid=0) for help. 42 | - Act like as if you are going to conduct the session. You will first write main points down. Then you will add subpoints. Then you will add examples. Then you will add pitfalls and tricks that are most probably not mentioned anywhere, but gained by experience. 43 | -------------------------------------------------------------------------------- /curriculum/outlines/solving_techniques/binary_search.md: -------------------------------------------------------------------------------- 1 | # Binary Search 2 | --- 3 | ## Outline 4 | 1. Basic usage of binary search 5 | - Examples 6 | * finding an element in array of distinct values 7 | * Arrays with duplicates (finding first/last occurence) 8 | * lower and upper bounds 9 | - Complexity 10 | - Built-in methods (e.g. `Collections.binarySearch()`) 11 | 2. Binary search on uncommon data structures 12 | - Example: "My Ancestor" problem 13 | 3. Bisection method 14 | - `while` loop implementation with `EPS` 15 | - `for` loop implementation 16 | 4. Main theorem 17 | - variants in checker predicates (e.g. simulating using current guessed value) 18 | 5. Binary Seach the Answer (monotonic functions) 19 | --- 20 | 21 | ## Material Resources 22 | | Resource | Points Covered | 23 | |:------------------------- |:--------------------------------| 24 | |CP Section 3.3 | Most of outline points| 25 | |[Topcoder Blog](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/)|Monotonicity and Finding the answer| 26 | 27 | --- 28 | ## Problem Sets 29 | ### Problem Set #1 30 | 31 | | Problem | Tags | Notes | Solution | 32 | |:------------- |:-------------|:-----|:--------| 33 | |[The Playboy Chimp](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1552)| | lower and upper bound |[link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v106/ThePlayboyChimp_UVa10611.java)| 34 | | [Where is the Marble?](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1415) | | basic usage | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v104/WhatIsTheMarble_UVa10474.java) | 35 | | [Burning Midnight Oil](http://codeforces.com/contest/165/problem/B) | | BS the answer | [link](http://codeforces.com/contest/165/submission/14923055) | 36 | | [Fill the Containers](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2408) | | BS the answer, checker predicate| [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v114/FillTheContainers_UVa11413.java) | 37 | |[Sagheer and Nubian Market](http://codeforces.com/contest/812/problem/C)| | BS the answer|[link](http://codeforces.com/contest/812/submission/27728473)| 38 | 39 | ### Problem Set #2 40 | | Problem | Tags | Notes | Solution | 41 | |:------------- |:-------------|:-----|:--------| 42 | | [Energy exchange](http://codeforces.com/contest/68/problem/B) | | BS the answer, doubles | [link](http://codeforces.com/contest/68/submission/20514429) | 43 | |[Gukiz and Boxes](http://codeforces.com/problemset/problem/551/C)|| BS the answer, predicate checker |[link](http://codeforces.com/contest/551/submission/34331187)| 44 | |[Magic Powder - 2](http://codeforces.com/problemset/problem/670/D2)| | BS the Answer |[link](http://codeforces.com/contest/670/submission/17824666)| 45 | | [Showstopper](http://www.spoj.com/problems/MSE07E/) | | BS on intervals | [link](https://ideone.com/0Dggd5) | 46 | | [Preparing for the Contest](http://codeforces.com/contest/377/problem/B) | sortings, priority queues, greedy | | [link](http://codeforces.com/contest/377/submission/19848348) | 47 | 48 | -------------------------------------------------------------------------------- /DynamicProgramming/Fibonacci.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | /** 8 | * @author Varun Upadhyay (https://github.com/varunu28) 9 | */ 10 | 11 | public class Fibonacci { 12 | 13 | private static Map map = new HashMap<>(); 14 | 15 | 16 | public static void main(String[] args) { 17 | 18 | // Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...] 19 | Scanner sc = new Scanner(System.in); 20 | int n = sc.nextInt(); 21 | 22 | System.out.println(fibMemo(n)); 23 | System.out.println(fibBotUp(n)); 24 | System.out.println(fibOptimized(n)); 25 | sc.close(); 26 | } 27 | 28 | /** 29 | * This method finds the nth fibonacci number using memoization technique 30 | * 31 | * @param n The input n for which we have to determine the fibonacci number 32 | * Outputs the nth fibonacci number 33 | **/ 34 | public static int fibMemo(int n) { 35 | if (map.containsKey(n)) { 36 | return map.get(n); 37 | } 38 | 39 | int f; 40 | 41 | if (n <= 1) { 42 | f = n; 43 | } else { 44 | f = fibMemo(n - 1) + fibMemo(n - 2); 45 | map.put(n, f); 46 | } 47 | return f; 48 | } 49 | 50 | /** 51 | * This method finds the nth fibonacci number using bottom up 52 | * 53 | * @param n The input n for which we have to determine the fibonacci number 54 | * Outputs the nth fibonacci number 55 | **/ 56 | public static int fibBotUp(int n) { 57 | 58 | Map fib = new HashMap<>(); 59 | 60 | for (int i = 0; i <= n; i++) { 61 | int f; 62 | if (i <= 1) { 63 | f = i; 64 | } else { 65 | f = fib.get(i - 1) + fib.get(i - 2); 66 | } 67 | fib.put(i, f); 68 | } 69 | 70 | return fib.get(n); 71 | } 72 | 73 | 74 | /** 75 | * This method finds the nth fibonacci number using bottom up 76 | * 77 | * @param n The input n for which we have to determine the fibonacci number 78 | * Outputs the nth fibonacci number 79 | *

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

85 | * Whereas , the above functions will take O(n) Space. 86 | * @author Shoaib Rayeen (https://github.com/shoaibrayeen) 87 | **/ 88 | public static int fibOptimized(int n) { 89 | if (n == 0) { 90 | return 0; 91 | } 92 | int prev = 0, res = 1, next; 93 | for (int i = 2; i <= n; i++) { 94 | next = prev + res; 95 | prev = res; 96 | res = next; 97 | } 98 | return res; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /AVLTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left; 7 | Node *right; 8 | int height; 9 | }*Root = NULL; 10 | 11 | Node* new_Node(int DATA) 12 | { 13 | Node* node = new Node(); 14 | node->data = DATA; 15 | node->left = NULL; 16 | node->right = NULL; 17 | node->height = 1; 18 | return(node); 19 | } 20 | 21 | int height(Node *a) 22 | { 23 | if(a==NULL) 24 | return 0; 25 | return a->height; 26 | } 27 | int balance(Node *a) 28 | { 29 | if(a==NULL) 30 | return 0; 31 | int lh = height(a->left); 32 | int rh = height(a->right); 33 | return (lh-rh); 34 | } 35 | Node *RR(Node *y) 36 | { 37 | Node *x = y->left; 38 | Node *T2 = x->right; 39 | x->right = y; 40 | y->left = T2; 41 | y->height = max(height(y->left), 42 | height(y->right)) + 1; 43 | x->height = max(height(x->left), 44 | height(x->right)) + 1; 45 | return x; 46 | } 47 | 48 | Node *LL(Node *x) 49 | { 50 | Node *y = x->right; 51 | Node *T2 = y->left; 52 | y->left = x; 53 | x->right = T2; 54 | x->height = max(height(x->left), 55 | height(x->right)) + 1; 56 | y->height = max(height(y->left), 57 | height(y->right)) + 1; 58 | return y; 59 | } 60 | Node* insertToAVL(Node* root, int data) 61 | { 62 | if(root==NULL) 63 | { 64 | Node* Nodes = new_Node(data); 65 | return(Nodes); 66 | } 67 | if(root->data>data) 68 | { 69 | root->left = insertToAVL(root->left,data); 70 | } 71 | else if(root->dataright = insertToAVL(root->right,data); 74 | } 75 | else 76 | return root; 77 | 78 | root->height = max(height(root->left),height(root->right)) + 1; 79 | 80 | int factor = balance(root); 81 | 82 | if(factor > 1 && root->left->data > data) 83 | { 84 | return RR(root); 85 | } 86 | if(factor < -1 && root->right->data < data) 87 | { 88 | return LL(root); 89 | } 90 | if (factor > 1 && data > root->left->data) 91 | { 92 | root->left = LL(root->left); 93 | return RR(root); 94 | } 95 | if (factor < -1 && data < root->right->data) 96 | { 97 | root->right = RR(root->right); 98 | return LL(root); 99 | } 100 | return root; 101 | } 102 | void inorder(Node* root) 103 | { 104 | if(root != NULL) 105 | { 106 | inorder(root->left); 107 | cout << root->data << " "; 108 | inorder(root->right); 109 | } 110 | } 111 | int main() 112 | { 113 | int size; 114 | cout << "\nEnter num of node :- "; 115 | cin >> size; 116 | vector vec; 117 | cout << "\nEnter values :- "; 118 | for(int i = 0; i < size; i++) 119 | { 120 | int x; 121 | cin >> x; 122 | vec.push_back(x); 123 | } 124 | Root = insertToAVL(Root, vec[0]); 125 | for(int i = 1; i < size; i++) { 126 | Root = insertToAVL(Root, vec[i]); 127 | } 128 | cout << "\nInOrder Traversal is:- \n"; 129 | inorder(Root); 130 | cout<< "\nRoot Node is:- \n"; 131 | cout<data<<"\n"; 132 | return 0; 133 | } 134 | -------------------------------------------------------------------------------- /DynamicProgramming/EditDistance.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | /** 4 | * A DynamicProgramming based solution for Edit Distance problem In Java 5 | * Description of Edit Distance with an Example: 6 | *

7 | * Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another, 8 | * by counting the minimum number of operations required to transform one string into the other. The 9 | * distance operations are the removal, insertion, or substitution of a character in the string. 10 | *

11 | *

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

14 | * kitten → sitten (substitution of "s" for "k") 15 | * sitten → sittin (substitution of "i" for "e") 16 | * sittin → sitting (insertion of "g" at the end). 17 | * 18 | * @author SUBHAM SANGHAI 19 | **/ 20 | 21 | import java.util.Scanner; 22 | 23 | public class EditDistance { 24 | 25 | public static int minDistance(String word1, String word2) { 26 | int len1 = word1.length(); 27 | int len2 = word2.length(); 28 | // len1+1, len2+1, because finally return dp[len1][len2] 29 | int[][] dp = new int[len1 + 1][len2 + 1]; 30 | /* If second string is empty, the only option is to 31 | insert all characters of first string into second*/ 32 | for (int i = 0; i <= len1; i++) { 33 | dp[i][0] = i; 34 | } 35 | /* If first string is empty, the only option is to 36 | insert all characters of second string into first*/ 37 | for (int j = 0; j <= len2; j++) { 38 | dp[0][j] = j; 39 | } 40 | //iterate though, and check last char 41 | for (int i = 0; i < len1; i++) { 42 | char c1 = word1.charAt(i); 43 | for (int j = 0; j < len2; j++) { 44 | char c2 = word2.charAt(j); 45 | //if last two chars equal 46 | if (c1 == c2) { 47 | //update dp value for +1 length 48 | dp[i + 1][j + 1] = dp[i][j]; 49 | } else { 50 | /* if two characters are different , 51 | then take the minimum of the various operations(i.e insertion,removal,substitution)*/ 52 | int replace = dp[i][j] + 1; 53 | int insert = dp[i][j + 1] + 1; 54 | int delete = dp[i + 1][j] + 1; 55 | 56 | int min = replace > insert ? insert : replace; 57 | min = delete > min ? min : delete; 58 | dp[i + 1][j + 1] = min; 59 | } 60 | } 61 | } 62 | /* return the final answer , after traversing through both the strings*/ 63 | return dp[len1][len2]; 64 | } 65 | 66 | 67 | public static void main(String[] args) { 68 | Scanner input = new Scanner(System.in); 69 | String s1, s2; 70 | System.out.println("Enter the First String"); 71 | s1 = input.nextLine(); 72 | System.out.println("Enter the Second String"); 73 | s2 = input.nextLine(); 74 | //ans stores the final Edit Distance between the two strings 75 | int ans = minDistance(s1, s2); 76 | System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans); 77 | input.close(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /circular linked list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Node { 4 | int data; 5 | Node* next; 6 | }; 7 | Node* last; 8 | 9 | //Node* create(Node* last , int d); 10 | void insertBeg( int d) 11 | { 12 | if(last==NULL) 13 | { 14 | Node* temp = new Node(); 15 | temp->data = d; 16 | last = temp; 17 | temp->next = last; 18 | 19 | } 20 | else 21 | { 22 | Node* temp = new Node(); 23 | temp->data = d; 24 | temp->next = last->next; 25 | last->next = temp; 26 | 27 | } 28 | } 29 | Node* append(Node* last , int d) 30 | { 31 | if(last ==NULL) 32 | { 33 | Node*temp = new Node(); 34 | temp->data = d; 35 | last = temp; 36 | temp->next = last; 37 | return last; 38 | } 39 | else 40 | { 41 | Node* temp = new Node(); 42 | temp->data = d; 43 | temp->next = last->next; 44 | last->next = temp; 45 | last = temp; 46 | return last; 47 | } 48 | 49 | } 50 | //Node* between(Node* last , int d , int item); 51 | void del(int d) 52 | { 53 | if(last == NULL) 54 | { 55 | cout<<"List is empty "<next; 59 | Node* temp; 60 | if(last-> next == last && last->data == d) 61 | { 62 | //only node 63 | temp = last; 64 | last = NULL; 65 | delete(temp); 66 | return; 67 | } 68 | if(last->next->data == d) 69 | { 70 | //first node 71 | temp = last->next; 72 | last->next = temp->next; 73 | delete(temp); 74 | return; 75 | } 76 | while(p->next != last) 77 | { 78 | //nth node 79 | if(p->next->data == d) 80 | { 81 | temp = p->next; 82 | p->next = temp->next; 83 | delete(temp); 84 | 85 | } 86 | p = p->next; 87 | } 88 | if(last->data == d) 89 | { 90 | //last node 91 | temp = last; 92 | } 93 | 94 | } 95 | void display() 96 | { 97 | Node* temp = last; 98 | if(temp == NULL) 99 | { 100 | cout<<"List is empty "<next; 105 | do 106 | { 107 | cout<data<<" "; 108 | p = p->next; 109 | } 110 | while(p != temp->next); 111 | cout<>z; 126 | switch(z) 127 | { 128 | case 1: 129 | cout<<"Enter the no of elements to be entered "<>n; 131 | cout<<"Enter the element of list "<>d; 135 | insertBeg(d); 136 | } 137 | display(); 138 | break; 139 | 140 | case 2: 141 | cout<<"Enter the no of elements to be entered "<>n; 143 | cout<<"Enter the element of list "<>d; 147 | last = append(last,d); 148 | } 149 | display(); 150 | break; 151 | 152 | case 3: 153 | return 0; 154 | 155 | default: 156 | cout<<"Wrong choice"; 157 | } 158 | } 159 | return 0; 160 | } 161 | -------------------------------------------------------------------------------- /data_structures/trees/SegmentTree2D.java: -------------------------------------------------------------------------------- 1 | package data_structures.trees; 2 | 3 | public class SegmentTree2D { // subrectangle sum, point update 4 | 5 | int[][] matrix; 6 | int[][] tree; 7 | int N, M; 8 | 9 | SegmentTree2D(int[][] a) 10 | { 11 | matrix = a; 12 | N = 1; while(N < a.length) N <<= 1; 13 | M = 1; while(M < a[0].length) M <<= 1; 14 | buildX(1, 1, N); 15 | } 16 | 17 | void buildX(int vx, int lx, int rx) 18 | { 19 | if(lx != rx) 20 | { 21 | int mid = (lx + rx) >> 1; 22 | buildX(vx << 1, lx, mid); 23 | buildX(vx << 1 | 1, mid + 1, rx); 24 | } 25 | buildY(vx, lx, rx, 1, 1, M); 26 | } 27 | 28 | void buildY(int vx, int lx, int rx, int vy, int ly, int ry) 29 | { 30 | if(ly == ry) { 31 | if(lx == rx) 32 | { 33 | if(lx <= matrix.length && ly <= matrix[0].length) 34 | tree[vx][vy] = matrix[lx - 1][ly - 1]; 35 | 36 | } 37 | else 38 | tree[vx][vy] = tree[vx << 1][vy] + tree[vx << 1 | 1][vy]; 39 | return; 40 | } 41 | 42 | int mid = (ly + ry) >> 1; 43 | buildY(vx, lx, rx, vy << 1, ly, mid); 44 | buildY(vx, lx, rx, vy << 1 | 1, mid + 1, ry); 45 | tree[vx][vy] = tree[vx][vy << 1] + tree[vx][vy << 1 | 1]; 46 | } 47 | 48 | int sum(int bx, int ex, int by, int ey) { return sumX(1, 1, N, bx, ex, by, ey); } 49 | 50 | int sumX(int vx, int lx, int rx, int bx, int ex, int by, int ey) 51 | { 52 | if(lx > rx) 53 | return 0; 54 | if(bx == lx && rx == ex) 55 | return sumY(vx, 1, 1, M, by, ey); 56 | int mid = (lx + rx) >> 1; 57 | int q1 = sumX(vx << 1, lx, mid, bx, Math.min(rx, mid), by, ey); 58 | int q2 = sumX(vx << 1 | 1, mid + 1, rx, Math.max(mid + 1, bx), ex, by, ey); 59 | return q1 + q2; 60 | } 61 | 62 | int sumY(int vx, int vy, int ly, int ry, int by, int ey) 63 | { 64 | if(ry > ly) 65 | return 0; 66 | if(by == ly && ry == ey) 67 | return tree[vx][vy]; 68 | int mid = (ly + ry) >> 1; 69 | int q1 = sumY(vx, vy << 1, ly, mid, by, Math.min(ey, mid)); 70 | int q2 = sumY(vx, vy << 1 | 1, mid + 1, ry, Math.max(mid + 1, by), ey); 71 | return q1 + q2; 72 | } 73 | 74 | void update(int i, int j, int val) { updateX(1, 1, N, i, j, val); } 75 | 76 | void updateX(int vx, int lx, int rx, int i, int j, int val) 77 | { 78 | if(lx != rx) 79 | { 80 | int mid = (lx + rx) >> 1; 81 | if(i <= mid) 82 | updateX(vx << 1, lx, mid, i, j, val); 83 | else 84 | updateX(vx << 1 | 1, mid + 1, rx, i, j, val); 85 | } 86 | updateY(vx, lx, rx, 1, 1, M, j, val); 87 | } 88 | 89 | void updateY(int vx, int lx, int rx, int vy, int ly, int ry, int j, int val) 90 | { 91 | if(ly == ry) 92 | if(lx == rx) 93 | tree[vx][vy] = val; 94 | else 95 | tree[vx][vy] = tree[vx << 1][vy] + tree[vx << 1 | 1][vy]; 96 | else 97 | { 98 | int mid = (ly + ry) >> 1; 99 | if(j <= mid) 100 | updateY(vx, lx, rx, vy << 1, ly, mid, j, val); 101 | else 102 | updateY(vx, lx, rx, vy << 1 | 1, mid + 1, ry, j, val); 103 | tree[vx][vy] = tree[vx][vy << 1] + tree[vx][vy << 1 | 1]; 104 | } 105 | 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /curriculum/outlines/getting_started/adhoc.md: -------------------------------------------------------------------------------- 1 | # Adhoc 2 | --- 3 | ## Outline 4 | Just some Adhoc problems! 5 | 6 | --- 7 | ## Material Resources 8 | | Resource | Points Covered | 9 | |:------------------------- |:--------------------------------| 10 | | [Wiki page](https://en.wikipedia.org/wiki/Ad_hoc) | Ad hoc ? | 11 | | CP 1.4 | Just Adhoc! | 12 | 13 | --- 14 | ## Problem Sets 15 | 16 | ### Problem Set #1 17 | 18 | | Problem | Tags | Notes | Solution | 19 | |:------------- |:-------------|:-----|:--------| 20 | | [Multiplication Table](http://codeforces.com/problemset/problem/577/A) | | | [link](http://codeforces.com/contest/577/submission/12926515) | 21 | | [Bear and Finding Criminals](http://codeforces.com/problemset/problem/680/B) | | | [link](http://codeforces.com/problemset/problem/680/B) | 22 | | [Guess the Permutation](http://codeforces.com/problemset/problem/618/B) | | | [link](http://codeforces.com/contest/618/submission/15653301)| 23 | | [Punctuation](http://codeforces.com/problemset/problem/147/A)| | | [link](http://codeforces.com/contest/147/submission/19827974)| 24 | | [Rewards](http://codeforces.com/problemset/problem/448/A) | | ceiling with integer division | [link](http://codeforces.com/contest/448/submission/21388142) | 25 | | [Bachgold Problem](http://codeforces.com/contest/749/problem/A) | | | [link](http://codeforces.com/contest/749/submission/23144882) | 26 | | [Infinite Sequence](http://codeforces.com/problemset/problem/675/A) | | | [link](http://codeforces.com/contest/675/submission/17934991) | 27 | | [Inna and Choose Options](http://codeforces.com/problemset/problem/400/A) | | | [link](http://codeforces.com/contest/400/submission/12474966) | 28 | | [Visiting a Friend](http://codeforces.com/problemset/problem/902/A) | | | [link](http://codeforces.com/contest/902/submission/33457561) | 29 | | [Cheap Travel](http://codeforces.com/problemset/problem/466/A) | | | [link](http://codeforces.com/contest/466/submission/16349453) | 30 | | [Initial Bet](http://codeforces.com/problemset/problem/478/A) | | | [link](http://codeforces.com/contest/478/submission/16349663) | 31 | | [Pashmak and Garden](http://codeforces.com/problemset/problem/459/A) | | | [link](http://codeforces.com/contest/459/submission/17912788) | 32 | | [Vitya in the Countryside](http://codeforces.com/problemset/problem/719/A) | | | [link](http://codeforces.com/contest/719/submission/20890852) | 33 | | [Currency System](http://codeforces.com/problemset/problem/560/A) | | | [link](http://codeforces.com/contest/560/submission/17421116) | 34 | | [Mahmoud and Longest UnCommon Subsequence](http://codeforces.com/contest/766/problem/A) | | | [link](http://codeforces.com/contest/766/submission/24492986) | 35 | | [Andrushya and Socks](http://codeforces.com/contest/782/problem/A) | | | [link](http://codeforces.com/contest/782/submission/25246355) | 36 | | [Taymyr is Calling You](http://codeforces.com/contest/764/problem/A) | | | [link](http://codeforces.com/contest/764/submission/24366650) | 37 | | [Sagheer and Crossroads](http://codeforces.com/problemset/problem/812/A) | | | [link](http://codeforces.com/contest/812/submission/27525235) | 38 | | [Bus Game](http://codeforces.com/problemset/problem/79/A) | | xor turn variable | [link](http://codeforces.com/contest/79/submission/33894006) | 39 | | [Buses Between Cities](http://codeforces.com/problemset/problem/665/A) | | | [link](http://codeforces.com/contest/665/submission/17402539) | 40 | | [Case of Zeroes and Ones](http://codeforces.com/problemset/problem/556/A) | | | [link](http://codeforces.com/contest/556/submission/17295036) | 41 | 42 | -------------------------------------------------------------------------------- /curriculum/outlines/graphs/graph_traversal.md: -------------------------------------------------------------------------------- 1 | # Graph Structure and Traversal 2 | --- 3 | ## Outline 4 | 1. Graph Definition 5 | 1. Representation Forms 6 | - Mathematical Form 7 | - Diagrammatic Form 8 | 2. Graph Types 9 | - Directed vs Undirected 10 | - Weighted vs Unweighted 11 | - Simple vs Multi 12 | 3. Important Classes of Graphs 13 | - Connected Graph 14 | - Complete Graph 15 | - Directed Acyclic Graph 16 | - Bipartite Graph 17 | - Tree 18 | 2. Graph Representation: space and time complexities 19 | - Adjacency Matrix 20 | - Adjacency List 21 | - Edge List 22 | - Implicit Graphs 23 | 3. Graph Traversal 24 | - Depth-First Search 25 | - Implementation and Complexity 26 | - Applications 27 | * Reachability between two nodes 28 | * Graph Connectivity 29 | - Breadth-First Search 30 | - Implementation and Complexity 31 | - Applications 32 | * Reachability between two nodes 33 | * Graph Connectivity 34 | * Shortest path in unweighted graph 35 | 36 | --- 37 | 38 | ## Material Resources 39 | | Resource | Points Covered | 40 | |:------------------------- |:--------------------------------| 41 | | [Wikipedia](https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)) | 1: Graph Definition | 42 | | CP Section 2.4.1 | 2: Graph Representation | 43 | | CP Section 4.4.1-2 | 2: Graph Traversal | 44 | | [Maximal: DFS](http://e-maxx.ru/algo/dfs) | 3. DFS Applications | 45 | | [Maximal: BFS](http://e-maxx.ru/algo/bfs) | 3. BFS Applications | 46 | 47 | --- 48 | ## Problem Sets 49 | ### Problem Set #1 50 | 51 | | Problem | Tags | Notes | Solution | 52 | |:------------- |:-------------|:-----|:--------| 53 | | [Easy Problem from Rujia Liu?](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3142) | | graph representation | [link]() | 54 | | [My Dear Neighbours](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1869) | | graph representation | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v109/MyDearNeighbours_UVa10928.java) | 55 | | [Demanding Dilemma](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2545) | | graph representation | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v115/DemandingDilemma_UVa11550.java) | 56 | | [The Forrest for the Trees](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=540) | | graph representation | [link]() | 57 | | [Colorful Graph](http://codeforces.com/contest/246/problem/D) | treesets | graph representation | [link](http://codeforces.com/contest/246/submission/14189098) | 58 | | [Vertex](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=216) | | dfs, reachability | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v002/Vertex_UVa280.java) | 59 | | [Forwarding Emails](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3873) | | dfs, cycles | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v124/ForwardingEmails_UVa12442.java) | 60 | | [Learning Languages](http://codeforces.com/problemset/problem/277/A) | | dfs | [link](http://codeforces.com/contest/277/submission/12548270) | 61 | | [Party](http://codeforces.com/problemset/problem/115/A) | | bfs | [link](http://codeforces.com/contest/115/submission/12466514) | 62 | | [Eternal Victory](http://codeforces.com/problemset/problem/61/D) | | dfs | [link](http://codeforces.com/contest/61/submission/12600005) | 63 | -------------------------------------------------------------------------------- /geometry/Point.java: -------------------------------------------------------------------------------- 1 | package geometry; 2 | 3 | public class Point implements Comparable{ 4 | 5 | static final double EPS = 1e-9; 6 | 7 | double x, y; 8 | 9 | Point(double a, double b) { x = a; y = b; } 10 | 11 | public int compareTo(Point p) 12 | { 13 | if(Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; 14 | if(Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; 15 | return 0; 16 | } 17 | 18 | public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } 19 | 20 | static double sq(double x) { return x * x; } 21 | 22 | Point rotate(double angle) 23 | { 24 | double c = Math.cos(angle), s = Math.sin(angle); 25 | return new Point(x * c - y * s, x * s + y * c); 26 | } 27 | // for integer points and rotation by 90 (counterclockwise) : swap x and y, negate x 28 | 29 | Point rotate(double theta, Point p) //rotate around p 30 | { 31 | Vector v = new Vector(p, new Point(0, 0)); 32 | return translate(v).rotate(theta).translate(v.reverse()); 33 | } 34 | 35 | Point translate(Vector v) { return new Point(x + v.x , y + v.y); } 36 | 37 | Point reflectionPoint(Line l) //reflection point of p on line l 38 | { 39 | Point p = l.closestPoint(this); 40 | Vector v = new Vector(this, p); 41 | return this.translate(v).translate(v); 42 | } 43 | 44 | boolean between(Point p, Point q) 45 | { 46 | return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) 47 | && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); 48 | } 49 | 50 | //returns true if it is on the line defined by a and b 51 | boolean onLine(Point a, Point b) 52 | { 53 | if(a.compareTo(b) == 0) return compareTo(a) == 0; 54 | return Math.abs(new Vector(a, b).cross(new Vector(a, this))) < EPS; 55 | } 56 | 57 | boolean onSegment(Point a, Point b) 58 | { 59 | if(a.compareTo(b) == 0) return compareTo(a) == 0; 60 | return onRay(a, b) && onRay(b, a); 61 | } 62 | 63 | //returns true if it is on the ray whose start point is a and passes through b 64 | boolean onRay(Point a, Point b) 65 | { 66 | if(a.compareTo(b) == 0) return compareTo(a) == 0; 67 | return new Vector(a, b).normalize().equals(new Vector(a, this).normalize()); //implement equals() 68 | } 69 | 70 | // returns true if it is on the left side of Line pq 71 | // add EPS to LHS if on-line points are accepted 72 | static boolean ccw(Point p, Point q, Point r) 73 | { 74 | return new Vector(p, q).cross(new Vector(p, r)) > 0; 75 | } 76 | 77 | static boolean collinear(Point p, Point q, Point r) 78 | { 79 | return Math.abs(new Vector(p, q).cross(new Vector(p, r))) < EPS; 80 | } 81 | 82 | static double angle(Point a, Point o, Point b) // angle AOB 83 | { 84 | Vector oa = new Vector(o, a), ob = new Vector(o, b); 85 | return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); 86 | } 87 | 88 | static double distToLine(Point p, Point a, Point b) //distance between point p and a line defined by points a, b (a != b) 89 | { 90 | if(a.compareTo(b) == 0) return p.dist(a); 91 | // formula: c = a + u * ab 92 | Vector ap = new Vector(a, p), ab = new Vector(a, b); 93 | double u = ap.dot(ab) / ab.norm2(); 94 | Point c = a.translate(ab.scale(u)); 95 | return p.dist(c); 96 | } 97 | // Another way: find closest point and calculate the distance between it and p 98 | 99 | static double distToLineSegment(Point p, Point a, Point b) 100 | { 101 | Vector ap = new Vector(a, p), ab = new Vector(a, b); 102 | double u = ap.dot(ab) / ab.norm2(); 103 | if (u < 0.0) return p.dist(a); 104 | if (u > 1.0) return p.dist(b); 105 | return distToLine(p, a, b); 106 | } 107 | // Another way: find closest point and calculate the distance between it and p 108 | } 109 | -------------------------------------------------------------------------------- /graphs/traversal/BridgesOnline.java: -------------------------------------------------------------------------------- 1 | package graphs.traversal; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class BridgesOnline { 6 | 7 | /* 8 | * WARNING: NOT TESTED BEFORE 9 | * 10 | * - A block is a set of connected nodes with no bridges. 11 | * - A Component is a set of connected nodes possibly bridges. 12 | * It consists of several blocks forming a tree (bridge tree). 13 | * 14 | * - When an edge (u, v) is added to the graph, there are 3 cases :- 15 | * + u and v in same block. 16 | * > Do nothing. 17 | * + u and v in different blocks and different components. 18 | * > let u and v are reps of their corresponding blocks 19 | * > let rank[comp(u)] > rank[comp(v)] 20 | * > comp(u) and comp(v) will be merged with rep = comp(u) 21 | * > set v as root of comp(v) 22 | * > set v as a child of u 23 | * + u and v in different blocks but same component. 24 | * > let u and v are reps of their corresponding blocks 25 | * > A cycle in the tree is formed 26 | * > bridges from u to lca(u, v) are removed 27 | * > bridges from v to lca(u, v) are removed 28 | * > blocks connected by the same bridge are unioned 29 | */ 30 | 31 | int[] block, comp, par, rank; 32 | int bridges, timer, time[]; 33 | 34 | BridgesOnline(int V) 35 | { 36 | block = new int[V]; 37 | comp = new int[V]; 38 | par = new int[V]; 39 | rank = new int[V]; 40 | 41 | for(int i = 0; i < V; ++i) 42 | { 43 | block[i] = comp[i] = i; 44 | par[i] = -1; 45 | } 46 | } 47 | 48 | int getBlock(int x) { return block[x] == x ? x : (block[x] = getBlock(block[x])); } 49 | 50 | int getComp(int x) { return comp[x] == x ? x : (comp[x] = getComp(comp[x])); } 51 | 52 | void addEdge(int u, int v) 53 | { 54 | u = getBlock(u); 55 | v = getBlock(v); 56 | 57 | if(u == v) 58 | return; 59 | 60 | int cu = getComp(u), cv = getComp(v); 61 | if(cu != cv) 62 | { 63 | ++bridges; 64 | if(rank[cu] < rank[cv]) 65 | { 66 | u ^= v; v ^= u; u ^= v; 67 | cu ^= cv; cv ^= cu; cu ^= cv; 68 | } 69 | makeRoot(v); 70 | par[v] = comp[v] = u; 71 | if(rank[cu] == rank[v]) 72 | ++rank[cu]; 73 | } 74 | else 75 | mergePath(u, v); 76 | } 77 | 78 | void makeRoot(int u) 79 | { 80 | int root = u, child = -1; 81 | while(u != -1) 82 | { 83 | int p = getBlock(par[u]); 84 | par[u] = child; 85 | comp[u] = root; 86 | child = u; 87 | u = p; 88 | } 89 | rank[root] = rank[child]; 90 | } 91 | 92 | void mergePath(int u, int v) 93 | { 94 | ++timer; 95 | ArrayList uPath = new ArrayList<>(1); 96 | ArrayList vPath = new ArrayList<>(1); 97 | 98 | int lca = -1; 99 | while(true) 100 | { 101 | if(u != -1) 102 | { 103 | uPath.add(u); 104 | if(time[u] == timer) { lca = u; break; } 105 | 106 | time[u] = timer; 107 | u = getBlock(par[u]); 108 | } 109 | 110 | if(v != -1) 111 | { 112 | vPath.add(v); 113 | if(time[v] == timer) { lca = v; break; } 114 | time[v] = timer; 115 | v = getBlock(par[v]); 116 | } 117 | } 118 | 119 | for(int x: uPath) 120 | { 121 | block[x] = lca; 122 | if(x == lca) break; 123 | --bridges; 124 | } 125 | 126 | for(int x: vPath) 127 | { 128 | block[x] = lca; 129 | if(x == lca) break; 130 | --bridges; 131 | } 132 | } 133 | } -------------------------------------------------------------------------------- /geometry/Polygon.java: -------------------------------------------------------------------------------- 1 | package geometry; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Polygon { 6 | // Cases to handle: collinear points, polygons with n < 3 7 | 8 | static final double EPS = 1e-9; 9 | 10 | Point[] g; //first point = last point, counter-clockwise representation 11 | 12 | Polygon(Point[] o) { g = o; } 13 | 14 | double perimeter() 15 | { 16 | double sum = 0.0; 17 | for(int i = 0; i < g.length - 1; ++i) 18 | sum += g[i].dist(g[i+1]); 19 | return sum; 20 | } 21 | 22 | double area() //clockwise/anti-clockwise check, for convex/concave polygons 23 | { 24 | double area = 0.0; 25 | for(int i = 0; i < g.length - 1; ++i) 26 | area += g[i].x * g[i+1].y - g[i].y * g[i+1].x; 27 | return Math.abs(area) / 2.0; //negative value in case of clockwise 28 | } 29 | 30 | boolean isConvex() 31 | { 32 | if(g.length <= 3) // point or line 33 | return false; 34 | boolean ccw = Point.ccw(g[g.length - 2], g[0], g[1]); //edit ccw check to accept collinear points 35 | for(int i = 1; i < g.length - 1; ++i) 36 | if(Point.ccw(g[i-1], g[i], g[i+1]) != ccw) 37 | return false; 38 | return true; 39 | } 40 | 41 | boolean inside(Point p) //for convex/concave polygons - winding number algorithm 42 | { 43 | double sum = 0.0; 44 | for(int i = 0; i < g.length - 1; ++i) 45 | { 46 | double angle = Point.angle(g[i], p, g[i+1]); 47 | if((Math.abs(angle) < EPS || Math.abs(angle - Math.PI) < EPS) && p.between(g[i], g[i+1])) 48 | return true; 49 | if(Point.ccw(p, g[i], g[i+1])) 50 | sum += angle; 51 | else 52 | sum -= angle; 53 | } 54 | 55 | return Math.abs(2 * Math.PI - Math.abs(sum)) < EPS; //abs makes it work for clockwise 56 | } 57 | /* 58 | * Another way if the polygon is convex 59 | * 1. Triangulate the poylgon through p 60 | * 2. Check if sum areas == poygon area 61 | * 3. Handle empty polygon 62 | */ 63 | 64 | Polygon cutPolygon(Point a, Point b) //returns the left part of the polygon, swap a & b for the right part 65 | { 66 | Point[] ans = new Point[g.length<<1]; 67 | Line l = new Line(a, b); 68 | Vector v = new Vector(a, b); 69 | 70 | int size = 0; 71 | for(int i = 0; i < g.length; ++i) 72 | { 73 | double left1 = v.cross(new Vector(a, g[i])); 74 | double left2 = i == g.length - 1 ? 0 : v.cross(new Vector(a, g[i+1])); 75 | 76 | if(left1 + EPS > 0) 77 | ans[size++] = g[i]; 78 | if(left1 * left2 + EPS < 0) 79 | ans[size++] = l.intersect(new Line(g[i], g[i+1])); 80 | } 81 | 82 | if(size != 0 && ans[0] != ans[size-1]) //necessary in case g[0] is not in the new polygon 83 | ans[size++] = ans[0]; 84 | return new Polygon(Arrays.copyOf(ans, size)); 85 | } 86 | 87 | static Polygon convexHull(Point[] points) //all points are unique, remove duplicates, edit ccw to accept collinear points 88 | { 89 | int n = points.length; 90 | Arrays.sort(points); 91 | Point[] ans = new Point[n<<1]; 92 | int size = 0, start = 0; 93 | 94 | for(int i = 0; i < n; i++) 95 | { 96 | Point p = points[i]; 97 | while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; 98 | ans[size++] = p; 99 | } 100 | start = --size; 101 | 102 | for(int i = n-1 ; i >= 0 ; i--) 103 | { 104 | Point p = points[i]; 105 | while(size - start >= 2 && !Point.ccw(ans[size-2], ans[size-1], p)) --size; 106 | ans[size++] = p; 107 | } 108 | // if(size < 0) size = 0 for empty set of points 109 | return new Polygon(Arrays.copyOf(ans, size)); 110 | } 111 | 112 | Point centroid() //center of mass 113 | { 114 | double cx = 0.0, cy = 0.0; 115 | for(int i = 0; i < g.length - 1; i++) 116 | { 117 | double x1 = g[i].x, y1 = g[i].y; 118 | double x2 = g[i+1].x, y2 = g[i+1].y; 119 | 120 | double f = x1 * y2 - x2 * y1; 121 | cx += (x1 + x2) * f; 122 | cy += (y1 + y2) * f; 123 | } 124 | double area = area(); //remove abs 125 | cx /= 6.0 * area; 126 | cy /= 6.0 * area; 127 | return new Point(cx, cy); 128 | } 129 | } -------------------------------------------------------------------------------- /data_structures/TreapSet.java: -------------------------------------------------------------------------------- 1 | package data_structures; 2 | import java.util.Random; 3 | 4 | // TODO Needs Testing 5 | public class TreapSet > 6 | { 7 | class Node> 8 | { 9 | T key; 10 | Node left, right; 11 | int prior, size; 12 | 13 | Node(T k, int p, int s, Node l, Node r) 14 | { 15 | key = k; 16 | prior = p; 17 | size = s; 18 | left = l; 19 | right = r; 20 | } 21 | } 22 | 23 | Random rand = new Random(); 24 | Node nill = new Node(null, Integer.MAX_VALUE, 0, null, null); 25 | Node root = nill; 26 | 27 | Node balance(Node root) 28 | { 29 | if(root.left.prior < root.prior) 30 | return rotateRight(root); 31 | if(root.right.prior < root.prior) 32 | return rotateLeft(root); 33 | return root; 34 | } 35 | 36 | void delete(K key) { root = delete(key, root); } 37 | 38 | Node delete(K key, Node root) 39 | { 40 | if(root == nill) return nill; 41 | if(key.compareTo(root.key) < 0) 42 | { 43 | root.left = delete(key, root.left); 44 | update(root); 45 | return root; 46 | } 47 | if(key.compareTo(root.key) > 0) 48 | { 49 | root.right = delete(key, root.right); 50 | update(root); 51 | return root; 52 | } 53 | if(root.left == nill && root.right == nill) 54 | return nill; 55 | return delete(key, root.left.prior < root.right.prior? rotateRight(root):rotateLeft(root)); 56 | } 57 | 58 | int height() { return height(root); } 59 | 60 | int height(Node root) 61 | { 62 | if(root == null) return -1; 63 | return 1 + Math.max(height(root.left), height(root.right)); 64 | } 65 | 66 | int indexOf(K key) { return indexOf(key, root); } 67 | 68 | int indexOf(K key, Node root) 69 | { 70 | if(root == nill) return Integer.MIN_VALUE; 71 | 72 | if(key.compareTo(root.key) < 0) return indexOf(key, root.left); 73 | 74 | if(key.compareTo(root.key) > 0) return indexOf(key, root.right) + root.left.size + 1; 75 | 76 | return root.left.size; 77 | } 78 | 79 | void insert(K key) { root = insert(key, root); } 80 | 81 | Node insert(K key, Node root) 82 | { 83 | if(root == nill) return new Node(key, rand.nextInt(1<<30), 1, nill, nill); 84 | 85 | if(key.compareTo(root.key) < 0) 86 | root.left = insert(key, root.left); 87 | else 88 | if(key.compareTo(root.key) > 0) 89 | root.right = insert(key, root.right); 90 | update(root); 91 | return balance(root); 92 | } 93 | 94 | K keyOf(int index) { return keyOf(index, root);} 95 | 96 | K keyOf(int index, Node root) 97 | { 98 | if(root == nill) return null; 99 | if(index < root.left.size) 100 | return keyOf(index, root.left); 101 | if(index > root.left.size) 102 | return keyOf(index - root.left.size - 1, root.right); 103 | return root.key; 104 | } 105 | 106 | void print() 107 | { 108 | System.out.print("["); 109 | print(root); 110 | System.out.println("]"); 111 | } 112 | 113 | void print(Node rooot) 114 | { 115 | if(root == nill) return; 116 | print(root.left); 117 | System.out.println(" " + root.key); 118 | print(root.right); 119 | } 120 | 121 | Node rotateLeft(Node root) 122 | { 123 | Node T = root.right; 124 | root.right = T.left; 125 | T.left = root; 126 | update(T.left); 127 | update(T); 128 | return T; 129 | } 130 | 131 | Node rotateRight(Node root) 132 | { 133 | Node T = root.left; 134 | root.left = T.right; 135 | T.right = root; 136 | update(T.right); 137 | update(T); 138 | return T; 139 | } 140 | 141 | boolean search(K key) {return search(key, root); } 142 | 143 | boolean search(K key, Node root) 144 | { 145 | if(root == nill) return false; 146 | if(key.compareTo(root.key) < 0) 147 | return search(key, root.left); 148 | if(key.compareTo(root.key) > 0) 149 | return search(key, root.right); 150 | return true; 151 | } 152 | 153 | int size() { return root.size; } 154 | 155 | void update(Node root) 156 | { 157 | if(root != nill) 158 | root.size = root.left.size + 1 + root.right.size; 159 | } 160 | } -------------------------------------------------------------------------------- /curriculum/outlines/general/pupils_gpsets.md: -------------------------------------------------------------------------------- 1 | # [Pupils] General Problem Sets 2 | 3 | ### Problem Set 1 4 | | Problem | Tags | Notes | Solution | 5 | | :-----------: |:-------------| :---------|:--------------:| 6 | | [Asphalting Roads](http://codeforces.com/problemset/problem/583/A) | implementation | | [link](http://codeforces.com/contest/583/submission/14749293) | 7 | | [Interesting drink](http://codeforces.com/problemset/problem/706/B) | implementation | | [link](http://codeforces.com/contest/706/submission/19789121) | 8 | | [Grid Successors](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2628) | arrays | 2D array manipulation | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v115/GridSuccessors_UVa11581.java) | 9 | | [Chat Order](http://codeforces.com/problemset/problem/637/B) | treesets | | [link](http://codeforces.com/contest/637/submission/17594248) | 10 | | [Transmigration](http://codeforces.com/problemset/problem/105/A) | treemaps | | [link](http://codeforces.com/contest/105/submission/19847729) | 11 | 12 | ### Problem Set 2 13 | | Problem | Tags | Notes | Solution | 14 | | :-----------: |:-------------| :---------|:--------------:| 15 | | [Round House](http://codeforces.com/problemset/problem/659/A) | math, implementation | | [link](http://codeforces.com/contest/659/submission/17224376) | 16 | | [Spreadsheets](http://codeforces.com/problemset/problem/1/B) | math, implementation | | [link](http://codeforces.com/contest/1/submission/12257458) | 17 | | [A and B and Interesting Substrings](http://codeforces.com/problemset/problem/519/D) | treemaps | prefix sum | [link](http://codeforces.com/contest/519/submission/18131191) | 18 | | [Team Queue](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=481) | queues | | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v005/TeamQueue_UVa540.java) | 19 | | [Powers of Two](http://codeforces.com/problemset/problem/702/B) | treemaps, brute force | | [link](http://codeforces.com/contest/702/submission/19483223) | 20 | 21 | 22 | ### Problem Set 3 23 | | Problem | Tags | Notes | Solution | 24 | | :-----------: |:-------------| :---------|:--------------:| 25 | | [Cakeminator](http://codeforces.com/problemset/problem/330/A) | brute force, implementation | | [link](http://codeforces.com/contest/330/submission/11350645) | 26 | | [Beru-taxi](http://codeforces.com/problemset/problem/706/A) | geometry, brute force | | [link](http://codeforces.com/contest/706/submission/19787899) | 27 | | [Rotated square](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1796) | arrays | 2D array manipulation | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v108/RotatedSquare_UVa10855.java) | 28 | | [Back to the 8-Queens](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2026) | brute force | backtracking | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v110/BackToThe8Queens_UVa11085.java) | 29 | | [Vasya and Types easy](http://codeforces.com/problemset/problem/87/B) | tree/hashmaps | | [link](http://codeforces.com/contest/87/submission/20625216) | 30 | 31 | 32 | ### Problem Set 4 33 | | Problem | Tags | Notes | Solution | 34 | | :-----------: |:-------------| :---------|:--------------:| 35 | | [Queue](http://codeforces.com/problemset/problem/545/D) | greedy | sortings | [link](http://codeforces.com/contest/545/submission/12347250) | 36 | | [Books](http://codeforces.com/problemset/problem/279/B) | binary search, two pointers | | [link](http://codeforces.com/contest/279/submission/15561797) | 37 | | [The Lonesome Cargo Distributor](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1113) | queues | | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v101/TheLonesomeCargoDistributor_UVa10172.java) | 38 | | [T-Shirt Hunt](http://codeforces.com/contest/807/problem/B) | brute force | Get the limit from the mod cycle | [link](http://codeforces.com/contest/807/submission/26964245) | 39 | | [Cooking Time](http://codeforces.com/problemset/gymProblem/101498/F) | greedy | | [link](https://ideone.com/kbc7TV) | 40 | 41 | -------------------------------------------------------------------------------- /curriculum/outlines/solving_techniques/greedy.md: -------------------------------------------------------------------------------- 1 | # Greedy 2 | --- 3 | ## Outline 4 | 1. What is Greedy 5 | - Example: Activity-Selection problem 6 | 2. Greedy Properties 7 | - Greedy-choice property 8 | - Optimal Sub-structure 9 | 3. Classical Examples 10 | - Sortings: [Dragon of Loowater](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2267) 11 | - Interval Covering: [Watering Grass](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1323) 12 | - Huffman Coding: [Add All](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1895) 13 | 4. Greedy failure 14 | - Example: greedy coin change vs general coin change. 15 | 16 | ## Material Resources 17 | | Resource | Points Covered | 18 | |:------------------------- |:--------------------------------| 19 | | CLRS 16.1, 16.2 | 1, 2: greedy concepts | 20 | | CP Section 3.4 | 3: greedy failure | 21 | | [ACP](https://www.youtube.com/watch?v=iXxP_liQklk&list=PLPt2dINI2MIbJYBTHmRuZuGLIP5PnkzMH) | extra | 22 | | [Topcoder](https://www.topcoder.com/community/data-science/data-science-tutorials/greedy-is-good/) | extra | 23 | --- 24 | ## Problem Sets 25 | 26 | ### Problem Set #1 27 | 28 | | Problem | Tags | Notes | Solution | 29 | |:------------- |:-------------|:-----|:--------| 30 | | [All in All](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1281) | | greedy choice: for each char in _t_, match with leftmost valid char in _s_ | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v103/AllInAll_UVa10340.java) | 31 | |[Boiled Eggs](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3051)|| gc: pick the lightest egg first |[link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v119/BoiledEggs_UVa11900.java)| 32 | | [Scarecrow](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3836) | | gc: put scarecrows from left to right each covering an uncovered range without leaving cells empty | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v124/Scarecrow_UVa12405.java) | 33 | | [Dragons](http://codeforces.com/contest/230/submission/11367857) | sortings | gc: kill weakest dragons first | [link](http://codeforces.com/contest/230/submission/11367857) | 34 | | [Jeopardy!](http://codeforces.com/problemset/problem/413/C) | sortings | gc: answer regular questions first, then auction questions from larger to smaller | [link](http://codeforces.com/contest/413/submission/24717142) | 35 | | [Gas Stations](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=3743) | | interval covering | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/3d54f533edc19cce6bf4406ee6934a571c11fcaf/v123/GasStations_12321.java)| 36 | 37 | 38 | 39 | 40 | ### Problem Set #2 41 | | Problem | Tags | Notes | Solution | 42 | |:------------- |:-------------|:-----|:-------| 43 | | [Ants](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1655) | | change your point of view! | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v107/Ants_UVa10714.java) | 44 | | [Fill the Square](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2515) | | gc: start with smallest char first | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v115/FillTheSquare_UVa11520.java) | 45 | | [Short Story Competition](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=3926) | | gc: make each line as full as possible | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v124/ShortStoryCompetition_UVa12482.java) | 46 | |[Shoemaker's Problem](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=967)|| greedy selection for only 2 items. For n items, sort using the pairwise selection! |[link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v100/ShoemakersProblem_UVa10026.java)| 47 | | [Dynamic Frog](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2098) | | gc: skip the first small rock | [link](https://github.com/Diusrex/UVA-Solutions/blob/master/11157%20Dynamic%20Frog.cpp) | 48 | -------------------------------------------------------------------------------- /curriculum/outlines/getting_started/io_tutorial.md: -------------------------------------------------------------------------------- 1 | # Java I/O Guide 2 | 3 | The contract between the problem solver and the online judge is based on taking the input and writing the output in specific formats. 4 | 5 | ### Input Reading 6 | 7 | - The main two input readers in java are: 8 | 1. Scanner 9 | ```java 10 | Scanner sc = new Scanner(System.in); 11 | // available methods: nextLine(), next(), nextInt(), nextLong(). See java docs for what they return. 12 | ``` 13 | 2. BufferedReader 14 | ```java 15 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 16 | // available method: readLine(). Equivalent to nextLine() in Scanner. 17 | ``` 18 | - If we have an input that looks like: 19 | ``` 20 | 1 3 21 | 100000000000 22 | myString 23 | ``` 24 | Using Scanner, you can parse it as follows: 25 | ```java 26 | int x = sc.nextInt(), y = sc.nextInt(); 27 | long z = sc.nextLong(); 28 | String s = sc.next(); 29 | ``` 30 | 31 | Using BufferedReader, you can parse it as follows: 32 | ``` 33 | StringTokenizer st = new StringTokenizer(br.readLine()); 34 | int x = Integer.parseInt(st.nextToken()); 35 | int y = Integer.parseInt(st.nextToken()); 36 | long z = Long.parseLong(br.readLine()); 37 | String s = br.readLine(); 38 | ``` 39 | 40 | - The judge runs the code against test cases using input files. The problem statement must specify how the input file will look like. Common input file formats are: 41 | 1. The file consists of one or more test cases where the number of test cases is given on the first line of the file. 42 | 2. The file consists of multiple test cases and there will be a character that indicates the end of file. For example, a line containing a single `0`. In such case, you should terminate immediately and stop reading any more input. 43 | 3. The file consists of multiple test cases and nothing to indicate the end of file. In such case, you have to read till *End Of File (EOF)* (the file has no more lines to read). You can check EOF in multiple ways: 44 | - Read a new line (`sc.nextLine()` or `br.readLine()`) and if the returned value is `null`, then you reached EOF. 45 | - Use input readers functions such as `br.ready()` or `sc.hasNext()` which returns false if EOF is reached. 46 | 47 | - BufferedReader is much more faster than Scanner. Only use the Scanner in case of small inputs (n < 1e5). 48 | - You can implement your own Scanner class to help you get rid of the tedious syntax of using the BufferedReader and the StringTokenizer. This class will have a BufferedReader and a StringTokenizer as its instance variables and some methods similar to that of a Scanner (`nextInt()`, `ready()`,...). 49 | 50 | ### Output Formatting 51 | - Three ways to print the output: 52 | 1. `System.out.println()`: slow a little bit (because every print statement flushes to the output file) 53 | 2. PrintWriter: faster 54 | ```java 55 | PrintWriter out = new PrintWriter(System.out); 56 | out.println("hello"); // it has the same functions as System.out (print(), println(), printf()) 57 | out.flush(); // you have to flush only once at the end of your code. Did you get why it is faster ;) ? 58 | ``` 59 | 3. StringBuilder: fast as PrintWriter 60 | ```java 61 | StringBuilder sb = new StringBuilder(); 62 | sb.append("hello").append("\n"); 63 | System.out.print(sb); 64 | ``` 65 | - Some examples to efficiently format your output: 66 | - Print [`7`, `days`, `24`] space-separated on a single line where `24` should have exactly 5 decimal places. 67 | ```java 68 | out.printf("%d %s %.5f\n", 7, "days", 24); 69 | ``` 70 | - Print strings = [`hello`, `world`, `I'm here!`] each on a separate line. 71 | ```java 72 | for(String s: strings) 73 | out.println(s); 74 | ``` 75 | - Print strings = [`hello`, `world`, `I'm here!`] each on a separate line and each followed by a blank line. 76 | ```java 77 | for(String s: strings) { 78 | out.println(s); 79 | out.println(); 80 | } 81 | ``` 82 | 83 | - Print strings = [`hello`, `world`, `I'm here!`] each on a separate line. Separate them with blank lines. 84 | ```java 85 | boolean first = true; 86 | for(String s: strings) { 87 | if(first) 88 | first = false; 89 | else 90 | out.println(); 91 | out.println(s); 92 | } 93 | ``` 94 | -------------------------------------------------------------------------------- /curriculum/outlines/data_structures/nonlinear_ds.md: -------------------------------------------------------------------------------- 1 | # Non-Linear DS 2 | --- 3 | ## Outline 4 | 1. Balanced Binary Search Tree (Java TreeMap/TreeSet) 5 | 1. Difference between a map and a set. 6 | 2. Creating TreeMaps and TreeSets. 7 | 3. Important functions and their complexities: 8 | * `add, remove, contains, get` 9 | 4. Core idea behind TreeMap/Set (BBST). 10 | 5. Traversing a TreeMap, TreeSet. 11 | 6. Creating a comparator for an object to be the key in a TreeMap/Set. 12 | 13 | 2. Heap (Java PriorityQueue) 14 | 1. Creating PriorityQueues. 15 | 2. Important functions and their complexities: 16 | * `add, remove, peek` 17 | 3. Core idea behing PriorityQueues (Heap). 18 | 3. Creating a comparator for the objects inserted in PriorityQueue. 19 | 20 | 3. Hash Table (Java HashMap/HashSet) 21 | 1. Creating HashMaps and HashSets. 22 | 2. Important functions and their complexities (same as TreeMaps/TreeSets). 23 | 3. Traversing HashMap, HashSet. 24 | 4. HashMap/Set vs TreeMap/Set. 25 | 5. Creating Hash functions and avoiding collisions. 26 | 27 | --- 28 | ## Material Resources 29 | | Resource | Points Covered | 30 | |:------------------------- |:--------------------------------| 31 | |CP section: 2.3 | Most of the outline points | 32 | |[HE Heaps and Priority Queues](https://www.hackerearth.com/practice/data-structures/trees/heapspriority-queues/tutorial/) | 2 | 33 | | [Article: TreeMaps vs HashMaps](https://dzone.com/articles/hashmap-vs-treemap-vs)| 1-vi, 3-iii | 34 | |[HE Hashing basics](https://www.hackerearth.com/practice/data-structures/hash-tables/basics-of-hash-tables/tutorial/) | 3-iv | 35 | | Book: Effective Java (item 9)| 3-iv: tricks for designing hash functions | 36 | --- 37 | ## Problem Sets 38 | ### Problem Set #1 39 | 40 | | Problem | Tags | Notes | Solution | 41 | |:------------- |:-------------|:-----|:--------| 42 | | [Andy's First Dictionary](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1756) | Hash/Treeset | input parsing , sort output | [Link](https://ideone.com/haO0a1) | 43 | | [Add All](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1895) | Priority Queues | better to add the smallest numbers first | [Link](https://ideone.com/2aHcCe) | 44 | | [Updating a Dictionary](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3948) | TreeMap | _ | [Link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v125/UpdatingADictionary_UVa12504.java) | 45 | | [Word Index](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=358) | TreeMaps, Queues | generating all indices with queues and storing results in a map | [Link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v004/WordIndex_UVa417.java) | 46 | | [Argus](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=3644) | Priority Queue | - | [Link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v012/Argus_UVa1203.java) | 47 | 48 | ### Problem Set #2 49 | 50 | | Problem | Tags | Notes | Solution | 51 | |:------------- |:-------------|:-----|:--------| 52 | | [Hay Points](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=631&page=show_problem&problem=1236) | TreeMap | _ | [Link](https://ideone.com/w1Onpp) | 53 | | [I Can Guess the Data Structure](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3146) | Queues,Stacks,Priority Queues | simulate the operation using the required data structures | [Link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v119/ICanGuessTheDataStructure_UVa11995.java) | 54 | | [CD](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2949) | Hash/TreeSet | _ | [Link](https://ideone.com/hJPndm) | 55 | | [Andy's Second Dictionary](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2003) | TreeSet | _ | [Link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v110/AndysSecondDicitionary_UVa11062.java) | 56 | | [Conformity](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2261) | TreeMap | _ | [Link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v112/Conformity_UVa11286.java) | 57 | -------------------------------------------------------------------------------- /curriculum/outlines/general/specialists_gpsets.md: -------------------------------------------------------------------------------- 1 | # [Specialists] General Problem Sets 2 | 3 | ### Problem Set 1 4 | | Problem | Tags | Notes | Solution | 5 | | :-----------: |:-------------| :---------|:--------------:| 6 | | [Dart-a-Mania](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=676) | brute force | | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v007/Dart_a_Mania_Uva735.java) | 7 | | [Hartals](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=991) | arrays | 1D array manipulation | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v100/Hartals_UVa10050.java) | 8 | | [One-Dimensional Battle Ships](http://codeforces.com/problemset/problem/567/D) | binary search | | [link](http://codeforces.com/contest/567/submission/21917226) | 9 | | [Where Are My Flakes?](http://codeforces.com/problemset/problem/60/A) | BitSets | | [link](http://codeforces.com/contest/60/submission/20737644) | 10 | | [Parallel Programming](http://codeforces.com/problemset/problem/291/D) | greedy | | [link](http://codeforces.com/contest/291/submission/23805317) | 11 | 12 | 13 | ### Problem Set 2 14 | | Problem | Tags | Notes | Solution | 15 | | :-----------: |:-------------| :---------|:--------------:| 16 | | [Igor In the Museum](http://codeforces.com/problemset/problem/598/D) | graphs | connected components, grids | [link](http://codeforces.com/contest/598/submission/23584149) | 17 | | [Banana](http://codeforces.com/problemset/problem/335/A) | strings | frequency count | [link](http://codeforces.com/contest/335/submission/24534338) | 18 | | [Movie Critics](http://codeforces.com/problemset/problem/250/C) | greedy | | [link](http://codeforces.com/contest/250/submission/19828933) | 19 | | [Anton and Lines](http://codeforces.com/problemset/problem/593/B) | geometry | sortings | [link](http://codeforces.com/contest/593/submission/16721050) | 20 | | [The problem of the crazy linguist](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2142) | brute force | backtracking, preprocessing | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v112/TheProblemOfTheCrazyLinguist_UVa11201.java) | 21 | 22 | 23 | 24 | ### Problem Set 3 25 | | Problem | Tags | Notes | Solution | 26 | | :-----------: |:-------------| :---------|:--------------:| 27 | | [Vasya and Robot](http://codeforces.com/problemset/problem/354/A) | greedy | cumulative sum, brute force | [link](http://codeforces.com/contest/354/submission/19308609) | 28 | | [GukiZ hates Boxes](http://codeforces.com/problemset/problem/551/C) | binary search | greedy predicate | [link](http://codeforces.com/contest/551/submission/28690098) | 29 | | [Is There A Second Way Left?](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1403) | graphs | 2nd mst | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/master/v104/IsThereASecondWayLeft_UVa10462.java) | 30 | | [Light and Transparencies](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=778) | geometry | | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/1b9963e051c2a4ed4f11b33dc9bbdb60466e81f1/v008/LightAndTransparencies_UVa837.java) | 31 | | [Network](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3505) | brute force | permutation, simulation | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/3d54f533edc19cce6bf4406ee6934a571c11fcaf/v003/Network_UVa315.java) | 32 | 33 | 34 | ### Problem Set 4 35 | | Problem | Tags | Notes | Solution | 36 | | :-----------: |:-------------| :---------|:--------------:| 37 | | [Anagram](http://codeforces.com/problemset/problem/254/C) | strings, greedy | | [link](http://codeforces.com/contest/254/submission/29208751) | 38 | | [Planets](http://codeforces.com/problemset/problem/229/B) | graphs | dijkstra, binary search, sets | [link](http://codeforces.com/contest/229/submission/28647246) | 39 | | [Marathon](http://codeforces.com/problemset/problem/404/B) | math | modular arithmetic | [link](http://codeforces.com/contest/404/submission/25475389) | 40 | | [Robot Challenge](https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=3691) | DP | geometry, SSSP on DAG | [link](https://github.com/AhmadElsagheer/UVa-Solutions/blob/1b9963e051c2a4ed4f11b33dc9bbdb60466e81f1/v012/RobotChallenge_UVa1250.java) | 41 | | [Bulls and Cows](http://codeforces.com/problemset/problem/63/C) | brute force | | [link](http://codeforces.com/contest/63/submission/20334184) | 42 | -------------------------------------------------------------------------------- /graphs/traversal/GraphTraversal.java: -------------------------------------------------------------------------------- 1 | package graphs.traversal; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.Queue; 6 | import java.util.Stack; 7 | 8 | public class GraphTraversal { 9 | 10 | static final int VISITED = 2, EXPLORED = 1, UNVISITED = 0; 11 | static ArrayList[] adjList; 12 | static boolean[] visited, adjMat[]; 13 | static int V; 14 | 15 | public void preTraversal() 16 | { 17 | for(int i = 0; i < V; ++i) //for non-connected graphs, Spanning Forest 18 | if(!visited[i]) 19 | dfs(i); //or bfs(i) 20 | } 21 | 22 | /* 23 | * 1.Depth-First Search (DFS) 24 | */ 25 | static void dfs(int u) //O(V + E) adjList, O(V^2) adjMat 26 | { 27 | visited[u] = true; 28 | 29 | //for adjacency list 30 | for(int v: adjList[u]) 31 | if(!visited[v]) 32 | dfs(v); 33 | 34 | //for adjacency matrix 35 | for(int i = 0; i < V; ++i) 36 | if(adjMat[u][i] && !visited[i]) 37 | dfs(i); 38 | } 39 | 40 | /* 41 | * 2.Breadth-First Search (BFS) 42 | */ 43 | static void bfs(int s, int t) 44 | { 45 | Queue q = new LinkedList(); 46 | q.add(s); 47 | visited[s] = true; 48 | while(!q.isEmpty()) 49 | { 50 | int u = q.remove(); 51 | 52 | for(int v: adjList[u]) 53 | if(!visited[v]) 54 | { 55 | visited[v] = true; 56 | q.add(v); 57 | } 58 | } 59 | } 60 | 61 | /* 62 | * 3.Types of Edges 63 | */ 64 | static int[] parent, status; 65 | static void edgeType(int u) 66 | { 67 | status[u] = EXPLORED; 68 | for(int v: adjList[u]) 69 | if(status[v] == UNVISITED) 70 | { 71 | System.out.printf("Edge from %d to %d is %s%n", u, v, "tree edge"); 72 | parent[v] = u; 73 | edgeType(v); 74 | } 75 | else 76 | if(status[v] == VISITED) //cross edges only occur in directed graph 77 | System.out.printf("Edge from %d to %d is %s%n", u, v, "forwad/cross edge"); 78 | else 79 | if(parent[u] == v) 80 | System.out.printf("Edge from %d to %d is %s%n", u, v, "bidirectional edge"); 81 | else 82 | { 83 | System.out.printf("Edge from %d to %d is %s%n", u, v, "back edge"); 84 | System.out.println("Cycle!"); 85 | } 86 | status[u] = VISITED; 87 | } 88 | 89 | /* 90 | * 4.Bipartite Graph Check 91 | */ 92 | static int[] color; 93 | static boolean bipartitieCheck(int u) 94 | { 95 | for(int v: adjList[u]) 96 | if(color[v] == -1) 97 | { 98 | color[v] = 1 ^ color[u]; 99 | if(!bipartitieCheck(v)) 100 | return false; 101 | } 102 | else 103 | if(color[v] == color[u]) 104 | return false; 105 | return true; 106 | } 107 | 108 | /* 109 | * 5.Flood Fill in Grids - Maze Problem (Reach (R-1, C-1) from (0, 0) using empty cells '.' only) 110 | */ 111 | static char[][] grid; 112 | static int R, C; 113 | static int[] dx = new int[]{-1, 1, 0, 0}; 114 | static int[] dy = new int[]{0, 0, -1, 1}; 115 | 116 | static boolean valid(int i, int j) 117 | { 118 | return i != -1 && j != -1 && i != R && j != C && grid[i][j] == '.'; 119 | } 120 | 121 | static void dfs2(int i, int j) 122 | { 123 | grid[i][j] = 'X'; //mark as visited 124 | for(int k = 0; k < 4; ++k) 125 | { 126 | int x = i + dx[k], y = j + dy[k]; 127 | if(valid(x, y) && grid[x][y] != 'X') 128 | dfs2(x, y); 129 | } 130 | } 131 | 132 | /* 133 | * 6.Topological Sort 134 | */ 135 | static Stack stack = new Stack(); 136 | static void toposortDFS(int u) //don't forget preTraversal 137 | { 138 | visited[u] = true; 139 | 140 | for(int v: adjList[u]) 141 | if(!visited[v]) //if v is explored -> failure, not a DAG! 142 | dfs(v); 143 | stack.push(u); 144 | } 145 | 146 | static ArrayList sortedArray; 147 | static void toposortBFS() 148 | { 149 | int[] p = new int[V]; 150 | sortedArray = new ArrayList(V); 151 | for(int i = 0; i < V; ++i) 152 | for(int v: adjList[i]) 153 | ++p[v]; 154 | Queue roots = new LinkedList(); //PriorityQueue for smallest lexiographical sorting 155 | 156 | for(int i = 0; i < V; ++i) 157 | if(p[i] == 0) 158 | roots.add(i); 159 | while(!roots.isEmpty()) 160 | { 161 | int u = roots.remove(); 162 | sortedArray.add(u); 163 | for(int v: adjList[u]) 164 | if(--p[v] == 0) 165 | roots.add(v); 166 | } 167 | 168 | //if p contains non-zero values -> failure, not a DAG! 169 | } 170 | } 171 | --------------------------------------------------------------------------------