0% found this document useful (0 votes)
192 views4 pages

C++ Graph Theory Sample Cheat Sheet: by Via

This document provides code snippets and explanations for various graph algorithms including Prim's algorithm, breadth-first search, Floyd-Warshall algorithm, Bellman-Ford algorithm, and union find data structure. It represents graphs using both adjacency matrix and adjacency list representations. Prim's algorithm and breadth-first search are explained in pseudocode. Complexities of algorithms like breadth-first search are also provided.

Uploaded by

Võ Tuấn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
192 views4 pages

C++ Graph Theory Sample Cheat Sheet: by Via

This document provides code snippets and explanations for various graph algorithms including Prim's algorithm, breadth-first search, Floyd-Warshall algorithm, Bellman-Ford algorithm, and union find data structure. It represents graphs using both adjacency matrix and adjacency list representations. Prim's algorithm and breadth-first search are explained in pseudocode. Complexities of algorithms like breadth-first search are also provided.

Uploaded by

Võ Tuấn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

C++ Graph Theory Sample Cheat Sheet

by Hackin7 via cheatography.com/71996/cs/20334/

Repres​ent​ation Prim's Algorithm Prim's Algorithm (cont)

///Adjacency //Lol just copied from ​ ​ ​ ​ ​ ​ ​ ​for(int i = 0;i <


Matrix//////////////////// hackerearth website adj[x].si​ze(​);++i)
int V, E, A, B, W, g[1005​][1​‐ #include <io​str​eam> ​ ​ ​ ​ ​ ​ ​ {
005]; #include <ve​cto​r> ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ y = adj[x]​[i].se​‐
cin >> V >> E; memset(g, -1, #include <qu​eue> cond;
sizeof​(g)); #include <fu​nct​ion​al> ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​if(​mar​ked[y] ==
for (int i = 0; i < E; i++) { #include <ut​ili​ty> false)
​ ​ ​ cin >> A >> B >> W; using namespace std; ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​Q.p​ush​(ad​j[x​]
​ ​ ​ ​//W​eight, can set for both const int MAX = 1e4 + 5; [i]);
or single direction typedef pair<long long, int> ​ ​ ​ ​ ​ ​ ​ }
​ ​ ​ ​g[A][B] = W; PII; ​ ​ ​ }
​ ​ ​ ​g[B][A] = W; bool marked​[MAX]; ​ ​ ​ ​return minimu​mCost;
} vector <PI​I> adj[MAX]; }
///Adj​acency long long prim(int x) int main()
List//​///​///​///​///​///​///// { {
vector​<pa​ir<int, int> > g[1005]; ​ ​ ​ ​pri​ori​ty_​que​ue<PII, vector​‐ ​ ​ ​ int nodes, edges, x, y;
int V, E, A, B, W; <PI​I>, greate​r<P​II> > Q; ​ ​ ​ long long weight, minimu​‐
cin >> V >> E; ​ ​ ​ int y; mCost;
for (int i = 0; i < E; i++) { ​ ​ ​ long long minimu​mCost = 0; ​ ​ ​ cin >> nodes >> edges;
​ ​ ​ cin >> A >> B >> W; ​ ​ ​ PII p; ​ ​ ​ ​for(int i = 0;i < edges;++i)
​ ​ ​ ​g[A​].p​ush​_ba​ck(​mak​e_p​air(B, ​ ​ ​ ​Q.p​ush​(ma​ke_​pair(0, x)); ​ ​ ​ {
W)); ​ ​ ​ ​whi​le(​!Q.e​mp​ty()) ​ ​ ​ ​ ​ ​ ​ cin >> x >> y >> weight;
​ ​ ​ ​g[B​].p​ush​_ba​ck(​mak​e_p​air(A, ​ ​ ​ { ​ ​ ​ ​ ​ ​ ​ ​adj​[x].pu​sh_​bac​k(m​ake​‐
W)); ​ ​ ​ ​ ​ ​ ​ // Select the edge with _pa​ir(​weight, y));
} minimum weight ​ ​ ​ ​ ​ ​ ​ ​adj​[y].pu​sh_​bac​k(m​ake​‐
​ ​ ​ ​ ​ ​ ​ p = Q.top(); _pa​ir(​weight, x));
Floyd-​War​shall ​ ​ ​ ​ ​ ​ ​ ​Q.p​op(); ​ ​ ​ }

//initialise dist[i][j] to ​ ​ ​ ​ ​ ​ ​ x = p.second; ​ ​ ​ // Selecting 1 as the

infinity at the start ​ ​ ​ ​ ​ ​ ​ // Checking for cycle starting node

for (int k=0;k<​n;k++) ​ ​ ​ ​ ​ ​ ​ ​if(​mar​ked[x] == true) ​ ​ ​ ​min​imu​mCost = prim(1);

​ ​ ​ for (int i=0;i<​n;i++) ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​con​tinue; ​ ​ ​ cout << minimu​mCost << endl;

​ ​ ​ ​ ​ ​ ​ for (int j=0;j<​n;j++) ​ ​ ​ ​ ​ ​ ​ ​min​imu​mCost += p.first; ​ ​ ​ ​return 0;

​ ​ ​ ​ ​ ​ ​ // if there is a shorter ​ ​ ​ ​ ​ ​ ​ ​mar​ked[x] = true; }

path through node k, take it! Used to Construct MST from Graph
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​dis​t[i][j] = min(di​‐
st[​i][j], dist[i​][k​]+d​ist​[k]​‐
[j]);w

Floyd-​War​shall algorithm uses the idea of


triangle inequa​lity, and is very
easy to code (just 4 lines!)

If there are negative cycles, dist[i][i] will be


negative. Note the order!!!

By Hackin7 Published 21st August, 2019. Sponsored by Readable.com


cheatography.com/hackin7/ Last updated 27th December, 2019. Measure your website readability!
Page 1 of 4. https://readable.com
C++ Graph Theory Sample Cheat Sheet
by Hackin7 via cheatography.com/71996/cs/20334/

Lowest Common Ancestor of Tree Breadth First Search (cont) Union Find Data Structure

ll lca(ll N,ll a,ll b){ ​ ​ ​ ​dist[v] = d; int root (int x ) {


​ ​ ​ ​if(​dep​th[​a]<​dep​th[b]) ​ ​ ​ for (int i = 0; i < g[v].s​‐ ​ ​ ​ if (x == parent [x]) return
swap(a,b); ize(); i++) { x ;
​ ​ ​ ​//E​qualise depth ​ ​ ​ ​ ​ ​ ​ ​q.p​ush​(ma​ke_​pai​r(g​[v] ​ ​ ​ ​return root (paren​t[x]) ;
​ ​ ​ ​for(ll k=log2​(N)​;k>​=0;​k--){ [i], d+1)); }
​ ​ ​ ​ ​ ​ ​ ll parent = find_p​are​‐ ​ ​ ​ } bool is_con​nected (int x,int y)
nt(​a,k​);/​/p[​a][k] } {
​ ​ ​ ​ ​ ​ ​ ​if(​par​ent!=-1 && depth[​‐ ​ ​ ​ ​return root (x) == root(y) ;
Time Comple​xity: O(|V| + |E|)
par​ent​]>=​dep​th[b]){ Space Comple​xity: O(b^d) }
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​a=p​arent; where d is the depth of the graph and b is void connect ( int x , int y ) {
​ ​ ​ ​ ​ ​ ​ } the branching factor. ​ ​ ​ int root_x = root (x);
​ ​ ​ } ​ ​ ​ int root_y = root (y);
​ ​ ​ if (a==b)​return a; BFS is more suitable when the goal is close ​ ​ ​ if (root_x != root_y)
​ ​ ​ ​//Jump parent by parent to the source, BFS is still faster in such ​ ​ ​ ​ ​ ​ ​ ​parent [root_x] = root_y
​ ​ ​ ​for(ll k=log2​(N)​;k>​=0;​k--){ cases. ;
​ ​ ​ ​ ​ ​ ​ ll parent = find_p​are​‐ }
nt(​a,k​);/​/p[​a][k] We can use this algorithm to find the ////For Rankin​‐
​ ​ ​ ​ ​ ​ ​ ll parentb = find_p​are​‐ shortest path in a grid/u​nwe​ighted g//​///​///​///​///​///​/////
nt(​b,k​);/​/p[​b][k] graph int rank[N];
​ ​ ​ ​ ​ ​ ​ ​if(​par​ent​!=p​are​ntb​)a=​‐ void connect (int x , int y) {
Bellma​n-Ford
par​ent​,b=​par​entb; ​ ​ ​ int root_x = root (x) ,
​ ​ ​ } dist[s]=0; //dist all others = root_y = root (y) ;
​ ​ ​ ​return p[a][0]; INF ​ ​ ​ if (root_x == root_y) return
} for (int i=0; i<N-1; i++){ ; // same root
​ ​ ​ for (int j=0; j<E; j++){ ​ ​ ​ if (rank[​root_x] > rank[r​‐
Requires 2k Decomp​osition of Parents
​ ​ ​ ​ ​ ​ ​ // if path is shorter oot_y]) {
through node u, take it! ​ ​ ​ ​ ​ ​ ​ ​par​ent​[ro​ot_y] = root_x
Breadth First Search
​ ​ ​ ​ ​ ​ ​ ​dist[v] = min(di​st[v], ;
vector<int> g[100005];
dist[u​]+c​ost); ​ ​ ​ } else if (rank[​root_x] <
queue<​pai​r<int, int> > q;
​ ​ ​ } rank[r​oot_y]) {
int dist[1​000​005];
} ​ ​ ​ ​ ​ ​ ​ ​par​ent​[ro​ot_x] = root_y
fill(dist, dist+1​000005, -1);
Solves the Single Source Shortest Path ;
while (!q.em​pty()) {
(SSSP) problem. (shortest path from one ​ ​ ​ } else {
​ ​ ​ int v = q.fron​t().first;
node (source) to all other nodes) ​ ​ ​ ​ ​ ​ ​ ​par​ent​[ro​ot_y] = root_x
​ ​ ​ int d = q.fron​t().se​cond;
Can be used with negative edges, Run the ;
​ ​ ​ ​q.p​op();
algorithm twice to detect for negative cycles ​ ​ ​ ​ ​ ​ ​ ​ran​k[r​oot​_x]++;
​ ​ ​ if (dist[v] != -1) continue;
​ ​ ​ }
//Visited
Time Comple​xity: O(VE) }
Space Comple​xity: O(V)

By Hackin7 Published 21st August, 2019. Sponsored by Readable.com


cheatography.com/hackin7/ Last updated 27th December, 2019. Measure your website readability!
Page 2 of 4. https://readable.com
C++ Graph Theory Sample Cheat Sheet
by Hackin7 via cheatography.com/71996/cs/20334/

Kruskal's Algorithm for MST Depth First Search (cont) Dijkstra's Algorithm (cont)

vector <tuple<int,int,int> > ///Ite​rat​‐ ​ ​ ​ ​pai​r<i​nt,​int> c = pq.top();


edges ; // weight,node A,node B ive​///​///​///​///​///​///​///​///​///​// ​ ​ ​ ​pq.p​op();
sort (edges.be​gin(), edges.end /// ​ ​ ​ ​if(​c.first != dist[c.se​‐
()) ; bool vis[N]; cond]) continue;
int total_​weight = 0; vector​<in​t> adjLis​t[N]; ​ ​ ​ ​for​(auto i : adjLis​t[c.se​‐
for (auto e : edges) { stack<​int> S; cond]){
​ ​ ​ int weight, a, b; while (!S.em​pty()) { ​ ​ ​ ​ ​ ​ ​ ​if(​dis​t[i.first] == -1
​ ​ ​ tie (weigh​t,a,b) = e ; ​ ​ ​ int node = S.top(); || dist[i.first] > c.first +
​ ​ ​ if (root(a) == root(b)) // ​ ​ ​ ​S.p​op(); i.second){
taking this edge will cause a ​ ​ ​ if (vis[n​ode]) continue; ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​dis​t[i.first] =
cycle ​ ​ ​ ​vis​[node] = true; c.first + i.second;
​ ​ ​ ​ ​ ​ ​ ​con​tinue; ​ ​ ​ for (int a = 0; a < (int)a​‐ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​pq.p​us​h(m​ake​_pa​ir(​‐
​ ​ ​ ​tot​al_​weight += weight ; // djL​ist​[no​de].si​ze(); ++a) dis​t[i.fi​rst], i.first));
take this edge ​ ​ ​ ​ ​ ​ ​ ​S.p​ush​(ad​jLi​st[​nod​e] ​ ​ ​ ​ ​ ​ ​ }
​ ​ ​ ​connect (a, b) ; // connect [a]); ​ ​ ​ }
them in the UFDS } }
}
DFS uses O(d) space, where d is the depth Time Complexity of our implem​ent​ation:
Sort the list of edges by weight of the graph O(E log E)
For each edge in ascending order: If both Space Comple​xity: O(V+E)
nodes aren’t already DFS is not suited for infinite graphs.
connected, take it. Else, skip this edge. Solves the Single Source Shortest Path
Time comple​xity: O(E log V) (but faster than Some applic​ations of DFS include: (SSSP) problem. Means shortest path from
Prim’s algorithm in 1. Topolo​gical Ordering (covered later) one node to all other nodes. Cannot be
practice) 2. Pre-/I​n-/​Pos​t-order numbering of a tree used with negative edges as it runs too
UFDS is needed to check if the nodes are 3. Graph connec​tivity slow
connected in (2). 4. Finding articu​lation points Especially cannot be used with negative
5. Finding bridges cycles
Depth First Search
Dijkstra's Algorithm 2k Parent Decomp​osition
bool vis[N];
vector​<in​t> adjLis​t[N]; vector<pair<int,int> > typedef long long ll;
void dfs(int node) { adjList[10000]; // node, weight ll p[V][K]; //node,kth ancestor
​ ​ ​ if (vis[n​ode]) return; priori​ty_​que​ue<​pai​r<i​nt,​int​>, //DFS to compute node parents
​ ​ ​ ​vis​[node] = true; vector​<pa​ir<​int​,in​t> >, greate​‐ for p[i][0], first parent
​ ​ ​ for (int a = 0; a < (int)a​‐ r<p​air​<in​t,i​nt> > > pq; // bool visite​d[V];
djL​ist​[no​de].si​ze(); ++a) distance, node ll depth[V];
​ ​ ​ ​ ​ ​ ​ ​dfs​(ad​jLi​st[​nod​e][a]); int dist[1​0000]; void dfs(ll x){
} memset​(dist, -1, sizeof​(di​st)); ​ ​ ​ if (visit​ed[​x])​return;
pq.pus​h(m​ake​_pa​ir(0, source)); ​ ​ ​ ​vis​ite​d[x​]=true;
dist[0] = 0; ​ ​ ​ for (auto i:adjl​ist​[x]){
while(​!pq.em​pty()){ ​ ​ ​ ​ ​ ​ ​ if (!visi​ted​[i.f​ir​st]){

By Hackin7 Published 21st August, 2019. Sponsored by Readable.com


cheatography.com/hackin7/ Last updated 27th December, 2019. Measure your website readability!
Page 3 of 4. https://readable.com
C++ Graph Theory Sample Cheat Sheet
by Hackin7 via cheatography.com/71996/cs/20334/

2k Parent Decomp​osition (cont) 2k Parent Decomp​osition (cont)

​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ if (p[i.f​irs​t][0] == -1){ }
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​//c​out​<<i.fi​rst​<<"<​-"
<<​x<<​endl;
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​p[i.fi​rst][0] = x;
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​dep​th[​i.f​irst] =
depth[​x]+1;
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ }
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​dfs​(i.f​irst);
​ ​ ​ ​ ​ ​ ​ }
​ ​ ​ }
}
void calc_k​_pa​ren​ts(ll N){
​ ​ ​ for (ll k=1;k<​K;k++){
​ ​ ​ ​ ​ ​ ​ for (ll i=0;i<​N;i++){
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ if (p[i][k-1] != -1){
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​p[i​][k]= p[p[i]​[k-​‐
1]]​[k-1];
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​}el​se{​p[i​][k​]=-1;}
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ // if (k==2)​cou​t<<​i<<​"​,"
<<​k<<​"​:"<<​p[i​][k​-1]​<<",​"​<<p​[p[​i][​k-
1​]][​k-1​]<<​"​,"<<​p[i​][k​]<<​endl;
​ ​ ​ ​ ​ ​ ​ }
​ ​ ​ }
}
ll find_p​are​nt(ll x,ll k){
​ ​ ​ for (ll i=K;i>​=0;​i--){
​ ​ ​ ​ ​ ​ ​ if (k>= (1<​<i)){
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ if (x==-1​)return -1;
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​x=p​[x][i];
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​k-=​1<<i;
​ ​ ​ ​ ​ ​ ​ }
​ ​ ​ }
​ ​ ​ ​return x;

By Hackin7 Published 21st August, 2019. Sponsored by Readable.com


cheatography.com/hackin7/ Last updated 27th December, 2019. Measure your website readability!
Page 4 of 4. https://readable.com

You might also like