problem
stringlengths
1.19k
65.4k
solution
stringlengths
1.19k
67.5k
topic
stringlengths
5
80
--- title intersecting_segments --- # Search for a pair of intersecting segments Given $n$ line segments on the plane. It is required to check whether at least two of them intersect with each other. If the answer is yes, then print this pair of intersecting segments; it is enough to choose any of them among several ...
--- title intersecting_segments --- # Search for a pair of intersecting segments Given $n$ line segments on the plane. It is required to check whether at least two of them intersect with each other. If the answer is yes, then print this pair of intersecting segments; it is enough to choose any of them among several ...
Search for a pair of intersecting segments
--- title segments_intersection_checking --- # Check if two segments intersect You are given two segments $(a, b)$ and $(c, d)$. You have to check if they intersect. Of course, you may find their intersection and check if it isn't empty, but this can't be done in integers for segments with integer coordinates. The a...
--- title segments_intersection_checking --- # Check if two segments intersect You are given two segments $(a, b)$ and $(c, d)$. You have to check if they intersect. Of course, you may find their intersection and check if it isn't empty, but this can't be done in integers for segments with integer coordinates. The a...
Check if two segments intersect
--- title - Original --- # Convex hull trick and Li Chao tree Consider the following problem. There are $n$ cities. You want to travel from city $1$ to city $n$ by car. To do this you have to buy some gasoline. It is known that a liter of gasoline costs $cost_k$ in the $k^{th}$ city. Initially your fuel tank is emp...
--- title - Original --- # Convex hull trick and Li Chao tree Consider the following problem. There are $n$ cities. You want to travel from city $1$ to city $n$ by car. To do this you have to buy some gasoline. It is known that a liter of gasoline costs $cost_k$ in the $k^{th}$ city. Initially your fuel tank is emp...
Convex hull trick and Li Chao tree
--- title - Original --- # Basic Geometry In this article we will consider basic operations on points in Euclidean space which maintains the foundation of the whole analytical geometry. We will consider for each point $\mathbf r$ the vector $\vec{\mathbf r}$ directed from $\mathbf 0$ to $\mathbf r$. Later we will n...
--- title - Original --- # Basic Geometry In this article we will consider basic operations on points in Euclidean space which maintains the foundation of the whole analytical geometry. We will consider for each point $\mathbf r$ the vector $\vec{\mathbf r}$ directed from $\mathbf 0$ to $\mathbf r$. Later we will n...
Basic Geometry
--- title circles_intersection --- # Circle-Circle Intersection You are given two circles on a 2D plane, each one described as coordinates of its center and its radius. Find the points of their intersection (possible cases: one or two points, no intersection or circles coincide). ## Solution Let's reduce this prob...
--- title circles_intersection --- # Circle-Circle Intersection You are given two circles on a 2D plane, each one described as coordinates of its center and its radius. Find the points of their intersection (possible cases: one or two points, no intersection or circles coincide). ## Solution Let's reduce this prob...
Circle-Circle Intersection
--- title segments_intersection --- # Finding intersection of two segments You are given two segments AB and CD, described as pairs of their endpoints. Each segment can be a single point if its endpoints are the same. You have to find the intersection of these segments, which can be empty (if the segments don't int...
--- title segments_intersection --- # Finding intersection of two segments You are given two segments AB and CD, described as pairs of their endpoints. Each segment can be a single point if its endpoints are the same. You have to find the intersection of these segments, which can be empty (if the segments don't int...
Finding intersection of two segments
--- title convex_hull_graham --- # Convex Hull construction In this article we will discuss the problem of constructing a convex hull from a set of points. Consider $N$ points given on a plane, and the objective is to generate a convex hull, i.e. the smallest convex polygon that contains all the given points. We w...
--- title convex_hull_graham --- # Convex Hull construction In this article we will discuss the problem of constructing a convex hull from a set of points. Consider $N$ points given on a plane, and the objective is to generate a convex hull, i.e. the smallest convex polygon that contains all the given points. We w...
Convex Hull construction
--- title voronoi_diagram_2d_n4 --- # Delaunay triangulation and Voronoi diagram Consider a set $\{p_i\}$ of points on the plane. A **Voronoi diagram** $V(\{p_i\})$ of $\{p_i\}$ is a partition of the plane into $n$ regions $V_i$, where $V_i = \{p\in\mathbb{R}^2;\ \rho(p, p_i) = \min\ \rho(p, p_k)\}$. The cells of th...
--- title voronoi_diagram_2d_n4 --- # Delaunay triangulation and Voronoi diagram Consider a set $\{p_i\}$ of points on the plane. A **Voronoi diagram** $V(\{p_i\})$ of $\{p_i\}$ is a partition of the plane into $n$ regions $V_i$, where $V_i = \{p\in\mathbb{R}^2;\ \rho(p, p_i) = \min\ \rho(p, p_k)\}$. The cells of th...
Delaunay triangulation and Voronoi diagram
--- title nearest_points --- # Finding the nearest pair of points ## Problem statement Given $n$ points on the plane. Each point $p_i$ is defined by its coordinates $(x_i,y_i)$. It is required to find among them two such points, such that the distance between them is minimal: $$ \min_{\scriptstyle i, j=0 \ldots n-...
--- title nearest_points --- # Finding the nearest pair of points ## Problem statement Given $n$ points on the plane. Each point $p_i$ is defined by its coordinates $(x_i,y_i)$. It is required to find among them two such points, such that the distance between them is minimal: $$ \min_{\scriptstyle i, j=0 \ldots n-...
Finding the nearest pair of points
--- title: Point location in O(log n) title - Original --- # Point location in $O(log n)$ Consider the following problem: you are given a [planar subdivision](https://en.wikipedia.org/wiki/Planar_straight-line_graph) without no vertices of degree one and zero, and a lot of queries. Each query is a point, for which w...
--- title: Point location in O(log n) title - Original --- # Point location in $O(log n)$ Consider the following problem: you are given a [planar subdivision](https://en.wikipedia.org/wiki/Planar_straight-line_graph) without no vertices of degree one and zero, and a lot of queries. Each query is a point, for which w...
Point location in $O(log n)$
--- title: Finding faces of a planar graph title facets --- # Finding faces of a planar graph Consider a graph $G$ with $n$ vertices and $m$ edges, which can be drawn on a plane in such a way that two edges intersect only at a common vertex (if it exists). Such graphs are called **planar**. Now suppose that we are gi...
--- title: Finding faces of a planar graph title facets --- # Finding faces of a planar graph Consider a graph $G$ with $n$ vertices and $m$ edges, which can be drawn on a plane in such a way that two edges intersect only at a common vertex (if it exists). Such graphs are called **planar**. Now suppose that we are gi...
Finding faces of a planar graph
--- title pick_grid_theorem --- # Pick's Theorem A polygon without self-intersections is called lattice if all its vertices have integer coordinates in some 2D grid. Pick's theorem provides a way to compute the area of this polygon through the number of vertices that are lying on the boundary and the number of verti...
--- title pick_grid_theorem --- # Pick's Theorem A polygon without self-intersections is called lattice if all its vertices have integer coordinates in some 2D grid. Pick's theorem provides a way to compute the area of this polygon through the number of vertices that are lying on the boundary and the number of verti...
Pick's Theorem
--- title oriented_area --- # Oriented area of a triangle Given three points $p_1$, $p_2$ and $p_3$, calculate an oriented (signed) area of a triangle formed by them. The sign of the area is determined in the following way: imagine you are standing in the plane at point $p_1$ and are facing $p_2$. You go to $p_2$ an...
--- title oriented_area --- # Oriented area of a triangle Given three points $p_1$, $p_2$ and $p_3$, calculate an oriented (signed) area of a triangle formed by them. The sign of the area is determined in the following way: imagine you are standing in the plane at point $p_1$ and are facing $p_2$. You go to $p_2$ an...
Oriented area of a triangle
--- title: Check if point belongs to the convex polygon in O(log N) title pt_in_polygon --- # Check if point belongs to the convex polygon in $O(\log N)$ Consider the following problem: you are given a convex polygon with integer vertices and a lot of queries. Each query is a point, for which we should determine whet...
--- title: Check if point belongs to the convex polygon in O(log N) title pt_in_polygon --- # Check if point belongs to the convex polygon in $O(\log N)$ Consider the following problem: you are given a convex polygon with integer vertices and a lot of queries. Each query is a point, for which we should determine whet...
Check if point belongs to the convex polygon in $O(\log N)$
--- title lines_intersection --- # Intersection Point of Lines You are given two lines, described via the equations $a_1 x + b_1 y + c_1 = 0$ and $a_2 x + b_2 y + c_2 = 0$. We have to find the intersection point of the lines, or determine that the lines are parallel. ## Solution If two lines are not parallel, the...
--- title lines_intersection --- # Intersection Point of Lines You are given two lines, described via the equations $a_1 x + b_1 y + c_1 = 0$ and $a_2 x + b_2 y + c_2 = 0$. We have to find the intersection point of the lines, or determine that the lines are parallel. ## Solution If two lines are not parallel, the...
Intersection Point of Lines
--- title - Original --- # Half-plane intersection In this article we will discuss the problem of computing the intersection of a set of half-planes. Such an intersection can be conveniently represented as a convex region/polygon, where every point inside of it is also inside all of the half-planes, and it is this ...
--- title - Original --- # Half-plane intersection In this article we will discuss the problem of computing the intersection of a set of half-planes. Such an intersection can be conveniently represented as a convex region/polygon, where every point inside of it is also inside all of the half-planes, and it is this ...
Half-plane intersection
--- title circle_tangents --- # Finding common tangents to two circles Given two circles. It is required to find all their common tangents, i.e. all such lines that touch both circles simultaneously. The described algorithm will also work in the case when one (or both) circles degenerate into points. Thus, this alg...
--- title circle_tangents --- # Finding common tangents to two circles Given two circles. It is required to find all their common tangents, i.e. all such lines that touch both circles simultaneously. The described algorithm will also work in the case when one (or both) circles degenerate into points. Thus, this alg...
Finding common tangents to two circles
--- title: Finding area of simple polygon in O(N) title polygon_area --- # Finding area of simple polygon in $O(N)$ Let a simple polygon (i.e. without self intersection, not necessarily convex) be given. It is required to calculate its area given its vertices. ## Method 1 This is easy to do if we go through all edg...
--- title: Finding area of simple polygon in O(N) title polygon_area --- # Finding area of simple polygon in $O(N)$ Let a simple polygon (i.e. without self intersection, not necessarily convex) be given. It is required to calculate its area given its vertices. ## Method 1 This is easy to do if we go through all edg...
Finding area of simple polygon in $O(N)$
--- title circle_line_intersection --- # Circle-Line Intersection Given the coordinates of the center of a circle and its radius, and the equation of a line, you're required to find the points of intersection. ## Solution Instead of solving the system of two equations, we will approach the problem geometrically. T...
--- title circle_line_intersection --- # Circle-Line Intersection Given the coordinates of the center of a circle and its radius, and the equation of a line, you're required to find the points of intersection. ## Solution Instead of solving the system of two equations, we will approach the problem geometrically. T...
Circle-Line Intersection
--- title - Original --- # Lattice points inside non-lattice polygon For lattice polygons there is Pick's formula to enumerate the lattice points inside the polygon. What about polygons with arbitrary vertices? Let's process each of the polygon's edges individually, and after that we may sum up the amounts of latt...
--- title - Original --- # Lattice points inside non-lattice polygon For lattice polygons there is Pick's formula to enumerate the lattice points inside the polygon. What about polygons with arbitrary vertices? Let's process each of the polygon's edges individually, and after that we may sum up the amounts of latt...
Lattice points inside non-lattice polygon
--- title - Original --- # Minkowski sum of convex polygons ## Definition Consider two sets $A$ and $B$ of points on a plane. Minkowski sum $A + B$ is defined as $\{a + b| a \in A, b \in B\}$. Here we will consider the case when $A$ and $B$ consist of convex polygons $P$ and $Q$ with their interiors. Throughout thi...
--- title - Original --- # Minkowski sum of convex polygons ## Definition Consider two sets $A$ and $B$ of points on a plane. Minkowski sum $A + B$ is defined as $\{a + b| a \in A, b \in B\}$. Here we will consider the case when $A$ and $B$ consist of convex polygons $P$ and $Q$ with their interiors. Throughout thi...
Minkowski sum of convex polygons
--- title length_of_segments_union --- # Length of the union of segments Given $n$ segments on a line, each described by a pair of coordinates $(a_{i1}, a_{i2})$. We have to find the length of their union. The following algorithm was proposed by Klee in 1977. It works in $O(n\log n)$ and has been proven to be the a...
--- title length_of_segments_union --- # Length of the union of segments Given $n$ segments on a line, each described by a pair of coordinates $(a_{i1}, a_{i2})$. We have to find the length of their union. The following algorithm was proposed by Klee in 1977. It works in $O(n\log n)$ and has been proven to be the a...
Length of the union of segments
--- title segment_to_line --- # Finding the equation of a line for a segment The task is: given the coordinates of the ends of a segment, construct a line passing through it. We assume that the segment is non-degenerate, i.e. has a length greater than zero (otherwise, of course, infinitely many different lines pass...
--- title segment_to_line --- # Finding the equation of a line for a segment The task is: given the coordinates of the ends of a segment, construct a line passing through it. We assume that the segment is non-degenerate, i.e. has a length greater than zero (otherwise, of course, infinitely many different lines pass...
Finding the equation of a line for a segment
--- title triangles_union --- # Vertical decomposition ## Overview Vertical decomposition is a powerful technique used in various geometry problems. The general idea is to cut the plane into several vertical stripes with some "good" properties and solve the problem for these stripes independently. We will illustrate...
--- title triangles_union --- # Vertical decomposition ## Overview Vertical decomposition is a powerful technique used in various geometry problems. The general idea is to cut the plane into several vertical stripes with some "good" properties and solve the problem for these stripes independently. We will illustrate...
Vertical decomposition
--- title - Original --- # Knuth's Optimization Knuth's optimization, also known as the Knuth-Yao Speedup, is a special case of dynamic programming on ranges, that can optimize the time complexity of solutions by a linear factor, from $O(n^3)$ for standard range DP to $O(n^2)$. ## Conditions The Speedup is applie...
--- title - Original --- # Knuth's Optimization Knuth's optimization, also known as the Knuth-Yao Speedup, is a special case of dynamic programming on ranges, that can optimize the time complexity of solutions by a linear factor, from $O(n^3)$ for standard range DP to $O(n^2)$. ## Conditions The Speedup is applie...
Knuth's Optimization
--- title maximum_zero_submatrix --- # Finding the largest zero submatrix You are given a matrix with `n` rows and `m` columns. Find the largest submatrix consisting of only zeros (a submatrix is a rectangular area of the matrix). ## Algorithm Elements of the matrix will be `a[i][j]`, where `i = 0...n - 1`, `j = 0...
--- title maximum_zero_submatrix --- # Finding the largest zero submatrix You are given a matrix with `n` rows and `m` columns. Find the largest submatrix consisting of only zeros (a submatrix is a rectangular area of the matrix). ## Algorithm Elements of the matrix will be `a[i][j]`, where `i = 0...n - 1`, `j = 0...
Finding the largest zero submatrix
--- title profile_dynamics --- # Dynamic Programming on Broken Profile. Problem "Parquet" Common problems solved using DP on broken profile include: - finding number of ways to fully fill an area (e.g. chessboard/grid) with some figures (e.g. dominoes) - finding a way to fill an area with minimum number of figures ...
--- title profile_dynamics --- # Dynamic Programming on Broken Profile. Problem "Parquet" Common problems solved using DP on broken profile include: - finding number of ways to fully fill an area (e.g. chessboard/grid) with some figures (e.g. dominoes) - finding a way to fill an area with minimum number of figures ...
Dynamic Programming on Broken Profile. Problem "Parquet"
--- title - Original --- # Divide and Conquer DP Divide and Conquer is a dynamic programming optimization. ### Preconditions Some dynamic programming problems have a recurrence of this form: $$ dp(i, j) = \min_{0 \leq k \leq j} \\{ dp(i - 1, k - 1) + C(k, j) \\} $$ where $C(k, j)$ is a cost function and $dp(i, ...
--- title - Original --- # Divide and Conquer DP Divide and Conquer is a dynamic programming optimization. ### Preconditions Some dynamic programming problems have a recurrence of this form: $$ dp(i, j) = \min_{0 \leq k \leq j} \\{ dp(i - 1, k - 1) + C(k, j) \\} $$ where $C(k, j)$ is a cost function and $dp(i, ...
Divide and Conquer DP
--- title maximum_average_segment --- # Search the subarray with the maximum/minimum sum Here, we consider the problem of finding a subarray with maximum sum, as well as some of its variations (including the algorithm for solving this problem online). ## Problem statement Given an array of numbers $a[1 \ldots n]$....
--- title maximum_average_segment --- # Search the subarray with the maximum/minimum sum Here, we consider the problem of finding a subarray with maximum sum, as well as some of its variations (including the algorithm for solving this problem online). ## Problem statement Given an array of numbers $a[1 \ldots n]$....
Search the subarray with the maximum/minimum sum
--- title joseph_problem --- # Josephus Problem ## Statement We are given the natural numbers $n$ and $k$. All natural numbers from $1$ to $n$ are written in a circle. First, count the $k$-th number starting from the first one and delete it. Then $k$ numbers are counted starting from the next one and the $k$-th on...
--- title joseph_problem --- # Josephus Problem ## Statement We are given the natural numbers $n$ and $k$. All natural numbers from $1$ to $n$ are written in a circle. First, count the $k$-th number starting from the first one and delete it. Then $k$ numbers are counted starting from the next one and the $k$-th on...
Josephus Problem
--- title stern_brocot_farey --- # The Stern-Brocot tree and Farey sequences ## Stern-Brocot tree The Stern-Brocot tree is an elegant construction to represent the set of all positive fractions. It was independently discovered by German mathematician Moritz Stern in 1858 and by French watchmaker Achille Brocot in 1...
--- title stern_brocot_farey --- # The Stern-Brocot tree and Farey sequences ## Stern-Brocot tree The Stern-Brocot tree is an elegant construction to represent the set of all positive fractions. It was independently discovered by German mathematician Moritz Stern in 1858 and by French watchmaker Achille Brocot in 1...
The Stern-Brocot tree and Farey sequences
--- title 15_puzzle --- # 15 Puzzle Game: Existence Of The Solution This game is played on a $4 \times 4$ board. On this board there are $15$ playing tiles numbered from 1 to 15. One cell is left empty (denoted by 0). You need to get the board to the position presented below by repeatedly moving one of the tiles to ...
--- title 15_puzzle --- # 15 Puzzle Game: Existence Of The Solution This game is played on a $4 \times 4$ board. On this board there are $15$ playing tiles numbered from 1 to 15. One cell is left empty (denoted by 0). You need to get the board to the position presented below by repeatedly moving one of the tiles to ...
15 Puzzle Game: Existence Of The Solution
--- title dijkstra --- # Dijkstra Algorithm You are given a directed or undirected weighted graph with $n$ vertices and $m$ edges. The weights of all edges are non-negative. You are also given a starting vertex $s$. This article discusses finding the lengths of the shortest paths from a starting vertex $s$ to all ot...
--- title dijkstra --- # Dijkstra Algorithm You are given a directed or undirected weighted graph with $n$ vertices and $m$ edges. The weights of all edges are non-negative. You are also given a starting vertex $s$. This article discusses finding the lengths of the shortest paths from a starting vertex $s$ to all ot...
Dijkstra Algorithm
--- title tree_painting --- # Paint the edges of the tree This is a fairly common task. Given a tree $G$ with $N$ vertices. There are two types of queries: the first one is to paint an edge, the second one is to query the number of colored edges between two vertices. Here we will describe a fairly simple solution (...
--- title tree_painting --- # Paint the edges of the tree This is a fairly common task. Given a tree $G$ with $N$ vertices. There are two types of queries: the first one is to paint an edge, the second one is to query the number of colored edges between two vertices. Here we will describe a fairly simple solution (...
Paint the edges of the tree
--- title flow_with_limits --- # Flows with demands In a normal flow network the flow of an edge is only limited by the capacity $c(e)$ from above and by 0 from below. In this article we will discuss flow networks, where we additionally require the flow of each edge to have a certain amount, i.e. we bound the flow f...
--- title flow_with_limits --- # Flows with demands In a normal flow network the flow of an edge is only limited by the capacity $c(e)$ from above and by 0 from below. In this article we will discuss flow networks, where we additionally require the flow of each edge to have a certain amount, i.e. we bound the flow f...
Flows with demands
--- title fixed_length_paths --- # Number of paths of fixed length / Shortest paths of fixed length The following article describes solutions to these two problems built on the same idea: reduce the problem to the construction of matrix and compute the solution with the usual matrix multiplication or with a modified...
--- title fixed_length_paths --- # Number of paths of fixed length / Shortest paths of fixed length The following article describes solutions to these two problems built on the same idea: reduce the problem to the construction of matrix and compute the solution with the usual matrix multiplication or with a modified...
Number of paths of fixed length / Shortest paths of fixed length
--- title kuhn_matching --- # Kuhn's Algorithm for Maximum Bipartite Matching ## Problem You are given a bipartite graph $G$ containing $n$ vertices and $m$ edges. Find the maximum matching, i.e., select as many edges as possible so that no selected edge shares a vertex with any other selected edge. ## Algorithm D...
--- title kuhn_matching --- # Kuhn's Algorithm for Maximum Bipartite Matching ## Problem You are given a bipartite graph $G$ containing $n$ vertices and $m$ edges. Find the maximum matching, i.e., select as many edges as possible so that no selected edge shares a vertex with any other selected edge. ## Algorithm D...
Kuhn's Algorithm for Maximum Bipartite Matching
--- title strong_connected_components --- # Finding strongly connected components / Building condensation graph ## Definitions You are given a directed graph $G$ with vertices $V$ and edges $E$. It is possible that there are loops and multiple edges. Let's denote $n$ as number of vertices and $m$ as number of edges ...
--- title strong_connected_components --- # Finding strongly connected components / Building condensation graph ## Definitions You are given a directed graph $G$ with vertices $V$ and edges $E$. It is possible that there are loops and multiple edges. Let's denote $n$ as number of vertices and $m$ as number of edges ...
Finding strongly connected components / Building condensation graph
--- title - Original --- # Maximum flow - MPM algorithm MPM (Malhotra, Pramodh-Kumar and Maheshwari) algorithm solves the maximum flow problem in $O(V^3)$. This algorithm is similar to [Dinic's algorithm](dinic.md). ## Algorithm Like Dinic's algorithm, MPM runs in phases, during each phase we find the blocking fl...
--- title - Original --- # Maximum flow - MPM algorithm MPM (Malhotra, Pramodh-Kumar and Maheshwari) algorithm solves the maximum flow problem in $O(V^3)$. This algorithm is similar to [Dinic's algorithm](dinic.md). ## Algorithm Like Dinic's algorithm, MPM runs in phases, during each phase we find the blocking fl...
Maximum flow - MPM algorithm
--- title topological_sort --- # Topological Sorting You are given a directed graph with $n$ vertices and $m$ edges. You have to find an **order of the vertices**, so that every edge leads from the vertex with a smaller index to a vertex with a larger one. In other words, you want to find a permutation of the verti...
--- title topological_sort --- # Topological Sorting You are given a directed graph with $n$ vertices and $m$ edges. You have to find an **order of the vertices**, so that every edge leads from the vertex with a smaller index to a vertex with a larger one. In other words, you want to find a permutation of the verti...
Topological Sorting
--- title prufer_code_cayley_formula --- # Prüfer code In this article we will look at the so-called **Prüfer code** (or Prüfer sequence), which is a way of encoding a labeled tree into a sequence of numbers in a unique way. With the help of the Prüfer code we will prove **Cayley's formula** (which specified the nu...
--- title prufer_code_cayley_formula --- # Prüfer code In this article we will look at the so-called **Prüfer code** (or Prüfer sequence), which is a way of encoding a labeled tree into a sequence of numbers in a unique way. With the help of the Prüfer code we will prove **Cayley's formula** (which specified the nu...
Prüfer code
--- title - rib_connectivity - vertex_connectivity --- # Edge connectivity / Vertex connectivity ## Definition Given an undirected graph $G$ with $n$ vertices and $m$ edges. Both the edge connectivity and the vertex connectivity are characteristics describing the graph. ### Edge connectivity The **edge connec...
--- title - rib_connectivity - vertex_connectivity --- # Edge connectivity / Vertex connectivity ## Definition Given an undirected graph $G$ with $n$ vertices and $m$ edges. Both the edge connectivity and the vertex connectivity are characteristics describing the graph. ### Edge connectivity The **edge connec...
Edge connectivity / Vertex connectivity
--- title dinic --- # Maximum flow - Dinic's algorithm Dinic's algorithm solves the maximum flow problem in $O(V^2E)$. The maximum flow problem is defined in this article [Maximum flow - Ford-Fulkerson and Edmonds-Karp](edmonds_karp.md). This algorithm was discovered by Yefim Dinitz in 1970. ## Definitions A **res...
--- title dinic --- # Maximum flow - Dinic's algorithm Dinic's algorithm solves the maximum flow problem in $O(V^2E)$. The maximum flow problem is defined in this article [Maximum flow - Ford-Fulkerson and Edmonds-Karp](edmonds_karp.md). This algorithm was discovered by Yefim Dinitz in 1970. ## Definitions A **res...
Maximum flow - Dinic's algorithm
--- title: Finding the Eulerian path in O(M) title euler_path --- # Finding the Eulerian path in $O(M)$ A Eulerian path is a path in a graph that passes through all of its edges exactly once. A Eulerian cycle is a Eulerian path that is a cycle. The problem is to find the Eulerian path in an **undirected multigraph w...
--- title: Finding the Eulerian path in O(M) title euler_path --- # Finding the Eulerian path in $O(M)$ A Eulerian path is a path in a graph that passes through all of its edges exactly once. A Eulerian cycle is a Eulerian path that is a cycle. The problem is to find the Eulerian path in an **undirected multigraph w...
Finding the Eulerian path in $O(M)$
--- title bridge_searching_online --- # Finding Bridges Online We are given an undirected graph. A bridge is an edge whose removal makes the graph disconnected (or, more precisely, increases the number of connected components). Our task is to find all the bridges in the given graph. Informally this task can be put ...
--- title bridge_searching_online --- # Finding Bridges Online We are given an undirected graph. A bridge is an edge whose removal makes the graph disconnected (or, more precisely, increases the number of connected components). Our task is to find all the bridges in the given graph. Informally this task can be put ...
Finding Bridges Online
--- title negative_cycle --- # Finding a negative cycle in the graph You are given a directed weighted graph $G$ with $N$ vertices and $M$ edges. Find any cycle of negative weight in it, if such a cycle exists. In another formulation of the problem you have to find all pairs of vertices which have a path of arbitra...
--- title negative_cycle --- # Finding a negative cycle in the graph You are given a directed weighted graph $G$ with $N$ vertices and $M$ edges. Find any cycle of negative weight in it, if such a cycle exists. In another formulation of the problem you have to find all pairs of vertices which have a path of arbitra...
Finding a negative cycle in the graph
--- title dfs --- # Depth First Search Depth First Search is one of the main graph algorithms. Depth First Search finds the lexicographical first path in the graph from a source vertex $u$ to each vertex. Depth First Search will also find the shortest paths in a tree (because there only exists one simple path), but...
--- title dfs --- # Depth First Search Depth First Search is one of the main graph algorithms. Depth First Search finds the lexicographical first path in the graph from a source vertex $u$ to each vertex. Depth First Search will also find the shortest paths in a tree (because there only exists one simple path), but...
Depth First Search
--- title mst_prim --- # Minimum spanning tree - Prim's algorithm Given a weighted, undirected graph $G$ with $n$ vertices and $m$ edges. You want to find a spanning tree of this graph which connects all vertices and has the least weight (i.e. the sum of weights of edges is minimal). A spanning tree is a set of edge...
--- title mst_prim --- # Minimum spanning tree - Prim's algorithm Given a weighted, undirected graph $G$ with $n$ vertices and $m$ edges. You want to find a spanning tree of this graph which connects all vertices and has the least weight (i.e. the sum of weights of edges is minimal). A spanning tree is a set of edge...
Minimum spanning tree - Prim's algorithm
--- title levit_algorithm --- # D´Esopo-Pape algorithm Given a graph with $n$ vertices and $m$ edges with weights $w_i$ and a starting vertex $v_0$. The task is to find the shortest path from the vertex $v_0$ to every other vertex. The algorithm from D´Esopo-Pape will work faster than [Dijkstra's algorithm](dijkstr...
--- title levit_algorithm --- # D´Esopo-Pape algorithm Given a graph with $n$ vertices and $m$ edges with weights $w_i$ and a starting vertex $v_0$. The task is to find the shortest path from the vertex $v_0$ to every other vertex. The algorithm from D´Esopo-Pape will work faster than [Dijkstra's algorithm](dijkstr...
D´Esopo-Pape algorithm
--- title - Original --- # Second Best Minimum Spanning Tree A Minimum Spanning Tree $T$ is a tree for the given graph $G$ which spans over all vertices of the given graph and has the minimum weight sum of all the edges, from all the possible spanning trees. A second best MST $T'$ is a spanning tree, that has the s...
--- title - Original --- # Second Best Minimum Spanning Tree A Minimum Spanning Tree $T$ is a tree for the given graph $G$ which spans over all vertices of the given graph and has the minimum weight sum of all the edges, from all the possible spanning trees. A second best MST $T'$ is a spanning tree, that has the s...
Second Best Minimum Spanning Tree
--- title assignment_mincostflow --- # Solving assignment problem using min-cost-flow The **assignment problem** has two equivalent statements: - Given a square matrix $A[1..N, 1..N]$, you need to select $N$ elements in it so that exactly one element is selected in each row and column, and the sum of the values ...
--- title assignment_mincostflow --- # Solving assignment problem using min-cost-flow The **assignment problem** has two equivalent statements: - Given a square matrix $A[1..N, 1..N]$, you need to select $N$ elements in it so that exactly one element is selected in each row and column, and the sum of the values ...
Solving assignment problem using min-cost-flow
--- title connected_components --- # Search for connected components in a graph Given an undirected graph $G$ with $n$ nodes and $m$ edges. We are required to find in it all the connected components, i.e, several groups of vertices such that within a group each vertex can be reached from another and no path exists b...
--- title connected_components --- # Search for connected components in a graph Given an undirected graph $G$ with $n$ nodes and $m$ edges. We are required to find in it all the connected components, i.e, several groups of vertices such that within a group each vertex can be reached from another and no path exists b...
Search for connected components in a graph
--- title rmq_linear --- # Solve RMQ (Range Minimum Query) by finding LCA (Lowest Common Ancestor) Given an array `A[0..N-1]`. For each query of the form `[L, R]` we want to find the minimum in the array `A` starting from position `L` and ending with position `R`. We will assume that the array `A` doesn't change in ...
--- title rmq_linear --- # Solve RMQ (Range Minimum Query) by finding LCA (Lowest Common Ancestor) Given an array `A[0..N-1]`. For each query of the form `[L, R]` we want to find the minimum in the array `A` starting from position `L` and ending with position `R`. We will assume that the array `A` doesn't change in ...
Solve RMQ (Range Minimum Query) by finding LCA (Lowest Common Ancestor)
--- title lca_linear_offline --- # Lowest Common Ancestor - Tarjan's off-line algorithm We have a tree $G$ with $n$ nodes and we have $m$ queries of the form $(u, v)$. For each query $(u, v)$ we want to find the lowest common ancestor of the vertices $u$ and $v$, i.e. the node that is an ancestor of both $u$ and $v$...
--- title lca_linear_offline --- # Lowest Common Ancestor - Tarjan's off-line algorithm We have a tree $G$ with $n$ nodes and we have $m$ queries of the form $(u, v)$. For each query $(u, v)$ we want to find the lowest common ancestor of the vertices $u$ and $v$, i.e. the node that is an ancestor of both $u$ and $v$...
Lowest Common Ancestor - Tarjan's off-line algorithm
--- title dijkstra_sparse --- # Dijkstra on sparse graphs For the statement of the problem, the algorithm with implementation and proof can be found on the article [Dijkstra's algorithm](dijkstra.md). ## Algorithm We recall in the derivation of the complexity of Dijkstra's algorithm we used two factors: the time o...
--- title dijkstra_sparse --- # Dijkstra on sparse graphs For the statement of the problem, the algorithm with implementation and proof can be found on the article [Dijkstra's algorithm](dijkstra.md). ## Algorithm We recall in the derivation of the complexity of Dijkstra's algorithm we used two factors: the time o...
Dijkstra on sparse graphs
--- title edmonds_karp --- # Maximum flow - Ford-Fulkerson and Edmonds-Karp The Edmonds-Karp algorithm is an implementation of the Ford-Fulkerson method for computing a maximal flow in a flow network. ## Flow network First let's define what a **flow network**, a **flow**, and a **maximum flow** is. A **network** ...
--- title edmonds_karp --- # Maximum flow - Ford-Fulkerson and Edmonds-Karp The Edmonds-Karp algorithm is an implementation of the Ford-Fulkerson method for computing a maximal flow in a flow network. ## Flow network First let's define what a **flow network**, a **flow**, and a **maximum flow** is. A **network** ...
Maximum flow - Ford-Fulkerson and Edmonds-Karp
--- title bfs --- # Breadth-first search Breadth first search is one of the basic and essential searching algorithms on graphs. As a result of how the algorithm works, the path found by breadth first search to any node is the shortest path to that node, i.e the path that contains the smallest number of edges in unw...
--- title bfs --- # Breadth-first search Breadth first search is one of the basic and essential searching algorithms on graphs. As a result of how the algorithm works, the path found by breadth first search to any node is the shortest path to that node, i.e the path that contains the smallest number of edges in unw...
Breadth-first search
--- title: Lowest Common Ancestor - O(sqrt(N)) and O(log N) with O(N) preprocessing title lca --- # Lowest Common Ancestor - $O(\sqrt{N})$ and $O(\log N)$ with $O(N)$ preprocessing Given a tree $G$. Given queries of the form $(v_1, v_2)$, for each query you need to find the lowest common ancestor (or least common anc...
--- title: Lowest Common Ancestor - O(sqrt(N)) and O(log N) with O(N) preprocessing title lca --- # Lowest Common Ancestor - $O(\sqrt{N})$ and $O(\log N)$ with $O(N)$ preprocessing Given a tree $G$. Given queries of the form $(v_1, v_2)$, for each query you need to find the lowest common ancestor (or least common anc...
Lowest Common Ancestor - $O(\sqrt{N})$ and $O(\log N)$ with $O(N)$ preprocessing
--- title: Finding articulation points in a graph in O(N+M) title cutpoints --- # Finding articulation points in a graph in $O(N+M)$ We are given an undirected graph. An articulation point (or cut vertex) is defined as a vertex which, when removed along with associated edges, makes the graph disconnected (or more pre...
--- title: Finding articulation points in a graph in O(N+M) title cutpoints --- # Finding articulation points in a graph in $O(N+M)$ We are given an undirected graph. An articulation point (or cut vertex) is defined as a vertex which, when removed along with associated edges, makes the graph disconnected (or more pre...
Finding articulation points in a graph in $O(N+M)$
--- title preflow_push_faster --- # Maximum flow - Push-relabel method improved We will modify the [push-relabel method](push-relabel.md) to achieve a better runtime. ## Description The modification is extremely simple: In the previous article we chosen a vertex with excess without any particular rule. But it turn...
--- title preflow_push_faster --- # Maximum flow - Push-relabel method improved We will modify the [push-relabel method](push-relabel.md) to achieve a better runtime. ## Description The modification is extremely simple: In the previous article we chosen a vertex with excess without any particular rule. But it turn...
Maximum flow - Push-relabel method improved
--- title ford_bellman --- # Bellman-Ford Algorithm **Single source shortest path with negative weight edges** Suppose that we are given a weighted directed graph $G$ with $n$ vertices and $m$ edges, and some specified vertex $v$. You want to find the length of shortest paths from vertex $v$ to every other vertex. ...
--- title ford_bellman --- # Bellman-Ford Algorithm **Single source shortest path with negative weight edges** Suppose that we are given a weighted directed graph $G$ with $n$ vertices and $m$ edges, and some specified vertex $v$. You want to find the length of shortest paths from vertex $v$ to every other vertex. ...
Bellman-Ford Algorithm
--- title - Original --- # 0-1 BFS It is well-known, that you can find the shortest paths between a single source and all other vertices in $O(|E|)$ using [Breadth First Search](breadth-first-search.md) in an **unweighted graph**, i.e. the distance is the minimal number of edges that you need to traverse from the s...
--- title - Original --- # 0-1 BFS It is well-known, that you can find the shortest paths between a single source and all other vertices in $O(|E|)$ using [Breadth First Search](breadth-first-search.md) in an **unweighted graph**, i.e. the distance is the minimal number of edges that you need to traverse from the s...
0-1 BFS
--- title heavy_light --- # Heavy-light decomposition **Heavy-light decomposition** is a fairly general technique that allows us to effectively solve many problems that come down to **queries on a tree** . ## Description Let there be a tree $G$ of $n$ vertices, with an arbitrary root. The essence of this tree de...
--- title heavy_light --- # Heavy-light decomposition **Heavy-light decomposition** is a fairly general technique that allows us to effectively solve many problems that come down to **queries on a tree** . ## Description Let there be a tree $G$ of $n$ vertices, with an arbitrary root. The essence of this tree de...
Heavy-light decomposition
--- title lca_simpler --- # Lowest Common Ancestor - Binary Lifting Let $G$ be a tree. For every query of the form `(u, v)` we want to find the lowest common ancestor of the nodes `u` and `v`, i.e. we want to find a node `w` that lies on the path from `u` to the root node, that lies on the path from `v` to the root ...
--- title lca_simpler --- # Lowest Common Ancestor - Binary Lifting Let $G$ be a tree. For every query of the form `(u, v)` we want to find the lowest common ancestor of the nodes `u` and `v`, i.e. we want to find a node `w` that lies on the path from `u` to the root node, that lies on the path from `v` to the root ...
Lowest Common Ancestor - Binary Lifting
--- title min_cost_flow --- # Minimum-cost flow - Successive shortest path algorithm Given a network $G$ consisting of $n$ vertices and $m$ edges. For each edge (generally speaking, oriented edges, but see below), the capacity (a non-negative integer) and the cost per unit of flow along this edge (some integer) are ...
--- title min_cost_flow --- # Minimum-cost flow - Successive shortest path algorithm Given a network $G$ consisting of $n$ vertices and $m$ edges. For each edge (generally speaking, oriented edges, but see below), the capacity (a non-negative integer) and the cost per unit of flow along this edge (some integer) are ...
Minimum-cost flow - Successive shortest path algorithm
--- title bipartite_checking --- # Check whether a graph is bipartite A bipartite graph is a graph whose vertices can be divided into two disjoint sets so that every edge connects two vertices from different sets (i.e. there are no edges which connect vertices from the same set). These sets are usually called sides....
--- title bipartite_checking --- # Check whether a graph is bipartite A bipartite graph is a graph whose vertices can be divided into two disjoint sets so that every edge connects two vertices from different sets (i.e. there are no edges which connect vertices from the same set). These sets are usually called sides....
Check whether a graph is bipartite
--- title 2_sat --- # 2-SAT SAT (Boolean satisfiability problem) is the problem of assigning Boolean values to variables to satisfy a given Boolean formula. The Boolean formula will usually be given in CNF (conjunctive normal form), which is a conjunction of multiple clauses, where each clause is a disjunction of l...
--- title 2_sat --- # 2-SAT SAT (Boolean satisfiability problem) is the problem of assigning Boolean values to variables to satisfy a given Boolean formula. The Boolean formula will usually be given in CNF (conjunctive normal form), which is a conjunction of multiple clauses, where each clause is a disjunction of l...
2-SAT
--- title kirchhoff_theorem --- # Kirchhoff's theorem. Finding the number of spanning trees Problem: You are given a connected undirected graph (with possible multiple edges) represented using an adjacency matrix. Find the number of different spanning trees of this graph. The following formula was proven by Kirchho...
--- title kirchhoff_theorem --- # Kirchhoff's theorem. Finding the number of spanning trees Problem: You are given a connected undirected graph (with possible multiple edges) represented using an adjacency matrix. Find the number of different spanning trees of this graph. The following formula was proven by Kirchho...
Kirchhoff's theorem. Finding the number of spanning trees
--- title - Original --- # Strong Orientation A **strong orientation** of an undirected graph is an assignment of a direction to each edge that makes it a [strongly connected graph](strongly-connected-components.md). That is, after the *orientation* we should be able to visit any vertex from any vertex by following...
--- title - Original --- # Strong Orientation A **strong orientation** of an undirected graph is an assignment of a direction to each edge that makes it a [strongly connected graph](strongly-connected-components.md). That is, after the *orientation* we should be able to visit any vertex from any vertex by following...
Strong Orientation
--- title mst_kruskal --- # Minimum spanning tree - Kruskal's algorithm Given a weighted undirected graph. We want to find a subtree of this graph which connects all vertices (i.e. it is a spanning tree) and has the least weight (i.e. the sum of weights of all the edges is minimum) of all possible spanning trees. Th...
--- title mst_kruskal --- # Minimum spanning tree - Kruskal's algorithm Given a weighted undirected graph. We want to find a subtree of this graph which connects all vertices (i.e. it is a spanning tree) and has the least weight (i.e. the sum of weights of all the edges is minimum) of all possible spanning trees. Th...
Minimum spanning tree - Kruskal's algorithm
--- title preflow_push --- # Maximum flow - Push-relabel algorithm The push-relabel algorithm (or also known as preflow-push algorithm) is an algorithm for computing the maximum flow of a flow network. The exact definition of the problem that we want to solve can be found in the article [Maximum flow - Ford-Fulkerso...
--- title preflow_push --- # Maximum flow - Push-relabel algorithm The push-relabel algorithm (or also known as preflow-push algorithm) is an algorithm for computing the maximum flow of a flow network. The exact definition of the problem that we want to solve can be found in the article [Maximum flow - Ford-Fulkerso...
Maximum flow - Push-relabel algorithm
--- title: Checking a graph for acyclicity and finding a cycle in O(M) title finding_cycle --- # Checking a graph for acyclicity and finding a cycle in $O(M)$ Consider a directed or undirected graph without loops and multiple edges. We have to check whether it is acyclic, and if it is not, then find any cycle. We ca...
--- title: Checking a graph for acyclicity and finding a cycle in O(M) title finding_cycle --- # Checking a graph for acyclicity and finding a cycle in $O(M)$ Consider a directed or undirected graph without loops and multiple edges. We have to check whether it is acyclic, and if it is not, then find any cycle. We ca...
Checking a graph for acyclicity and finding a cycle in $O(M)$
--- title: Finding bridges in a graph in O(N+M) title bridge_searching --- # Finding bridges in a graph in $O(N+M)$ We are given an undirected graph. A bridge is defined as an edge which, when removed, makes the graph disconnected (or more precisely, increases the number of connected components in the graph). The tas...
--- title: Finding bridges in a graph in O(N+M) title bridge_searching --- # Finding bridges in a graph in $O(N+M)$ We are given an undirected graph. A bridge is defined as an edge which, when removed, makes the graph disconnected (or more precisely, increases the number of connected components in the graph). The tas...
Finding bridges in a graph in $O(N+M)$
--- title mst_kruskal_with_dsu --- # Minimum spanning tree - Kruskal with Disjoint Set Union For an explanation of the MST problem and the Kruskal algorithm, first see the [main article on Kruskal's algorithm](mst_kruskal.md). In this article we will consider the data structure ["Disjoint Set Union"](../data_struct...
--- title mst_kruskal_with_dsu --- # Minimum spanning tree - Kruskal with Disjoint Set Union For an explanation of the MST problem and the Kruskal algorithm, first see the [main article on Kruskal's algorithm](mst_kruskal.md). In this article we will consider the data structure ["Disjoint Set Union"](../data_struct...
Minimum spanning tree - Kruskal with Disjoint Set Union
--- title lca_linear --- # Lowest Common Ancestor - Farach-Colton and Bender Algorithm Let $G$ be a tree. For every query of the form $(u, v)$ we want to find the lowest common ancestor of the nodes $u$ and $v$, i.e. we want to find a node $w$ that lies on the path from $u$ to the root node, that lies on the path fr...
--- title lca_linear --- # Lowest Common Ancestor - Farach-Colton and Bender Algorithm Let $G$ be a tree. For every query of the form $(u, v)$ we want to find the lowest common ancestor of the nodes $u$ and $v$, i.e. we want to find a node $w$ that lies on the path from $u$ to the root node, that lies on the path fr...
Lowest Common Ancestor - Farach-Colton and Bender Algorithm
--- title floyd_warshall_algorithm --- # Floyd-Warshall Algorithm Given a directed or an undirected weighted graph $G$ with $n$ vertices. The task is to find the length of the shortest path $d_{ij}$ between each pair of vertices $i$ and $j$. The graph may have negative weight edges, but no negative weight cycles. ...
--- title floyd_warshall_algorithm --- # Floyd-Warshall Algorithm Given a directed or an undirected weighted graph $G$ with $n$ vertices. The task is to find the length of the shortest path $d_{ij}$ between each pair of vertices $i$ and $j$. The graph may have negative weight edges, but no negative weight cycles. ...
Floyd-Warshall Algorithm
--- title assignment_mincostflow --- # Solving assignment problem using min-cost-flow The **assignment problem** has two equivalent statements: - Given a square matrix $A[1..N, 1..N]$, you need to select $N$ elements in it so that exactly one element is selected in each row and column, and the sum of the values ...
--- title assignment_mincostflow --- # Solving assignment problem using min-cost-flow The **assignment problem** has two equivalent statements: - Given a square matrix $A[1..N, 1..N]$, you need to select $N$ elements in it so that exactly one element is selected in each row and column, and the sum of the values ...
Solving assignment problem using min-cost-flow
--- title bfs --- # Breadth-first search Breadth first search is one of the basic and essential searching algorithms on graphs. As a result of how the algorithm works, the path found by breadth first search to any node is the shortest path to that node, i.e the path that contains the smallest number of edges in unw...
--- title bfs --- # Breadth-first search Breadth first search is one of the basic and essential searching algorithms on graphs. As a result of how the algorithm works, the path found by breadth first search to any node is the shortest path to that node, i.e the path that contains the smallest number of edges in unw...
Breadth-first search
--- title johnson_problem_2 --- # Scheduling jobs on two machines This task is about finding an optimal schedule for $n$ jobs on two machines. Every item must first be processed on the first machine, and afterwards on the second one. The $i$-th job takes $a_i$ time on the first machine, and $b_i$ time on the second ...
--- title johnson_problem_2 --- # Scheduling jobs on two machines This task is about finding an optimal schedule for $n$ jobs on two machines. Every item must first be processed on the first machine, and afterwards on the second one. The $i$-th job takes $a_i$ time on the first machine, and $b_i$ time on the second ...
Scheduling jobs on two machines
--- title schedule_with_completion_duration --- # Optimal schedule of jobs given their deadlines and durations Suppose, we have a set of jobs, and we are aware of every job’s deadline and its duration. The execution of a job cannot be interrupted prior to its ending. It is required to create such a schedule to accom...
--- title schedule_with_completion_duration --- # Optimal schedule of jobs given their deadlines and durations Suppose, we have a set of jobs, and we are aware of every job’s deadline and its duration. The execution of a job cannot be interrupted prior to its ending. It is required to create such a schedule to accom...
Optimal schedule of jobs given their deadlines and durations
--- title johnson_problem_1 --- # Scheduling jobs on one machine This task is about finding an optimal schedule for $n$ jobs on a single machine, if the job $i$ can be processed in $t_i$ time, but for the $t$ seconds waiting before processing the job a penalty of $f_i(t)$ has to be paid. Thus the task asks to find ...
--- title johnson_problem_1 --- # Scheduling jobs on one machine This task is about finding an optimal schedule for $n$ jobs on a single machine, if the job $i$ can be processed in $t_i$ time, but for the $t$ seconds waiting before processing the job a penalty of $f_i(t)$ has to be paid. Thus the task asks to find ...
Scheduling jobs on one machine
--- title binomial_coeff --- # Binomial Coefficients Binomial coefficients $\binom n k$ are the number of ways to select a set of $k$ elements from $n$ different elements without taking into account the order of arrangement of these elements (i.e., the number of unordered sets). Binomial coefficients are also the c...
--- title binomial_coeff --- # Binomial Coefficients Binomial coefficients $\binom n k$ are the number of ways to select a set of $k$ elements from $n$ different elements without taking into account the order of arrangement of these elements (i.e., the number of unordered sets). Binomial coefficients are also the c...
Binomial Coefficients
--- title inclusion_exclusion_principle --- # The Inclusion-Exclusion Principle The inclusion-exclusion principle is an important combinatorial way to compute the size of a set or the probability of complex events. It relates the sizes of individual sets with their union. ## Statement ### The verbal formula The i...
--- title inclusion_exclusion_principle --- # The Inclusion-Exclusion Principle The inclusion-exclusion principle is an important combinatorial way to compute the size of a set or the probability of complex events. It relates the sizes of individual sets with their union. ## Statement ### The verbal formula The i...
The Inclusion-Exclusion Principle
--- title: Generating all K-combinations title generating_combinations --- # Generating all $K$-combinations In this article we will discuss the problem of generating all $K$-combinations. Given the natural numbers $N$ and $K$, and considering a set of numbers from $1$ to $N$. The task is to derive all **subsets of s...
--- title: Generating all K-combinations title generating_combinations --- # Generating all $K$-combinations In this article we will discuss the problem of generating all $K$-combinations. Given the natural numbers $N$ and $K$, and considering a set of numbers from $1$ to $N$. The task is to derive all **subsets of s...
Generating all $K$-combinations
--- title bishops_arrangement --- # Placing Bishops on a Chessboard Find the number of ways to place $K$ bishops on an $N \times N$ chessboard so that no two bishops attack each other. ## Algorithm This problem can be solved using dynamic programming. Let's enumerate the diagonals of the chessboard as follows: bl...
--- title bishops_arrangement --- # Placing Bishops on a Chessboard Find the number of ways to place $K$ bishops on an $N \times N$ chessboard so that no two bishops attack each other. ## Algorithm This problem can be solved using dynamic programming. Let's enumerate the diagonals of the chessboard as follows: bl...
Placing Bishops on a Chessboard
--- title catalan_numbers --- # Catalan Numbers Catalan numbers is a number sequence, which is found useful in a number of combinatorial problems, often involving recursively-defined objects. This sequence was named after the Belgian mathematician [Catalan](https://en.wikipedia.org/wiki/Eug%C3%A8ne_Charles_Catalan),...
--- title catalan_numbers --- # Catalan Numbers Catalan numbers is a number sequence, which is found useful in a number of combinatorial problems, often involving recursively-defined objects. This sequence was named after the Belgian mathematician [Catalan](https://en.wikipedia.org/wiki/Eug%C3%A8ne_Charles_Catalan),...
Catalan Numbers
--- title burnside_polya --- # Burnside's lemma / Pólya enumeration theorem ## Burnside's lemma **Burnside's lemma** was formulated and proven by **Burnside** in 1897, but historically it was already discovered in 1887 by **Frobenius**, and even earlier in 1845 by **Cauchy**. Therefore it is also sometimes named th...
--- title burnside_polya --- # Burnside's lemma / Pólya enumeration theorem ## Burnside's lemma **Burnside's lemma** was formulated and proven by **Burnside** in 1897, but historically it was already discovered in 1887 by **Frobenius**, and even earlier in 1845 by **Cauchy**. Therefore it is also sometimes named th...
Burnside's lemma / Pólya enumeration theorem
--- title counting_connected_graphs --- # Counting labeled graphs ## Labeled graphs Let the number of vertices in a graph be $n$. We have to compute the number $G_n$ of labeled graphs with $n$ vertices (labeled means that the vertices are marked with the numbers from $1$ to $n$). The edges of the graphs are conside...
--- title counting_connected_graphs --- # Counting labeled graphs ## Labeled graphs Let the number of vertices in a graph be $n$. We have to compute the number $G_n$ of labeled graphs with $n$ vertices (labeled means that the vertices are marked with the numbers from $1$ to $n$). The edges of the graphs are conside...
Counting labeled graphs
--- title bracket_sequences --- # Balanced bracket sequences A **balanced bracket sequence** is a string consisting of only brackets, such that this sequence, when inserted certain numbers and mathematical operations, gives a valid mathematical expression. Formally you can define balanced bracket sequence with: - $...
--- title bracket_sequences --- # Balanced bracket sequences A **balanced bracket sequence** is a string consisting of only brackets, such that this sequence, when inserted certain numbers and mathematical operations, gives a valid mathematical expression. Formally you can define balanced bracket sequence with: - $...
Balanced bracket sequences
--- title - Original --- # Stars and bars Stars and bars is a mathematical technique for solving certain combinatorial problems. It occurs whenever you want to count the number of ways to group identical objects. ## Theorem The number of ways to put $n$ identical objects into $k$ labeled boxes is $$\binom{n + k ...
--- title - Original --- # Stars and bars Stars and bars is a mathematical technique for solving certain combinatorial problems. It occurs whenever you want to count the number of ways to group identical objects. ## Theorem The number of ways to put $n$ identical objects into $k$ labeled boxes is $$\binom{n + k ...
Stars and bars
# Garner's algorithm A consequence of the [Chinese Remainder Theorem](chinese-remainder-theorem.md) is, that we can represent big numbers using an array of small integers. For example, let $p$ be the product of the first $1000$ primes. $p$ has around $3000$ digits. Any number $a$ less than $p$ can be represented as a...
# Garner's algorithm A consequence of the [Chinese Remainder Theorem](chinese-remainder-theorem.md) is, that we can represent big numbers using an array of small integers. For example, let $p$ be the product of the first $1000$ primes. $p$ has around $3000$ digits. Any number $a$ less than $p$ can be represented as a...
Garner's algorithm
--- title factorial_divisors --- # Finding Power of Factorial Divisor You are given two numbers $n$ and $k$. Find the largest power of $k$ $x$ such that $n!$ is divisible by $k^x$. ## Prime $k$ {data-toc-label="Prime k"} Let's first consider the case of prime $k$. The explicit expression for factorial $$n! = 1 \c...
--- title factorial_divisors --- # Finding Power of Factorial Divisor You are given two numbers $n$ and $k$. Find the largest power of $k$ $x$ such that $n!$ is divisible by $k^x$. ## Prime $k$ {data-toc-label="Prime k"} Let's first consider the case of prime $k$. The explicit expression for factorial $$n! = 1 \c...
Finding Power of Factorial Divisor
--- title - Original --- # Operations on polynomials and series Problems in competitive programming, especially the ones involving enumeration some kind, are often solved by reducing the problem to computing something on polynomials and formal power series. This includes concepts such as polynomial multiplication,...
--- title - Original --- # Operations on polynomials and series Problems in competitive programming, especially the ones involving enumeration some kind, are often solved by reducing the problem to computing something on polynomials and formal power series. This includes concepts such as polynomial multiplication,...
Operations on polynomials and series
--- title eratosthenes_sieve --- # Sieve of Eratosthenes Sieve of Eratosthenes is an algorithm for finding all the prime numbers in a segment $[1;n]$ using $O(n \log \log n)$ operations. The algorithm is very simple: at the beginning we write down all numbers between 2 and $n$. We mark all proper multiples of 2 (si...
--- title eratosthenes_sieve --- # Sieve of Eratosthenes Sieve of Eratosthenes is an algorithm for finding all the prime numbers in a segment $[1;n]$ using $O(n \log \log n)$ operations. The algorithm is very simple: at the beginning we write down all numbers between 2 and $n$. We mark all proper multiples of 2 (si...
Sieve of Eratosthenes
--- title binary_pow --- # Binary Exponentiation Binary exponentiation (also known as exponentiation by squaring) is a trick which allows to calculate $a^n$ using only $O(\log n)$ multiplications (instead of $O(n)$ multiplications required by the naive approach). It also has important applications in many tasks unr...
--- title binary_pow --- # Binary Exponentiation Binary exponentiation (also known as exponentiation by squaring) is a trick which allows to calculate $a^n$ using only $O(\log n)$ multiplications (instead of $O(n)$ multiplications required by the naive approach). It also has important applications in many tasks unr...
Binary Exponentiation
--- title balanced_ternary --- # Balanced Ternary !["Setun computer using Balanced Ternary system"](https://earltcampbell.files.wordpress.com/2014/12/setun.jpeg?w=300) This is a non-standard but still positional **numeral system**. Its feature is that digits can have one of the values `-1`, `0` and `1`. Nevertheles...
--- title balanced_ternary --- # Balanced Ternary !["Setun computer using Balanced Ternary system"](https://earltcampbell.files.wordpress.com/2014/12/setun.jpeg?w=300) This is a non-standard but still positional **numeral system**. Its feature is that digits can have one of the values `-1`, `0` and `1`. Nevertheles...
Balanced Ternary
--- title discrete_root --- # Discrete Root The problem of finding a discrete root is defined as follows. Given a prime $n$ and two integers $a$ and $k$, find all $x$ for which: $x^k \equiv a \pmod n$ ## The algorithm We will solve this problem by reducing it to the [discrete logarithm problem](discrete-log.md). ...
--- title discrete_root --- # Discrete Root The problem of finding a discrete root is defined as follows. Given a prime $n$ and two integers $a$ and $k$, find all $x$ for which: $x^k \equiv a \pmod n$ ## The algorithm We will solve this problem by reducing it to the [discrete logarithm problem](discrete-log.md). ...
Discrete Root
--- title - Original --- # Integer factorization In this article we list several algorithms for factorizing integers, each of them can be both fast and also slow (some slower than others) depending on their input. Notice, if the number that you want to factorize is actually a prime number, most of the algorithms, ...
--- title - Original --- # Integer factorization In this article we list several algorithms for factorizing integers, each of them can be both fast and also slow (some slower than others) depending on their input. Notice, if the number that you want to factorize is actually a prime number, most of the algorithms, ...
Integer factorization
--- title all_submasks --- # Submask Enumeration ## Enumerating all submasks of a given mask Given a bitmask $m$, you want to efficiently iterate through all of its submasks, that is, masks $s$ in which only bits that were included in mask $m$ are set. Consider the implementation of this algorithm, based on tricks...
--- title all_submasks --- # Submask Enumeration ## Enumerating all submasks of a given mask Given a bitmask $m$, you want to efficiently iterate through all of its submasks, that is, masks $s$ in which only bits that were included in mask $m$ are set. Consider the implementation of this algorithm, based on tricks...
Submask Enumeration
--- title - Original --- <!--?title Continued fractions --> # Continued fractions **Continued fraction** is a representation of a real number as a specific convergent sequence of rational numbers. They are useful in competitive programming because they are easy to compute and can be efficiently used to find the bes...
--- title - Original --- <!--?title Continued fractions --> # Continued fractions **Continued fraction** is a representation of a real number as a specific convergent sequence of rational numbers. They are useful in competitive programming because they are easy to compute and can be efficiently used to find the bes...
Continued fractions