\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{Hackin7} \pdfinfo{ /Title (c-graph-theory-sample.pdf) /Creator (Cheatography) /Author (Hackin7) /Subject (C++ Graph Theory Sample Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{92D9EB} \definecolor{LightBackground}{HTML}{F1FAFC} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{C++ Graph Theory Sample Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{Hackin7} via \textcolor{DarkBackground}{\uline{cheatography.com/71996/cs/20334/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}Hackin7 \\ \uline{cheatography.com/hackin7} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Published 21st August, 2019.\\ Updated 27th December, 2019.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{3} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Representation}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{///Adjacency \seqsplit{Matrix////////////////////} \newline int V, E, A, B, W, g{[}1005{]}{[}1005{]}; \newline cin \textgreater{}\textgreater{} V \textgreater{}\textgreater{} E; memset(g, -1, sizeof(g)); \newline for (int i = 0; i \textless{} E; i++) \{ \newline cin \textgreater{}\textgreater{} A \textgreater{}\textgreater{} B \textgreater{}\textgreater{} W; \newline //Weight, can set for both or single direction \newline g{[}A{]}{[}B{]} = W; \newline g{[}B{]}{[}A{]} = W; \newline \} \newline \newline ///Adjacency \seqsplit{List//////////////////////} \newline vector\textless{}pair\textless{}int, int\textgreater{} \textgreater{} g{[}1005{]}; \newline int V, E, A, B, W; \newline cin \textgreater{}\textgreater{} V \textgreater{}\textgreater{} E; \newline for (int i = 0; i \textless{} E; i++) \{ \newline cin \textgreater{}\textgreater{} A \textgreater{}\textgreater{} B \textgreater{}\textgreater{} W; \newline g{[}A{]}.push\_back(make\_pair(B, W)); \newline g{[}B{]}.push\_back(make\_pair(A, W)); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Floyd-Warshall}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{//initialise dist{[}i{]}{[}j{]} to infinity at the start \newline for (int k=0;k\textless{}n;k++) \newline for (int i=0;i\textless{}n;i++) \newline for (int j=0;j\textless{}n;j++) \newline // if there is a shorter path through node k, take it! \newline dist{[}i{]}{[}j{]} = min(dist{[}i{]}{[}j{]}, dist{[}i{]}{[}k{]}+dist{[}k{]}{[}j{]});w} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Floyd-Warshall algorithm uses the idea of triangle inequality, and is very \newline easy to code (just 4 lines!) \newline \newline If there are negative cycles, dist{[}i{]}{[}i{]} will be negative. Note the order!!!} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Prim's Algorithm}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{//Lol just copied from hackerearth website \newline \#include \textless{}iostream\textgreater{} \newline \#include \textless{}vector\textgreater{} \newline \#include \textless{}queue\textgreater{} \newline \#include \textless{}functional\textgreater{} \newline \#include \textless{}utility\textgreater{} \newline \newline using namespace std; \newline const int MAX = 1e4 + 5; \newline typedef pair\textless{}long long, int\textgreater{} PII; \newline bool marked{[}MAX{]}; \newline vector \textless{}PII\textgreater{} adj{[}MAX{]}; \newline \newline long long prim(int x) \newline \{ \newline priority\_queue\textless{}PII, vector\textless{}PII\textgreater{}, greater\textless{}PII\textgreater{} \textgreater{} Q; \newline int y; \newline long long minimumCost = 0; \newline PII p; \newline Q.push(make\_pair(0, x)); \newline while(!Q.empty()) \newline \{ \newline // Select the edge with minimum weight \newline p = Q.top(); \newline Q.pop(); \newline x = p.second; \newline // Checking for cycle \newline if(marked{[}x{]} == true) \newline continue; \newline minimumCost += p.first; \newline marked{[}x{]} = true; \newline for(int i = 0;i \textless{} adj{[}x{]}.size();++i) \newline \{ \newline y = adj{[}x{]}{[}i{]}.second; \newline if(marked{[}y{]} == false) \newline Q.push(adj{[}x{]}{[}i{]}); \newline \} \newline \} \newline return minimumCost; \newline \} \newline \newline int main() \newline \{ \newline int nodes, edges, x, y; \newline long long weight, minimumCost; \newline cin \textgreater{}\textgreater{} nodes \textgreater{}\textgreater{} edges; \newline for(int i = 0;i \textless{} edges;++i) \newline \{ \newline cin \textgreater{}\textgreater{} x \textgreater{}\textgreater{} y \textgreater{}\textgreater{} weight; \newline adj{[}x{]}.push\_back(make\_pair(weight, y)); \newline adj{[}y{]}.push\_back(make\_pair(weight, x)); \newline \} \newline // Selecting 1 as the starting node \newline minimumCost = prim(1); \newline cout \textless{}\textless{} minimumCost \textless{}\textless{} endl; \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Used to Construct MST from Graph} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Lowest Common Ancestor of Tree}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{ll lca(ll N,ll a,ll b)\{ \newline if(depth{[}a{]}\textless{}depth{[}b{]}) swap(a,b); \newline //Equalise depth \newline for(ll k=log2(N);k\textgreater{}=0;k-{}-)\{ \newline ll parent = find\_parent(a,k);//p{[}a{]}{[}k{]} \newline if(parent!=-1 \&\& depth{[}parent{]}\textgreater{}=depth{[}b{]})\{ \newline a=parent; \newline \} \newline \} \newline if (a==b)return a; \newline //Jump parent by parent \newline for(ll k=log2(N);k\textgreater{}=0;k-{}-)\{ \newline ll parent = find\_parent(a,k);//p{[}a{]}{[}k{]} \newline ll parentb = find\_parent(b,k);//p{[}b{]}{[}k{]} \newline if(parent!=parentb)a=parent,b=parentb; \newline \} \newline return p{[}a{]}{[}0{]}; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Requires 2k Decomposition of Parents} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Breadth First Search}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{vector\textless{}int\textgreater{} g{[}100005{]}; \newline queue\textless{}pair\textless{}int, int\textgreater{} \textgreater{} q; \newline int dist{[}1000005{]}; \newline fill(dist, dist+1000005, -1); \newline while (!q.empty()) \{ \newline int v = q.front().first; \newline int d = q.front().second; \newline q.pop(); \newline if (dist{[}v{]} != -1) continue; //Visited \newline dist{[}v{]} = d; \newline for (int i = 0; i \textless{} g{[}v{]}.size(); i++) \{ \newline q.push(make\_pair(g{[}v{]}{[}i{]}, d+1)); \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Time Complexity: O(|V| + |E|) \newline Space Complexity: O(b\textasciicircum{}d) \newline where d is the depth of the graph and b is the branching factor. \newline \newline BFS is more suitable when the goal is close to the source, BFS is still faster in such cases. \newline \newline We can use this algorithm to find the shortest path in a grid/unweighted \newline graph} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Bellman-Ford}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{dist{[}s{]}=0; //dist all others = INF \newline for (int i=0; i\textless{}N-1; i++)\{ \newline for (int j=0; j\textless{}E; j++)\{ \newline // if path is shorter through node u, take it! \newline dist{[}v{]} = min(dist{[}v{]}, dist{[}u{]}+cost); \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Solves the Single Source Shortest Path (SSSP) problem. (shortest path from one node (source) to all other nodes) \newline Can be used with negative edges, Run the algorithm twice to detect for negative cycles \newline \newline Time Complexity: O(VE) \newline Space Complexity: O(V)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Union Find Data Structure}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{int root (int x ) \{ \newline if (x == parent {[}x{]}) return x ; \newline return root (parent{[}x{]}) ; \newline \} \newline bool is\_connected (int x,int y) \{ \newline return root (x) == root(y) ; \newline \} \newline void connect ( int x , int y ) \{ \newline int root\_x = root (x); \newline int root\_y = root (y); \newline if (root\_x != root\_y) \newline parent {[}root\_x{]} = root\_y ; \newline \} \newline \newline ////For \seqsplit{Ranking//////////////////////} \newline int rank{[}N{]}; \newline void connect (int x , int y) \{ \newline int root\_x = root (x) , root\_y = root (y) ; \newline if (root\_x == root\_y) return ; // same root \newline if (rank{[}root\_x{]} \textgreater{} rank{[}root\_y{]}) \{ \newline parent{[}root\_y{]} = root\_x ; \newline \} else if (rank{[}root\_x{]} \textless{} rank{[}root\_y{]}) \{ \newline parent{[}root\_x{]} = root\_y ; \newline \} else \{ \newline parent{[}root\_y{]} = root\_x ; \newline rank{[}root\_x{]}++; \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Kruskal's Algorithm for MST}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{vector \textless{}tuple\textless{}int,int,int\textgreater{} \textgreater{} edges ; // weight,node A,node B \newline sort (edges.begin(), edges.end ()) ; \newline int total\_weight = 0; \newline for (auto e : edges) \{ \newline int weight, a, b; \newline tie (weight,a,b) = e ; \newline if (root(a) == root(b)) // taking this edge will cause a cycle \newline continue; \newline total\_weight += weight ; // take this edge \newline connect (a, b) ; // connect them in the UFDS \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Sort the list of edges by weight \newline For each edge in ascending order: If both nodes aren't already \newline connected, take it. Else, skip this edge. \newline Time complexity: O(E log V) (but faster than Prim's algorithm in \newline practice) \newline UFDS is needed to check if the nodes are connected in (2).} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Depth First Search}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{bool vis{[}N{]}; \newline vector\textless{}int\textgreater{} adjList{[}N{]}; \newline void dfs(int node) \{ \newline if (vis{[}node{]}) return; \newline vis{[}node{]} = true; \newline for (int a = 0; a \textless{} (int)adjList{[}node{]}.size(); ++a) \newline dfs(adjList{[}node{]}{[}a{]}); \newline \} \newline \newline ///Iterative//////////////////////////////// \newline bool vis{[}N{]}; \newline vector\textless{}int\textgreater{} adjList{[}N{]}; \newline stack\textless{}int\textgreater{} S; \newline while (!S.empty()) \{ \newline int node = S.top(); \newline S.pop(); \newline if (vis{[}node{]}) continue; \newline vis{[}node{]} = true; \newline for (int a = 0; a \textless{} (int)adjList{[}node{]}.size(); ++a) \newline S.push(adjList{[}node{]}{[}a{]}); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{DFS uses O(d) space, where d is the depth of the graph \newline \newline DFS is not suited for infinite graphs. \newline \newline Some applications of DFS include: \newline 1. Topological Ordering (covered later) \newline 2. Pre-/In-/Post-order numbering of a tree \newline 3. Graph connectivity \newline 4. Finding articulation points \newline 5. Finding bridges} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Dijkstra's Algorithm}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{vector\textless{}pair\textless{}int,int\textgreater{} \textgreater{} adjList{[}10000{]}; // node, weight \newline priority\_queue\textless{}pair\textless{}int,int\textgreater{}, vector\textless{}pair\textless{}int,int\textgreater{} \textgreater{}, greater\textless{}pair\textless{}int,int\textgreater{} \textgreater{} \textgreater{} pq; // distance, node \newline int dist{[}10000{]}; \newline memset(dist, -1, sizeof(dist)); \newline pq.push(make\_pair(0, source)); dist{[}0{]} = 0; \newline while(!pq.empty())\{ \newline pair\textless{}int,int\textgreater{} c = pq.top(); \newline pq.pop(); \newline if(c.first != dist{[}c.second{]}) continue; \newline for(auto i : adjList{[}c.second{]})\{ \newline if(dist{[}i.first{]} == -1 || dist{[}i.first{]} \textgreater{} c.first + i.second)\{ \newline dist{[}i.first{]} = c.first + i.second; \newline pq.push(make\_pair(dist{[}i.first{]}, i.first)); \newline \} \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Time Complexity of our implementation: O(E log E) \newline Space Complexity: O(V+E) \newline \newline Solves the Single Source Shortest Path (SSSP) problem. Means shortest path from one node to all other nodes. Cannot be used with negative edges as it runs too slow \newline Especially cannot be used with negative cycles} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{2k Parent Decomposition}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{typedef long long ll; \newline ll p{[}V{]}{[}K{]}; //node,kth ancestor \newline //DFS to compute node parents for p{[}i{]}{[}0{]}, first parent \newline bool visited{[}V{]}; \newline ll depth{[}V{]}; \newline void dfs(ll x)\{ \newline if (visited{[}x{]})return; \newline visited{[}x{]}=true; \newline for (auto i:adjlist{[}x{]})\{ \newline if (!visited{[}i.first{]})\{ \newline if (p{[}i.first{]}{[}0{]} == -1)\{ \newline //cout\textless{}\textless{}i.first\textless{}\textless{}"\textless{}-"\textless{}\textless{}x\textless{}\textless{}endl; \newline p{[}i.first{]}{[}0{]} = x; \newline depth{[}i.first{]} = depth{[}x{]}+1; \newline \} \newline dfs(i.first); \newline \} \newline \} \newline \} \newline void calc\_k\_parents(ll N)\{ \newline for (ll k=1;k\textless{}K;k++)\{ \newline for (ll i=0;i\textless{}N;i++)\{ \newline if (p{[}i{]}{[}k-1{]} != -1)\{ \newline p{[}i{]}{[}k{]}= p{[}p{[}i{]}{[}k-1{]}{]}{[}k-1{]}; \newline \}else\{p{[}i{]}{[}k{]}=-1;\} \newline // if (k==2)cout\textless{}\textless{}i\textless{}\textless{}","\textless{}\textless{}k\textless{}\textless{}":"\textless{}\textless{}p{[}i{]}{[}k-1{]}\textless{}\textless{}","\textless{}\textless{}p{[}p{[}i{]}{[}k-1{]}{]}{[}k-1{]}\textless{}\textless{}","\textless{}\textless{}p{[}i{]}{[}k{]}\textless{}\textless{}endl; \newline \newline \} \newline \} \newline \} \newline ll find\_parent(ll x,ll k)\{ \newline for (ll i=K;i\textgreater{}=0;i-{}-)\{ \newline if (k\textgreater{}= (1\textless{}\textless{}i))\{ \newline if (x==-1)return -1; \newline x=p{[}x{]}{[}i{]}; \newline k-=1\textless{}\textless{}i; \newline \} \newline \} \newline return x; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}