From 0d6997e3e61cbc3f021a0d1668c85fc56bf7285f Mon Sep 17 00:00:00 2001 From: Bruno Freitas Tissei <bft15@inf.ufpr.br> Date: Tue, 14 May 2019 18:44:52 -0300 Subject: [PATCH] Remove overly descriptive comments and make code more compact Signed-off-by: Bruno Freitas Tissei <bft15@inf.ufpr.br> --- algorithms/geometry/convex_hull.cpp | 24 +++++------ algorithms/geometry/geometry_functions.cpp | 28 ++++++------- algorithms/graph/articulations_bridges.cpp | 21 ---------- algorithms/graph/bellman_ford.cpp | 19 ++------- algorithms/graph/bfs.cpp | 38 ----------------- algorithms/graph/bipartite_match.cpp | 9 ++-- algorithms/graph/centroid_decomposition.cpp | 17 ++------ algorithms/graph/dfs.cpp | 28 ------------- algorithms/graph/dijkstra.cpp | 4 +- algorithms/graph/dinic.cpp | 13 +----- algorithms/graph/edmonds_karp.cpp | 9 +--- algorithms/graph/floyd_warshall.cpp | 5 ++- algorithms/graph/ford_fulkerson.cpp | 13 +----- algorithms/graph/hopcroft_karp.cpp | 9 +--- algorithms/graph/kosaraju.cpp | 15 ++----- algorithms/graph/kruskal.cpp | 14 +++---- algorithms/graph/lca.cpp | 18 ++++---- algorithms/graph/prim.cpp | 5 +-- algorithms/graph/tarjan.cpp | 14 +------ algorithms/graph/topological_sort.cpp | 10 +---- algorithms/math/binary_exponentiation.cpp | 4 -- algorithms/math/euler_totient.cpp | 3 -- algorithms/math/fft.cpp | 34 ++++++++------- .../math/modular_multiplicative_inverse.cpp | 3 -- algorithms/math/sieve_of_eratosthenes.cpp | 8 +--- algorithms/paradigm/edit_distance.cpp | 6 +-- algorithms/paradigm/kadane.cpp | 10 ----- algorithms/paradigm/lis.cpp | 3 -- algorithms/paradigm/ternary_search.cpp | 4 +- algorithms/string/kmp.cpp | 5 --- algorithms/string/z-function.cpp | 3 -- algorithms/structure/avl.cpp | 42 ++++--------------- algorithms/structure/ball_tree.cpp | 32 +++----------- algorithms/structure/bit.cpp | 10 +---- algorithms/structure/bit2d.cpp | 2 - algorithms/structure/bitmask.cpp | 7 ---- algorithms/structure/disjoint_set.cpp | 3 -- algorithms/structure/lazy_segment_tree.cpp | 21 +++------- algorithms/structure/policy_tree.cpp | 10 ++--- algorithms/structure/segment_tree.cpp | 21 ++++------ algorithms/structure/sqrt_decomposition.cpp | 11 ----- algorithms/structure/trie.cpp | 8 ---- gen_notebook | 6 ++- notebook/gen_latex.py | 35 ++++++++++------ notebook/header.tex | 21 ++++++---- 45 files changed, 164 insertions(+), 461 deletions(-) delete mode 100644 algorithms/graph/bfs.cpp delete mode 100644 algorithms/graph/dfs.cpp diff --git a/algorithms/geometry/convex_hull.cpp b/algorithms/geometry/convex_hull.cpp index 9c28b2f..5c94162 100644 --- a/algorithms/geometry/convex_hull.cpp +++ b/algorithms/geometry/convex_hull.cpp @@ -4,41 +4,37 @@ /// Complexity (Space): O(n) struct ConvexHull { - using dd = pair<double,double>; + using point = pair<double,double>; - /// The three points are a counter-clockwise turn if cross > 0, clockwise if - /// cross < 0, and collinear if cross = 0 - /// @param a,b,c input points - double cross(dd a, dd b, dd c) { - return (b.fi - a.fi) * (c.se - a.se) - (b.se - a.se) * (c.fi - a.fi); + // The three points are a counter-clockwise turn if + // cross > 0, clockwise if cross < 0, and collinear + // if cross = 0. + double cross(point a, point b, point c) { + return (b.fi-a.fi)*(c.se-a.se) - (b.se-a.se)*(c.fi-a.fi); } - /// Finds, among v, the points that form a convex hull - /// @param v vector of points - vector<int> run(const vector<dd> &v) { + vector<int> run(const vector<point> &v) { int k = 0; vector<int> ans(v.size() * 2); - sort(all(v), [](const dd &a, const dd &b) { + sort(all(v), [](const point &a, const point &b) { return (a.fi == b.fi) ? (a.se < b.se) : (a.fi < b.fi); }); // Uppermost part of convex hull for (int i = 0; i < v.size(); ++i) { - while (k >= 2 && cross(v[ans[k - 2]], v[ans[k - 1]], v[i]) < 0) + while (k >= 2 && cross(v[ans[k-2]], v[ans[k-1]], v[i]) < 0) k--; ans[k++] = i; } // Lowermost part of convex hull for (int i = v.size() - 2, t = k + 1; i >= 0; --i) { - while (k >= t && cross(v[ans[k - 2]], v[ans[k - 1]], v[i]) < 0) + while (k >= t && cross(v[ans[k-2]], v[ans[k-1]], v[i]) < 0) k--; ans[k++] = i; } - // The ans vector contains the indices (relative to the sorted vector!) - // of the points belonging to the convex hull ans.resize(k - 1); return ans; } diff --git a/algorithms/geometry/geometry_functions.cpp b/algorithms/geometry/geometry_functions.cpp index 01edb1a..b3884c1 100644 --- a/algorithms/geometry/geometry_functions.cpp +++ b/algorithms/geometry/geometry_functions.cpp @@ -12,27 +12,25 @@ struct Point { T dot(Point p) { return (x * p.x) + (y * p.y); } T cross(Point p) { return (x * p.y) - (y * p.y); } - /// Returns angle between this and p: - /// atan2(y, x) is in the range [-180,180]. To get [0, 360], - /// atan2(-y, -x) + 180 is used + // Returns angle between this and p: + // atan2(y, x) is in the range [-180,180]. To get [0, 360], + // atan2(-y, -x) + 180 is used T angle(Point p) { return ((atan2(-cross(p), -dot(p)) * 180.0) / M_PI) + 180.0; } - /// Returns cosine value between this and p. + // Returns cosine value between this and p. T cosine(Point p) { return (dot(p) / (sqrt(dot(*this)) * sqrt(p.dot(p)))); } - /// Returns sine value between this and p. + // Returns sine value between this and p. T sine(Point p) { return (cross(p) / (sqrt(dot(*this)) * sqrt(p.dot(p)))); } - /// Finds orientation of ordered triplet (a,b,c). - /// 0 - Colinear; - /// 1 - Clockwise; - /// 2 - Counterclockwise. + // Finds orientation of ordered triplet (a,b,c). + // Colinear (0), Clockwise (1), Counterclockwise (2) static int orientation(Point a, Point b, Point c) { T val = (b - a).cross(c - b); @@ -49,14 +47,14 @@ struct Segment { Segment(Point a, Point b) : a(a), b(b) {} - /// Checks if points p and q are on the same side of the segment. + // Checks if points p and q are on the same side of the segment. bool same_side(Point p, Point q) { T cpp = (p - a).cross(b - a); T cpq = (q - a).cross(b - a); return ((cpp > 0 && cpq > 0) || (cpp < 0 && cpq < 0)); } - /// Checks if point p is on the segment. + // Checks if point p is on the segment. bool on_segment(Point p) { return (p.x <= max(a.x, b.x) && p.x >= min(a.x, b.x) && @@ -64,7 +62,7 @@ struct Segment { p.y >= min(a.y, b.y)); } - /// Checks if segment intersects with s. + // Checks if segment intersects with s. bool intersect(Segment s) { int o1 = Point::orientation( a, b, s.a); int o2 = Point::orientation( a, b, s.b); @@ -90,11 +88,11 @@ struct Polygon { Polygon() {} Polygon(vector<Point> vertices) : vertices(vertices) {} - /// Adds a vertex to the polygon. + // Adds a vertex to the polygon. void add_point(Point p) { vertices.pb(p); } - /// Returns area of polygon (only works when vertices are sorted in clockwise - /// or counterclockwise order). + // Returns area of polygon (only works when vertices are sorted + // in clockwise or counterclockwise order). double area() { double ans = 0; for (int i = 0; i < vertices.size(); ++i) diff --git a/algorithms/graph/articulations_bridges.cpp b/algorithms/graph/articulations_bridges.cpp index 23d7fb4..4e80bed 100644 --- a/algorithms/graph/articulations_bridges.cpp +++ b/algorithms/graph/articulations_bridges.cpp @@ -9,10 +9,7 @@ struct Tarjan { int N; vector<int> vis, par, L, low; - /// Answer vector with bridges (edges) vector<ii> brid; - - /// Answer vector with articulations (vertices) vector<int> arti; Tarjan(int N) : @@ -25,8 +22,6 @@ struct Tarjan { fill(all(par), -1); } - /// Finds all articulations and bridges in the graph. - /// @param x root vertex void dfs(int x) { int child = 0; vis[x] = 1; @@ -36,43 +31,27 @@ struct Tarjan { child++; par[i] = x; - // Initially low[i] is equal to low[x] low[i] = L[i] = L[x] + 1; dfs(i); - - // After the DFS, low[i] might have changed, in that case, low[x] - // should be updated if a lower value has been found low[x] = min(low[x], low[i]); - // If x is the root and has more than one child, or if it's not the - // root and the child i of x has no back edges, then x is an - // articulation vertex if ((par[x] == -1 && child > 1) || (par[x] != -1 && low[i] >= L[x])) arti.pb(x); - // If node i can't reach a node above x (has no back edges), then it - // the egde (x,i) is a bridge if (low[i] > L[x]) brid.pb(ii(x, i)); - // If i has been vis but it's not x's par, then i is "above" - // (has smaller level then x), meaning that the edge (x,i) - // is a "back edge" } else if (par[x] != i) low[x] = min(low[x], L[i]); } } - /// Applies tarjan algorithm and format articulations vector. void run() { - - // Apply tarjan in every component for (int i = 0; i < N; ++i) if (!vis[i]) dfs(i); - // Remove duplicates for articulations sort(all(arti)); arti.erase(unique(all(arti)), arti.end()); } diff --git a/algorithms/graph/bellman_ford.cpp b/algorithms/graph/bellman_ford.cpp index 6deb54a..0b21186 100644 --- a/algorithms/graph/bellman_ford.cpp +++ b/algorithms/graph/bellman_ford.cpp @@ -3,19 +3,12 @@ /// Complexity (Time): O(V*E) /// Complexity (Space): O(V + E) -struct Edge { - int u, v, w; - - Edge(int u, int v, int w) : - u(u), v(v), w(w) - {} -}; - -vector<Edge> graph; - struct BellmanFord { + struct Edge { int u, v, w; }; + int N; vector<int> dist; + vector<Edge> graph; BellmanFord(int N) : N(N), dist(N) @@ -25,14 +18,10 @@ struct BellmanFord { fill(all(dist), inf); } - /// Returns distance between s and d in a graph with N vertices - /// using bellman_ford. - /// @param s,d origin and destination vertices + // Returns distance between s and d. int run(int s, int d) { dist[s] = 0; - // Iterate through all edges N times computing the shortest distance - // to all vertices from s for (int i = 0; i < N; ++i) for (auto e : graph) if (dist[e.u] != inf && dist[e.u] + e.w < dist[e.v]) diff --git a/algorithms/graph/bfs.cpp b/algorithms/graph/bfs.cpp deleted file mode 100644 index 55c0ec8..0000000 --- a/algorithms/graph/bfs.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/// Breadth First Search (BFS) -/// -/// Complexity (Time): O(V + E) -/// Complexity (Space): O(V + E) - -vector<int> graph[MAX]; - -struct BFS { - int N; - vector<int> vis; - - BFS(int N) : - N(N), vis(N) - {} - - void init() { - fill(all(vis), 0); - } - - /// Applies BFS on graph. - /// @param x starting vertex - void run(int x) { - queue<int> Q; - - Q.push(x); - vis[x] = true; - - while (!Q.empty()) { - int v = Q.front(); Q.pop(); - - for (auto i : graph[v]) - if (!vis[i]) { - vis[i] = true; - Q.push(i); - } - } - } -}; diff --git a/algorithms/graph/bipartite_match.cpp b/algorithms/graph/bipartite_match.cpp index 304c7dd..c74383a 100644 --- a/algorithms/graph/bipartite_match.cpp +++ b/algorithms/graph/bipartite_match.cpp @@ -18,8 +18,7 @@ struct BipartiteMatching { fill(all(match), -1); } - /// Finds match for x. - /// @param x starting vertex + // Finds match for x. int dfs(int x) { if (vis[x]) return 0; @@ -34,9 +33,9 @@ struct BipartiteMatching { return 0; } - /// Returns number of left elements in matching and fills match array with - /// the match itself (match[right_i] = left_i). - /// @param n number of vertices on the left + // Returns number of left elements in matching and + // fills match array with the match itself + // (match[right_i] = left_i). int run() { int ans = 0; diff --git a/algorithms/graph/centroid_decomposition.cpp b/algorithms/graph/centroid_decomposition.cpp index 6952825..536a833 100644 --- a/algorithms/graph/centroid_decomposition.cpp +++ b/algorithms/graph/centroid_decomposition.cpp @@ -23,8 +23,6 @@ vector<int> graph[MAX]; struct CentroidDecomposition { vector<int> par, size, marked; - /// Constructor. - /// @param N number of vertices CentroidDecomposition(int N) : par(N), size(N), marked(N) { init(); } @@ -36,9 +34,7 @@ struct CentroidDecomposition { build(0); } - /// Builds the centroid decomposition of the tree recursively. - /// @param x initial node (root) - /// @param p parent node + // Builds the centroid decomposition of the tree recursively. void build(int x, int p = -1) { int n = dfs(x); int centroid = get_centroid(x, n); @@ -51,9 +47,7 @@ struct CentroidDecomposition { build(i, centroid); } - /// Calculates size of every subtree (in the original tree). - /// @param x initial node - /// @param p parent node + // Calculates size of every subtree (in the original tree). int dfs(int x, int p = -1) { size[x] = 1; for (auto i : graph[x]) @@ -63,11 +57,8 @@ struct CentroidDecomposition { return size[x]; } - /// Finds centroid by recursively searching for it in the subtree - /// with more than n / 2 nodes in it. - /// @param x initial node - /// @param n size of initial subtree - /// @param p parent node + // Finds centroid by recursively searching for it in the subtree + // with more than n / 2 nodes in it. int get_centroid(int x, int n, int p = -1) { for (auto i : graph[x]) if (i != p && size[i] > n / 2 && !marked[i]) diff --git a/algorithms/graph/dfs.cpp b/algorithms/graph/dfs.cpp deleted file mode 100644 index a1e6fd6..0000000 --- a/algorithms/graph/dfs.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/// Depth First Search (DFS) -/// -/// Complexity (Time): O(V + E) -/// Complexity (Space): O(V + E) - -vector<int> graph[MAX]; - -struct DFS { - int N; - vector<bool> vis; - - DFS(int N) : - N(N), vis(N) - {} - - void init() { - fill(all(vis), 0); - } - - /// Applies DFS on graph. - /// @param x starting vertex - void run(int x) { - vis[x] = true; - for (auto i : graph[x]) - if (!vis[i]) - run(x); - } -} diff --git a/algorithms/graph/dijkstra.cpp b/algorithms/graph/dijkstra.cpp index a9e80b2..054ea2e 100644 --- a/algorithms/graph/dijkstra.cpp +++ b/algorithms/graph/dijkstra.cpp @@ -18,8 +18,7 @@ struct Dijkstra { fill(all(dist), inf); } - /// Returns shortest distance from s to d - /// @param s,d origin and destination vertices + // Returns shortest distance from s to d. int run(int s, int d) { set<ii> pq; @@ -37,7 +36,6 @@ struct Dijkstra { int v = i.fi; int wt = i.se; - // If the distance to v can be improved from d, improve it if (!vis[v] && dist[v] > dist[u] + wt) { dist[v] = dist[u] + wt; pq.insert(ii(dist[v], v)); diff --git a/algorithms/graph/dinic.cpp b/algorithms/graph/dinic.cpp index 9f6f315..b74d047 100644 --- a/algorithms/graph/dinic.cpp +++ b/algorithms/graph/dinic.cpp @@ -20,9 +20,7 @@ struct Dinic { N(N), depth(N), start(N), graph(N) {} - /// Adds edge to the graph. - /// @param s,t origin and destination of edge - /// @param c capacity of edge + // Adds edge (s, t) with capacity c to the graph. void add_edge(int s, int t, int c) { Edge forward(t, 0, c, graph[t].size()); Edge backward(s, 0, 0, graph[s].size()); @@ -31,9 +29,6 @@ struct Dinic { graph[t].pb(backward); } - /// Calculates depth of each vertex from source, considering only - /// edges with remaining capacity. - /// @param s,t source and sink of flow graph bool bfs(int s, int t) { queue<int> Q; Q.push(s); @@ -55,9 +50,6 @@ struct Dinic { return depth[t] != -1; } - /// Finds bottleneck flow and add to the edges belonging to the paths found. - /// @param s,t source and sink of flow graph - /// @param flow minimum flow so far int dfs(int s, int t, int flow) { if (s == t) return flow; @@ -79,8 +71,7 @@ struct Dinic { return 0; } - /// Returns maximum flow. - /// @param s,t source and sink of flow graph + // Returns maximum flow. int run(int s, int t) { int ans = 0; diff --git a/algorithms/graph/edmonds_karp.cpp b/algorithms/graph/edmonds_karp.cpp index 70a831c..e00bfa5 100644 --- a/algorithms/graph/edmonds_karp.cpp +++ b/algorithms/graph/edmonds_karp.cpp @@ -18,9 +18,6 @@ struct EdmondsKarp { fill(all(vis), 0); } - /// Finds if there's a path between s and t using non-full - /// residual edges. - /// @param s,t source and sink of flow graph bool bfs(int s, int t) { queue<int> Q; Q.push(s); @@ -44,23 +41,19 @@ struct EdmondsKarp { return false; } - /// Returns maximum flow. - /// @param s,t source and sink of flow graph + // Returns maximum flow. int run(int s, int t) { int ans = 0; par[s] = -1; memcpy(rg, graph, sizeof(graph)); - // Repeat while there's a valid path between s and t while (bfs(s, t)) { int flow = inf; - // Get the minimum capacity among all edges of the chosen path for (int i = t; par[i] != -1; i = par[i]) flow = min(flow, rg[par[i]][i]); - // Update residual graph for (int i = t; par[i] != -1; i = par[i]) { rg[par[i]][i] -= flow; rg[i][par[i]] += flow; diff --git a/algorithms/graph/floyd_warshall.cpp b/algorithms/graph/floyd_warshall.cpp index bae4c37..68fb43a 100644 --- a/algorithms/graph/floyd_warshall.cpp +++ b/algorithms/graph/floyd_warshall.cpp @@ -13,7 +13,7 @@ struct FloydWarshall { N(N) {} - /// Computes shortest path between all pairs of vertices. + // Fills dist matrix with result. int run() { for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) @@ -22,6 +22,7 @@ struct FloydWarshall { for (int k = 0; k < N; ++k) for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) - dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) + dist[i][j] = min(dist[i][j], + dist[i][k] + dist[k][j]) } }; diff --git a/algorithms/graph/ford_fulkerson.cpp b/algorithms/graph/ford_fulkerson.cpp index aff839c..7db674b 100644 --- a/algorithms/graph/ford_fulkerson.cpp +++ b/algorithms/graph/ford_fulkerson.cpp @@ -14,13 +14,8 @@ struct FordFulkerson { N(N), par(N), vis(N) {} - void init() { - fill(all(vis), 0); - } + void init() { fill(all(vis), 0); } - /// Finds if there's a path between s and t using non-full - /// residual edges. - /// @param s,t source and sink of flow graph bool dfs(int s, int t) { vis[s] = true; if (s == t) @@ -37,23 +32,19 @@ struct FordFulkerson { return false; } - /// Returns maximum flow. - /// @param s,t source and sink of flow graph + // Returns maximum flow. int run(int s, int t) { int ans = 0; par[s] = -1; memcpy(rg, graph, sizeof(graph)); - // Repeat while there's a valid path between s and t while (dfs(s, t)) { int flow = inf; - // Get the minimum capacity among all edges of the chosen path for (int i = t; par[i] != -1; i = par[i]) flow = min(flow, rg[par[i]][i]); - // Update residual graph for (int i = t; par[i] != -1; i = par[i]) { rg[par[i]][i] -= flow; rg[i][par[i]] += flow; diff --git a/algorithms/graph/hopcroft_karp.cpp b/algorithms/graph/hopcroft_karp.cpp index 598d358..877469d 100644 --- a/algorithms/graph/hopcroft_karp.cpp +++ b/algorithms/graph/hopcroft_karp.cpp @@ -20,9 +20,6 @@ struct HopcroftKarp { fill(all(matchR), 0); } - /// Builds an alternating level graph rooted at unmatched vertices in L - /// using BFS, and returns whether there is an augmenting path in the graph - /// or not. bool bfs() { queue<int> Q; @@ -53,9 +50,6 @@ struct HopcroftKarp { return (dist[0] != inf); } - /// Augments path starting in l if there is one, returns - /// whether a path was augmented or not. - /// @param l initial free vertex on the left bool dfs(int l) { if (l == 0) return true; @@ -74,7 +68,8 @@ struct HopcroftKarp { return false; } - /// Returns number of matched vertices on the left (matched edges). + // Returns number of matched vertices on the left + // (matched edges). int run() { int ans = 0; diff --git a/algorithms/graph/kosaraju.cpp b/algorithms/graph/kosaraju.cpp index efcbbc6..d0ccd4a 100644 --- a/algorithms/graph/kosaraju.cpp +++ b/algorithms/graph/kosaraju.cpp @@ -11,16 +11,10 @@ struct Kosaraju { stack<int> S; vector<int> vis; - Kosaraju(int N) : - N(N), vis(N) - {} + Kosaraju(int N) : N(N), vis(N) {} - void init() { - fill(all(vis), 0); - } + void init() { fill(all(vis), 0); } - /// Traverses a SCC. - /// @param x initial vertex void dfs(int x) { vis[x] = true; @@ -29,8 +23,7 @@ struct Kosaraju { dfs(i); } - /// Fills stack with DFS starting points to find SCC. - /// @param x initial vertex + // Fills stack with DFS starting points to find SCC. void fill_stack(int x) { vis[x] = true; @@ -41,7 +34,7 @@ struct Kosaraju { S.push(x); } - /// Returns number of SCC of a graph. + // Returns number of SCC of a graph. int run() { int scc = 0; diff --git a/algorithms/graph/kruskal.cpp b/algorithms/graph/kruskal.cpp index e12f0f9..a48ee1f 100644 --- a/algorithms/graph/kruskal.cpp +++ b/algorithms/graph/kruskal.cpp @@ -12,20 +12,17 @@ struct Kruskal { int N; DisjointSet ds; - Kruskal(int N) : - N(N), ds(N) - {} + Kruskal(int N) : N(N), ds(N) {} - /// Returns value of MST. - /// @param mst[out] vector with edges of computed MST + // Returns value of MST. int run(vector<iii> &mst) { // Sort by weight of the edges sort(all(edges), [&](const iii &a, const iii &b) { - return a.se < b.se; // ('>' for maximum spanning tree) + // ('>' for maximum spanning tree) + return a.se < b.se; }); - int size = 0; for (int i = 0; i < N; i++) ds.make_set(i); @@ -34,7 +31,8 @@ struct Kruskal { int pu = ds.find_set(edges[i].fi.fi); int pv = ds.find_set(edges[i].fi.se); - // If the sets are different, then the edge i does not close a cycle + // If the sets are different, then the edge i does + // not close a cycle if (pu != pv) { mst.pb(edges[i]); size += edges[i].se; diff --git a/algorithms/graph/lca.cpp b/algorithms/graph/lca.cpp index 177510e..66b1c2d 100644 --- a/algorithms/graph/lca.cpp +++ b/algorithms/graph/lca.cpp @@ -26,15 +26,16 @@ struct LCA { fill(all(i), -1); for (auto &i : cost) fill(all(i), 0); - dfs(0); // Assuming root is 0 + + // Assuming root is 0 + dfs(0); } inline int op(int a, int b) { - return a + b; // or max(a, b) + // or max(a, b) + return a + b; } - /// Performs DFS while filling h, par, and cost. - /// @param v root of the tree void dfs(int v, int p = -1, int c = 0) { par[v][0] = p; cost[v][0] = c; @@ -45,7 +46,9 @@ struct LCA { for (int i = 1; i < MAXLOG; ++i) if (par[v][i - 1] != -1) { par[v][i] = par[par[v][i - 1]][i - 1]; - cost[v][i] = op(cost[v][i], op(cost[par[v][i-1]][i-1], cost[v][i-1])); + cost[v][i] = op(cost[v][i], + op(cost[par[v][i-1]][i-1], + cost[v][i-1])); } for (auto u : graph[v]) @@ -53,8 +56,7 @@ struct LCA { dfs(u.fi, v, u.se); } - /// Returns LCA (or sum or max). - /// @param p,q query nodes + // Returns LCA (or sum or max). int query(int p, int q) { int ans = 0; @@ -77,7 +79,7 @@ struct LCA { for (int i = MAXLOG - 1; i >= 0; --i) if (par[p][i] != -1 && par[p][i] != par[q][i]) { - ans = op(ans, op(cost[p][i], cost[q][i])); // * + ans = op(ans, op(cost[p][i], cost[q][i])); p = par[p][i]; q = par[q][i]; } diff --git a/algorithms/graph/prim.cpp b/algorithms/graph/prim.cpp index ac51f93..729cf83 100644 --- a/algorithms/graph/prim.cpp +++ b/algorithms/graph/prim.cpp @@ -17,18 +17,15 @@ struct Prim { fill(all(vis), 0); } - /// Returns value of MST of graph. + // Returns value of MST of graph. int run() { init(); vis[0] = true; - // Add negative values to pq in order to give priority - // to the edge with the smallest weight priority_queue<ii> pq; for (auto i : graph[0]) pq.push(ii(-i.se, -i.fi)); - // At each step, connect vertex with smallest weight to the MST int ans = 0; while (!pq.empty()) { ii front = pq.top(); pq.pop(); diff --git a/algorithms/graph/tarjan.cpp b/algorithms/graph/tarjan.cpp index ce9b170..61cd3ec 100644 --- a/algorithms/graph/tarjan.cpp +++ b/algorithms/graph/tarjan.cpp @@ -3,11 +3,8 @@ /// Complexity (Time): O(V + E) /// Complexity (Space): O(V + E) -vector<int> graph[MAX]; - -/// scc[i] contains the i-th SCC stored as a vector with the ids of the -/// vertices in it vector<int> scc[MAX]; +vector<int> graph[MAX]; struct Tarjan { int N, ncomp, ind; @@ -24,8 +21,6 @@ struct Tarjan { fill(all(vis), 0); } - /// Fills SCC with strongly connected components of graph. - /// @param x any vertex void dfs(int x) { id[x] = low[x] = ind++; vis[x] = 1; @@ -35,13 +30,7 @@ struct Tarjan { for (auto i : graph[x]) if (id[i] == -1) { dfs(i); - - // After the DFS, low[i] might have changed, in that case, low[x] - // should be updated if a lower value has been found low[x] = min(low[x], low[i]); - - // If i has been visited, then i is "above" (has smaller id then x), - // meaning that the edge (x,i) is a "back edge" } else if (vis[i]) low[x] = min(low[x], id[i]); @@ -49,7 +38,6 @@ struct Tarjan { if (low[x] == id[x]) { int w; - // Every node on top of x in the stack belongs to the SCC found do { w = S.top(); S.pop(); vis[w] = 0; diff --git a/algorithms/graph/topological_sort.cpp b/algorithms/graph/topological_sort.cpp index 0583af4..61390dd 100644 --- a/algorithms/graph/topological_sort.cpp +++ b/algorithms/graph/topological_sort.cpp @@ -10,16 +10,12 @@ struct TopologicalSort { stack<int> S; vector<int> vis; - TopologicalSort(int N) : - N(N), vis(N) - {} + TopologicalSort(int N) : N(N), vis(N) {} void init() { fill(all(vis), 0); } - /// Fills stack and check for cycles. - /// @param x any vertex bool dfs(int x) { vis[x] = 1; @@ -37,15 +33,13 @@ struct TopologicalSort { } /// Returns whether graph contains cycle or not. - /// @param[out] tsort topological sort of the graph bool run(vector<int> &tsort) { init(); bool cycle = false; - for (int i = 0; i < N; ++i) { + for (int i = 0; i < N; ++i) if (!vis[i]) cycle |= dfs(i); - } if (cycle) return true; diff --git a/algorithms/math/binary_exponentiation.cpp b/algorithms/math/binary_exponentiation.cpp index ff4bd97..65bca42 100644 --- a/algorithms/math/binary_exponentiation.cpp +++ b/algorithms/math/binary_exponentiation.cpp @@ -4,10 +4,6 @@ /// Complexity (Space): O(1) struct BinaryExponentiation { - - /// Returns x^n in O(log n) time - /// @param x number - /// @param n exponent ll fast_pow(ll x, ll n) { ll ans = 1; diff --git a/algorithms/math/euler_totient.cpp b/algorithms/math/euler_totient.cpp index 009c5fd..ee56b38 100644 --- a/algorithms/math/euler_totient.cpp +++ b/algorithms/math/euler_totient.cpp @@ -4,9 +4,6 @@ /// Complexity (space): O(1) struct EulerTotient { - - /// Returns phi(n) (i.e. the number of relative primes less than n) - /// @param n input number int run(int n) { int result = n; diff --git a/algorithms/math/fft.cpp b/algorithms/math/fft.cpp index f8e0193..dfc807b 100644 --- a/algorithms/math/fft.cpp +++ b/algorithms/math/fft.cpp @@ -10,24 +10,34 @@ struct FFT { Complex() : r(0), i(0) {} Complex(float r, float i) : r(r), i(i) {} - Complex operator+(Complex b) { return Complex(r + b.r, i + b.i); } - Complex operator-(Complex b) { return Complex(r - b.r, i - b.i); } - Complex operator*(Complex b) { return Complex(r*b.r - i*b.i, r*b.i + i*b.r); } + Complex operator+(Complex b) { + return Complex(r + b.r, i + b.i); + } + + Complex operator-(Complex b) { + return Complex(r - b.r, i - b.i); + } + + Complex operator*(Complex b) { + return Complex(r*b.r - i*b.i, r*b.i + i*b.r); + } Complex operator/(Complex b) { float div = (b.r * b.r) + (b.i * b.i); - return Complex((r * b.r + i * b.i) / div, (i * b.r - r * b.i) / div); + return Complex((r * b.r + i * b.i) / div, + (i * b.r - r * b.i) / div); } - // Returns complex conjugate - static inline Complex conj(Complex a) { return Complex(a.r, -a.i); } + static inline Complex conj(Complex a) { + return Complex(a.r, -a.i); + } }; vector<int> rev = {0, 1}; vector<Complex> roots = {{0, 0}, {1, 0}}; - /// Initializes reversed-bit vector (rev) and roots of unity vector (roots) - /// @param nbase log2 of size of vectors. + // Initializes reversed-bit vector (rev) and + // roots of unity vector (roots) void init(int nbase) { rev.resize(1 << nbase); roots.resize(1 << nbase); @@ -49,12 +59,9 @@ struct FFT { } } - /// Applies FFT on a vector. - /// @param a input vector void fft(vector<Complex> &a) { int n = a.size(); - // Change order of elements to match the end of recursion for (int i = 0; i < n; ++i) if (i < rev[i]) swap(a[i], a[rev[i]]); @@ -70,8 +77,6 @@ struct FFT { } } - /// Executes vector multiplication in O(n log n). - /// @param a, b input vectors vector<int> multiply(const vector<int> &a, const vector<int> &b) { int nbase, need = a.size() + b.size() + 1; @@ -81,7 +86,6 @@ struct FFT { int size = 1 << nbase; vector<Complex> fa(size); - // Assemble vector fa from a and b for (int i = 0; i < size; ++i) { int x = (i < a.size() ? a[i] : 0); int y = (i < b.size() ? b[i] : 0); @@ -90,7 +94,6 @@ struct FFT { fft(fa); - // Multiply vectors using magic Complex r(0, -0.25 / size); for (int i = 0; i <= (size >> 1); ++i) { int j = (size - i) & (size - 1); @@ -104,7 +107,6 @@ struct FFT { fft(fa); - // Obtain result vector vector<int> res(need); for (int i = 0; i < need; ++i) res[i] = fa[i].r + 0.5; diff --git a/algorithms/math/modular_multiplicative_inverse.cpp b/algorithms/math/modular_multiplicative_inverse.cpp index 57ae875..a602bb4 100644 --- a/algorithms/math/modular_multiplicative_inverse.cpp +++ b/algorithms/math/modular_multiplicative_inverse.cpp @@ -7,7 +7,6 @@ /// Used when m is prime /// #include "binary_exponentiation.cpp" -/// Finds x where: a*x === 1 (mod MOD) ll mod_inverse(ll a) { return fast_pow(a, MOD - 2); } @@ -16,7 +15,6 @@ ll mod_inverse(ll a) { /// ========== Extended Euclidean Algorithm ========== /// Used when m and a are coprime -/// Returns gcd(a, b) and find x, y where: a*x + b*y = gcd(a, b) ll gcd_extended(ll a, ll b, ll &x, ll &y) { if (!a) { x = 0; @@ -33,7 +31,6 @@ ll gcd_extended(ll a, ll b, ll &x, ll &y) { return g; } -/// Finds x where: a*x === 1 (mod MOD) ll mod_inverse(ll a) { ll x, y; ll g = gcd_extended(a, MOD, x, y); diff --git a/algorithms/math/sieve_of_eratosthenes.cpp b/algorithms/math/sieve_of_eratosthenes.cpp index 2979036..94f0cd9 100644 --- a/algorithms/math/sieve_of_eratosthenes.cpp +++ b/algorithms/math/sieve_of_eratosthenes.cpp @@ -3,31 +3,25 @@ /// Complexity (Time): O(n*log(log(n))) /// Complexity (Space): O(n) -/// Returns vector of primes less than or equal to n struct Sieve { int N; vector<int> is_prime; - Sieve(int N) : - N(N), is_prime(N + 1) - {} + Sieve(int N) : N(N), is_prime(N+1) {} void init() { fill(all(is_prime), 1); } - /// Returns vector of primes less than N vector<int> run() { vector<int> primes; init(); - // Mark which elements are not prime (multiples of p) for (int p = 2; p*p <= N; ++p) if (is_prime[p]) for (int i = p*p; i <= N; i += p) is_prime[i] = false; - // Add non-marked elements (primes) to the list for (int p = 2; p <= N; ++p) if (is_prime[p]) primes.pb(p); diff --git a/algorithms/paradigm/edit_distance.cpp b/algorithms/paradigm/edit_distance.cpp index c8f9d0d..dbafd1b 100644 --- a/algorithms/paradigm/edit_distance.cpp +++ b/algorithms/paradigm/edit_distance.cpp @@ -10,8 +10,6 @@ struct EditDistance { dp(N, vector<int>(M)) {} - /// Returns edit distance (Levenshtein distance) between a and b - /// @param a,b input strings int run(string a, string b) { for (int i = 0; i <= a.size(); ++i) for (int j = 0; j <= b.size(); ++j) @@ -22,7 +20,9 @@ struct EditDistance { else if (a[i-1] == b[j-1]) dp[i][j] = d[i-1][j-1]; else - dp[i][j] = 1 + min({dp[i][j-1], dp[i-1][j], dp[i-1][j-1]}); + dp[i][j] = 1 + min({dp[i][j-1], + dp[i-1][j], + dp[i-1][j-1]}); return dp[a.size()][b.size()]; } diff --git a/algorithms/paradigm/kadane.cpp b/algorithms/paradigm/kadane.cpp index b0fc99b..be9dcf6 100644 --- a/algorithms/paradigm/kadane.cpp +++ b/algorithms/paradigm/kadane.cpp @@ -4,28 +4,18 @@ /// Complexity (Space): O(n + m) struct Kadane { - - /// Returns the largest sum of a contiguous subarray - /// @param[in] v input vector - /// @param[out] start,end start and end index of said subarray int run(const vector<int> &v, int &start, int &end) { start = end = 0; - - // Maximum so far (msf), Maximum ending here (meh). int msf = -inf, meh = 0, s = 0; for (int i = 0; i < v.size(); ++i) { meh += v[i]; - // Store maximum so far as well as starting and ending position - // of the subsequence if (msf < meh) { msf = meh; start = s, end = i; } - // If maximum ending here is negative, then it's definitely - // better to restart if (meh < 0) { meh = 0; s = i + 1; diff --git a/algorithms/paradigm/lis.cpp b/algorithms/paradigm/lis.cpp index 2aa433e..e7e289d 100644 --- a/algorithms/paradigm/lis.cpp +++ b/algorithms/paradigm/lis.cpp @@ -4,9 +4,6 @@ /// Complexity (Space): O(n) struct LIS { - - /// Returns the length of the longest increasing subsequence - /// @param v input vector int run(vector<int> v) { vector<int> lis(v.size()); lis[0] = 1; diff --git a/algorithms/paradigm/ternary_search.cpp b/algorithms/paradigm/ternary_search.cpp index 3b00840..e90f8ff 100644 --- a/algorithms/paradigm/ternary_search.cpp +++ b/algorithms/paradigm/ternary_search.cpp @@ -5,13 +5,11 @@ struct TernarySearch { - /// Unimodal function + // Unimodal function double f(double x) { return x * x; } - /// Executes ternary search to find maximum or minimum - /// @param l,r boundaries of search double run(double l, double r) { double rt, lt; diff --git a/algorithms/string/kmp.cpp b/algorithms/string/kmp.cpp index 76357a3..4fee58d 100644 --- a/algorithms/string/kmp.cpp +++ b/algorithms/string/kmp.cpp @@ -13,8 +13,6 @@ struct KMP { patt(patt), table(patt.size()) { preprocess(); } - /// Builds the table where table[i] is the longest prefix of - /// patt[0..i] that is also a sufix of patt[0..i]. void preprocess() { int i = 1, len = 0; @@ -28,9 +26,6 @@ struct KMP { } } - /// Searches for occurrences of patt in txt and return vector - /// of the indices of occurrence. - /// @param txt text vector<int> search(const string &txt) { int i = 0, j = 0; vector<int> occurs; diff --git a/algorithms/string/z-function.cpp b/algorithms/string/z-function.cpp index 9ab2ed7..650405d 100644 --- a/algorithms/string/z-function.cpp +++ b/algorithms/string/z-function.cpp @@ -4,9 +4,6 @@ /// Complexity (space): O(n) struct ZFunction { - - /// Computes z-function of a string and returns it. - /// @param s input string vector<int> run(string s) { int n = (int) s.length(); vector<int> z(n); diff --git a/algorithms/structure/avl.cpp b/algorithms/structure/avl.cpp index b62bdcf..1a91ecd 100644 --- a/algorithms/structure/avl.cpp +++ b/algorithms/structure/avl.cpp @@ -13,28 +13,23 @@ struct AVL { left(nullptr), right(nullptr) {} - /// Change height based on the information on the left and right. void fix_height() { int lh = (left == nullptr) ? 0 : left->height; int rh = (right == nullptr) ? 0 : right->height; height = max(lh, rh) + 1; } - /// Change size based on the information on the left and right. void fix_size() { int ls = (left == nullptr) ? 0 : left->size; int rs = (right == nullptr) ? 0 : right->size; size = ls + rs + 1; } - /// Fix both height and size. void fix_state() { fix_height(); fix_size(); } - /// Returns difference between the height on the left and the - /// height on the right int get_balance() { int lh = (left == nullptr) ? 0 : left->height; int rh = (right == nullptr) ? 0 : right->height; @@ -44,55 +39,42 @@ struct AVL { Node *root; - AVL() : - root(nullptr) - {} + AVL() : root(nullptr) {} + + void insert(int key) { + root = insert(root, key); + } + +private: - /// Rotates node to right. - /// @param node input node Node *rotate_right(Node *node) { Node *aux1 = node->left; Node *aux2 = aux1->right; - aux1->right = node; node->left = aux2; - node->fix_state(); aux1->fix_state(); - return aux1; } - /// Rotates node to left. - /// @param node input node Node *rotate_left(Node *node) { Node *aux1 = node->right; Node *aux2 = aux1->left; - aux1->left = node; node->right = aux2; - node->fix_state(); aux1->fix_state(); - return aux1; } - /// Inserts key recursively in AVL and returns new root. - /// @param node root - /// @param key value to be inserted Node *insert(Node *node, int key) { if (node == nullptr) { - - // Create new node Node *new_node = new Node(key, 1, 1); if (root == nullptr) root = new_node; - return new_node; } - // Insert recursively if (key < node->key) node->left = insert(node->left, key); else @@ -101,17 +83,13 @@ struct AVL { int balance = node->get_balance(); node->fix_state(); - // Check balance of tree and rotates if necessary if (balance > 1 && key < node->left->key) { return rotate_right(node); - } else if (balance < -1 && key > node->right->key) { return rotate_left(node); - } else if (balance > 1 && key > node->left->key) { node->left = rotate_left(node->left); return rotate_right(node); - } else if (balance < -1 && key < node->right->key) { node->right = rotate_right(node->right); return rotate_left(node); @@ -119,10 +97,4 @@ struct AVL { return node; } - - /// Insert new key. - /// @param key value to be inserted - void insert(int key) { - root = insert(root, key); - } }; diff --git a/algorithms/structure/ball_tree.cpp b/algorithms/structure/ball_tree.cpp index 9a439e2..6ef5749 100644 --- a/algorithms/structure/ball_tree.cpp +++ b/algorithms/structure/ball_tree.cpp @@ -21,12 +21,10 @@ struct BallTree { build(points); } - /// Returns distance between point a and b double distance(point &a, point &b) { - return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); + return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)); } - /// Finds furthest point from center and returns <distance,index> of that point pair<double, int> get_radius(point ¢er, vector<point> &ps) { int ind = 0; double dist, radius = -1.0; @@ -43,9 +41,6 @@ struct BallTree { return pair<double, int>(radius, ind); } - /// Finds average point and pretends it's the center of the given set of points - /// @param ps vector of points - /// @param[out] center center point void get_center(const vector<point> &ps, point ¢er) { center.x = center.y = 0; @@ -58,14 +53,9 @@ struct BallTree { center.y /= (double) ps.size(); } - /// Splits the set of points in closer to ps[lind] and closer to ps[rind], - /// where lind is returned by get_radius and rind is the furthest points - /// from ps[lind] - /// @param ps vector of points - /// @param[out] left leftmost point - /// @param[out] right rightmost point - /// @param lind index of left point - void partition(const vector<point> &ps, vector<point> &left, vector<point> &right, int lind) { + void partition(const vector<point> &ps, vector<point> &left, + vector<point> &right, int lind) + { int rind = 0; double dist, grt = -1.0; double ldist, rdist; @@ -100,22 +90,17 @@ struct BallTree { } } - /// Builds ball-tree recursively. Node *build(vector<point> &ps) { if (ps.size() == 0) return nullptr; Node *n = new Node; - // When there's only one point in ps, a leaf node is created storing that - // point if (ps.size() == 1) { n->center = ps[0]; n->radius = 0.0; n->right = n->left = nullptr; - - // Otherwise, ps gets split into two partitions, one for each child } else { get_center(ps, n->center); auto rad = get_radius(n->center, ps); @@ -130,23 +115,16 @@ struct BallTree { return n; } - - /// Search the ball-tree recursively - /// @param n root - /// @param t query point - /// @param pq initially empty multiset (will contain the answer after execution) - /// @param k number of nearest neighbors + void search(Node *n, point t, multiset<double> &pq, int &k) { if (n->left == nullptr && n->right == nullptr) { double dist = distance(t, n->center); - // (!) Only necessary when the same point needs to be ignored if (dist < EPS) return; else if (pq.size() < k || dist < *pq.rbegin()) { pq.insert(dist); - if (pq.size() > k) pq.erase(prev(pq.end())); } diff --git a/algorithms/structure/bit.cpp b/algorithms/structure/bit.cpp index e2473e0..665f9ef 100644 --- a/algorithms/structure/bit.cpp +++ b/algorithms/structure/bit.cpp @@ -9,15 +9,10 @@ struct BIT { int N; vector<int> tree; - BIT(int N) : - N(N), tree(N) - {} + BIT(int N) : N(N), tree(N) {} - void init() { - fill(all(tree), 0); - } + void init() { fill(all(tree), 0); } - /// Performs query in array (tree) in the idx position. int query(int idx) { int sum = 0; for (; idx > 0; idx -= (idx & -idx)) @@ -26,7 +21,6 @@ struct BIT { return sum; } - /// Adds a value (val) to a single position (idx) in the array (tree). void update(int idx, int val) { for (; idx < N; idx += (idx & -idx)) tree[idx] += val; diff --git a/algorithms/structure/bit2d.cpp b/algorithms/structure/bit2d.cpp index 1c0f9ca..c20a664 100644 --- a/algorithms/structure/bit2d.cpp +++ b/algorithms/structure/bit2d.cpp @@ -18,7 +18,6 @@ struct BIT2D { fill(all(i), 0); } - /// Performs query in array (tree) in the (idx,idy) position. int query(int idx, int idy) { int sum = 0; for (; idx > 0; idx -= (idx & -idx)) @@ -28,7 +27,6 @@ struct BIT2D { return sum; } - /// Adds a value (val) to a single position (idx,idy) in the array (tree). void update(int idx, int idy, int val) { for (; idx < N; idx += (idx & -idx)) for (int m = idy; m < M; m += (m & -m)) diff --git a/algorithms/structure/bitmask.cpp b/algorithms/structure/bitmask.cpp index 0f63995..585ec9e 100644 --- a/algorithms/structure/bitmask.cpp +++ b/algorithms/structure/bitmask.cpp @@ -10,37 +10,30 @@ struct Bitmask { state(state) {} - /// Sets bit in position pos (0 to 1). void set(int pos) { state |= (1 << pos); } - /// Sets all bits in a bitmask with size n. void set_all(int n) { state = (1 << n) - 1; } - /// Unsets bit in position pos (1 to 0). void unset(int pos) { state &= ~(1 << pos); } - /// Unsets all bits. void unset_all() { state = 0; } - /// Gets value of bit in position pos. int get(int pos) { return state & (1 << pos); } - /// Toggles value in position pos. void toggle(int pos) { state ^= (1 << pos); } - /// Gets position of least significant 1. int least_significant_one() { return state & (-state); } diff --git a/algorithms/structure/disjoint_set.cpp b/algorithms/structure/disjoint_set.cpp index 076ab71..071860b 100644 --- a/algorithms/structure/disjoint_set.cpp +++ b/algorithms/structure/disjoint_set.cpp @@ -17,20 +17,17 @@ struct DisjointSet { make_set(i); } - /// Initializes element x. void make_set(int x) { par[x] = x; rank[x] = 0; } - /// Returns set index from element x. int find_set(int x) { if (par[x] != x) par[x] = find_set(par[x]); return par[x]; } - /// Makes x and y belong to the same set. void union_set(int x, int y) { x = find_set(x); y = find_set(y); diff --git a/algorithms/structure/lazy_segment_tree.cpp b/algorithms/structure/lazy_segment_tree.cpp index cd56303..4fbf1ad 100644 --- a/algorithms/structure/lazy_segment_tree.cpp +++ b/algorithms/structure/lazy_segment_tree.cpp @@ -10,7 +10,9 @@ int N; struct LazySegmentTree { vector<int> tree, lazy; - LazySegmentTree(const vector<int> &v) : tree(MAX*4), lazy(MAX*4) { + LazySegmentTree(const vector<int> &v) : + tree(MAX*4), lazy(MAX*4) + { init(); build(v); } @@ -23,9 +25,7 @@ struct LazySegmentTree { inline int left(int x) { return (x << 1); } inline int right(int x) { return (x << 1) + 1; } - /// Builds tree with elements from v (0-indexed). - /// @param v vector containing initial values - void build(const vector<int> &v, int node = 1, int a = 0, int b = N - 1) { + void build(const vector<int> &v, int node=1, int a=0, int b=N-1) { if (a > b) return; @@ -40,10 +40,6 @@ struct LazySegmentTree { tree[node] = tree[left(node)] + tree[right(node)]; } - /// Propagates value to tree and through lazy tree. - /// @param node node to change - /// @param a,b range of node - /// @param val value to be pushed void push(int node, int a, int b, int val) { tree[node] += val; // tree[node] += (b - a + 1) * val; (for Range Sum Query) @@ -56,10 +52,7 @@ struct LazySegmentTree { lazy[node] = 0; } - /// Updates segment [i,j] by adding value val. - /// @param i,j range - /// @param val value to be added - void update(int i, int j, int val, int node = 1, int a = 0, int b = N - 1) { + void update(int i, int j, int val, int node=1, int a=0, int b=N-1) { if (lazy[node] != 0) push(node, a, b, lazy[node]); @@ -77,9 +70,7 @@ struct LazySegmentTree { tree[node] = tree[left(node)] + tree[right(node)]; } - /// Returns sum of [i,j]. - /// @param i,j range - int query(int i, int j, int node = 1, int a = 0, int b = N - 1) { + int query(int i, int j, int node=1, int a=0, int b=N-1) { if (a > b || a > j || b < i) return 0; diff --git a/algorithms/structure/policy_tree.cpp b/algorithms/structure/policy_tree.cpp index eba528e..a9c8180 100644 --- a/algorithms/structure/policy_tree.cpp +++ b/algorithms/structure/policy_tree.cpp @@ -22,19 +22,17 @@ typedef tree< tree_order_statistics_node_update > set_t; -/// Demonstration of operations. void operations() { set_t S; - // Insert element in S S.insert(x); - - // Remove element from S S.erase(x); - // Returns iterator to the k-th largest element (counting from zero) + // Return iterator to the k-th largest element + // (counting from zero) int pos = *S.find_by_order(k); - // Returns the number of items strictly smaller than x + // Return the number of items strictly smaller + // than x int ord = S.order_of_key(x) } diff --git a/algorithms/structure/segment_tree.cpp b/algorithms/structure/segment_tree.cpp index 6367e56..5298d80 100644 --- a/algorithms/structure/segment_tree.cpp +++ b/algorithms/structure/segment_tree.cpp @@ -10,21 +10,19 @@ int N; struct SegmentTree { vector<int> tree; - SegmentTree(const vector<int> &v) : tree(MAX*4) { + SegmentTree(const vector<int> &v) : + tree(MAX*4) + { init(); build(v); } - void init() { - fill(all(tree), 0); - } + void init() { fill(all(tree), 0); } inline int left(int x) { return (x << 1); } inline int right(int x) { return (x << 1) + 1; } - /// Builds tree with elements from v (0-indexed). - /// @param v vector containing initial values - void build(const vector<int> &v, int node = 1, int a = 0, int b = N - 1) { + void build(const vector<int> &v, int node=1, int a=0, int b=N-1) { if (a > b) return; @@ -39,10 +37,7 @@ struct SegmentTree { tree[node] = tree[left(node)] + tree[right(node)]; } - /// Updates position idx by adding value val. - /// @param idx position - /// @param val value to be added - void update(int idx, int val, int node = 1, int a = 0, int b = N - 1) { + void update(int idx, int val, int node=1, int a=0, int b=N-1) { if (a > b || a > idx || b < idx) return; @@ -57,9 +52,7 @@ struct SegmentTree { tree[node] = tree[left(node)] + tree[right(node)]; } - /// Returns sum of [i,j]. - /// @param i,j range - int query(int i, int j, int node = 1, int a = 0, int b = N - 1) { + int query(int i, int j, int node=1, int a=0, int b=N-1) { if (a > b || a > j || b < i) return 0; diff --git a/algorithms/structure/sqrt_decomposition.cpp b/algorithms/structure/sqrt_decomposition.cpp index b37a582..c73a3ac 100644 --- a/algorithms/structure/sqrt_decomposition.cpp +++ b/algorithms/structure/sqrt_decomposition.cpp @@ -10,37 +10,26 @@ int v[MAX]; int block[MAX]; int block_size; -/// Update v[idx] with val. -/// @param idx index of v -/// @param val new value of v[idx] void update(int idx, int val) { block[idx / block_size] += val - v[idx]; v[idx] = val; } -/// Range sum query of v[l..r]. -/// @param l,r range int query(int l, int r) { int ans = 0; - // Query sum of elements in case l is inside a block for (; l < r && ((l % block_size) != 0); ++l) ans += v[l]; - // Query sum of each block between l and r for (; l + block_size <= r; l += block_size) ans += block[l / block_size]; - // Query sum of remaining blocks (e.g. r is inside a block) for (; l <= r; ++l) ans += v[l]; return ans; } -/// Fills block array with necessary data to perform update and query in -/// less than linear time. -/// @param n number of elements of v void preprocess(int n) { block_size = sqrt(n); diff --git a/algorithms/structure/trie.cpp b/algorithms/structure/trie.cpp index 9bdf697..0af8e62 100644 --- a/algorithms/structure/trie.cpp +++ b/algorithms/structure/trie.cpp @@ -9,8 +9,6 @@ struct Trie { int N, states; - /// ending[i] is true when the node i represents the last - /// char of a string contained in the Trie vector<int> ending; vector<vector<int>> trie; @@ -24,7 +22,6 @@ struct Trie { fill(all(i), -1); } - /// Inserts word into the Trie. void insert(string word) { int node = 0; @@ -39,7 +36,6 @@ struct Trie { ending[node] = true; } - /// Returns true if word is in the Trie. bool search(string word) { int node = 0; @@ -58,8 +54,6 @@ struct Trie { struct Trie { int N, states; - /// ending[i] is true when the node i represents the last - /// bit of an integer contained in the Trie vector<int> ending; vector<vector<int>> trie; @@ -73,7 +67,6 @@ struct Trie { fill(all(i), -1); } - /// Inserts x into the Trie. void insert(int x) { int node = 0; @@ -88,7 +81,6 @@ struct Trie { ending[node] = true; } - /// Returns true if x is in the Trie. bool search(int x) { int node = 0; diff --git a/gen_notebook b/gen_notebook index 823f912..9366504 100755 --- a/gen_notebook +++ b/gen_notebook @@ -7,8 +7,10 @@ else tex_file=$(mktemp) python3 notebook/gen_latex.py --header=notebook/header.tex --output=$tex_file - pdflatex $tex_file -output-directory . && - pdflatex $tex_file -output-directory . + #pdflatex $tex_file -halt-on-error -output-directory . && + #pdflatex $tex_file -halt-on-error -output-directory . + lualatex $tex_file -halt-on-error -output-directory . && + lualatex $tex_file -halt-on-error -output-directory . mv tmp.pdf caderno.pdf rm tmp* diff --git a/notebook/gen_latex.py b/notebook/gen_latex.py index c42922a..8327fb8 100644 --- a/notebook/gen_latex.py +++ b/notebook/gen_latex.py @@ -44,50 +44,61 @@ class LatexGenerator: self.tree = tree self.files = {} - self.hierarchy = ['part', 'chapter'] + [i*'sub' + 'section' for i in range(3)] + #self.hierarchy = ['part', 'chapter'] + \ + # [i*'sub' + 'section' for i in range(3)] + self.hierarchy = ['chapter'] + \ + [i*'sub' + 'section' for i in range(3)] self._add_header() self.gen_latex(tree) - self.output.write('\\end{document}') + self._write('\\end{document}') + + def _write(self, text): + self.output.write(text) # Adds Latex header to the output. def _add_header(self): lines = self.header.readlines() for i in lines: - self.output.write(i) - self.output.write('\\newpage\n') - self.output.write('\n') + self._write(i) + + self._write('\\begin{document}\n') + self._write('\\tableofcontents\n') + self._write('\\newpage\n') + self._write('\n') # Prints section title in Latex format. def gen_title_latex(self, content, depth): - self.output.write('\\' + self.hierarchy[depth] + '{' + content + '}' + '\n') + self._write('\\%s{%s}\n' % (self.hierarchy[depth], content)) # Prints code in Latex format. def gen_code_latex(self, path): - # TODO: Add code parsing funcion to extract text + # TODO: Add code parsing funcion to extract text from comments suffix = path.split('.')[-1] - self.output.write('\\begin{lstlisting}[style=custom%s]\n' % suffix) + self._write('\\begin{lstlisting}[style=custom%s]\n' % suffix) with open(path) as f: lines = f.readlines() for i in lines: - self.output.write(i) + self._write(i) - self.output.write('\\end{lstlisting}\n') - self.output.write('\n') + self._write('\\end{lstlisting}\n') + self._write('\n') # Generates Latex for entire tree recursively def gen_latex(self, sub, path = '', depth = 0): if type(sub) == list: + self._write('\\begin{multicols}{2}\n') for i in sub: self.gen_title_latex(self._parse_file_name(path + i), depth) self.gen_code_latex(path + i) + self._write('\\end{multicols}\n') else: for i in sub: self.gen_title_latex(self._parse_dir_name(i), depth) self.gen_latex(sub[i], path + i + '/', depth + 1) - self.output.write('\n') + self._write('\n') # Parses name of the section (capitalize) def _parse_dir_name(self, name): diff --git a/notebook/header.tex b/notebook/header.tex index 163ead9..8a182fe 100644 --- a/notebook/header.tex +++ b/notebook/header.tex @@ -1,29 +1,34 @@ \documentclass[oneside]{book} \usepackage{listings} \usepackage{titlesec} -\usepackage[a4paper, total={6in, 8in}]{geometry} +\usepackage{fontspec} +\usepackage{multicol} +\usepackage[a4paper,landscape,hmargin={0.5cm,0.5cm},vmargin={1.0cm,0.4cm}]{geometry} + +\setmonofont{Ubuntu Mono} +\setlength{\columnseprule}{1pt} +\def\columnseprulecolor{\color{black}} \geometry{ a4paper, left=20mm, - right=10mm, + right=20mm, top=1in, bottom=1in, } -\titleformat*{\subsubsection}{\Large\bfseries} +\titleformat*{\subsubsection}{\large\bfseries} +\titleformat*{\subsection}{\large\bfseries} +\titleformat*{\section}{\large\bfseries} \lstdefinestyle{customcpp}{ - frame=single, language=C++, - basicstyle=\small, + basicstyle=\footnotesize\ttfamily, tabsize=2, breaklines=true, morekeywords={int32\_t, ll} } \lstdefinestyle{customvim}{ frame=single, - basicstyle=\small, + basicstyle=\footnotesize\ttfamily, tabsize=2, breaklines=true, morekeywords={set} } -\begin{document} -\tableofcontents -- GitLab