0% found this document useful (0 votes)
2 views

cpp

The document contains code snippets related to graph algorithms, specifically focusing on articulation points, strongly connected components (SCCs), and minimum spanning trees (MST). It includes implementations of depth-first search (DFS), breadth-first search (BFS), and Kruskal's algorithm, along with user input prompts for nodes and edges. The code is structured using C++ and utilizes various data structures such as vectors and queues.

Uploaded by

allroundsports00
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

cpp

The document contains code snippets related to graph algorithms, specifically focusing on articulation points, strongly connected components (SCCs), and minimum spanning trees (MST). It includes implementations of depth-first search (DFS), breadth-first search (BFS), and Kruskal's algorithm, along with user input prompts for nodes and edges. The code is structured using C++ and utilizes various data structures such as vectors and queues.

Uploaded by

allroundsports00
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Articulation disc[u]) // Bridge cout << "Enter if (!vis[item_adj]) while (!q.

empty()) vis[item_adj] =
case number of nodes 1;
Point and edges: "; { {
isArticulation[u]
#include = true; cin >> n >> e; vis[item_adj] = int curr = s.push(item_adj);
<iostream> 1; q.front();
} DFS(item_adj,
#include <vector> q.pop(); n, adj, vis, s,
else if (v != cout << "Enter q.push(item_adj); result);
#include parent[u]) edges (u v):" << BFS(curr, n, adj,
<algorithm> endl; vis, q, result); }
{ result.push_back(it
using namespace for (int i = 0; i < e; em_adj); } }
std; low[u] = i++)
min(low[u], } cout << "BFS }
const int N = 100; disc[v]); // Update { traversal order:" <<
// Max number of low value } endl;
nodes int u, v;
} } for (auto item : int main()
vector<int> adj[N]; cin >> u >> v; result)
// Adjacency list } int main() {
{
bool visited[N]; } adj[u].push_back(v { cout << "Enter the
); cout << item << number of nodes
int disc[N], low[N], void cout << "Enter the endl; and edges: ";
parent[N]; findArticulationPoi number of nodes
nts(int n) adj[v].push_back(u and edges: "; } int n, e;
bool );
isArticulation[N]; { int n, e; } cin >> n >> e;
}
int timer = 0; fill(visited, visited cin >> n >> e;
+ n, false); findArticulationPoi
void dfs(int u) nts(n); vector<int> adj[n]; vector<int> adj[n];
fill(parent, parent
DFS
{ + n, -1); return 0; queue<int> q; cout << "Enter the
#include node connections
visited[u] = true; fill(isArticulation, } vector<int> vis(n, <iostream> (node1 node2): "
isArticulation + n, 0); << endl;
disc[u] = low[u] = false); #include <stack>
++timer; vector<int> result; for (int i = 0; i < e;
timer = 0; #include <vector> i++)
int children = 0; BFS cout << "Enter
node connections {
(node1 node2): "
for (int i = 0; i < n; << endl; using namespace int u, v;
for (int v : adj[u]) i++) #include std; // Add this
<iostream> for (int i = 0; i < e; line to avoid cin >> u >> v;
{ { i++) prefixing std::
#include <vector>
if (!visited[v]) if (!visited[i]) { adj[u].push_back(v
#include );
{ dfs(i); <algorithm> int u, v; void DFS(int node,
int n,
children++; } #include <queue> cin >> u >> v; adj[v].push_back(u
vector<int> ); // Assuming
parent[v] = u; cout << using namespace adj[], undirected graph
"Articulation std; // Add this adj[u].push_back(v
dfs(v); Points: "; line to avoid ); vector<int> }
prefixing std:: &vis,
for (int i = 0; i < n;
i++) adj[v].push_back(u stack<int> &s,
// Update low ); // Assuming int source;
value of u { void BFS(int undirected graph vector<int>
source, int n, &result) cout << "Enter the
low[u] = if vector<int> adj[], } source node: ";
min(low[u], (isArticulation[i]) {
low[v]); vector<int> int source; cin >> source;
cout << i << " "; &vis, vis[node] = 1;
// Check if u is cout << "Enter the
an articulation } queue<int> source node: ";
point &q, result.push_back(n vector<int> vis(n,
cout << endl; cin >> source; ode); 0);
if (parent[u] == vector<int>
-1 && children > 1) } &result) q.push(source); for (auto stack<int> s;
// Root case &item_adj :
int main() { vis[source] = 1; adj[node]) vector<int> result;

isArticulation[u] = for (auto {


{ s.push(source);
true; &item_adj : result.push_back(s
int n, e; adj[source]) ource); if (!vis[item_adj])
if (parent[u] != -
1 && low[v] >= { {
DFS(source, n, adj, finishing its if (!vis[i]) cout << "Enter cout << "The
vis, s, result); adjacencies the edges (node1 number of SCCs is: parent[rootY] =
{ node2): " << endl; " << count << endl; rootX;
}
DFS(i, adj, for (int i = 0; i < } else if
cout << "[ "; vis, finish_order); e; i++) (rank[rootX] <
return 0; rank[rootY]) {
for (int i = 0; i < // Second DFS to } {
result.size(); i++) explore SCCs on }
the reverse graph } int u, v; parent[rootX] =
{ rootY;
void DFS_SCC(int // Reset visited cin >> u >> v;
(i == result.size() node, vector<int> array for second krushkal } else {
- 1) ? cout << adj_rev[], DFS
result.at(i) : cout << vector<int> &vis, adj[u].push_back(v #include
result.at(i) << " , "; vector<int> vis.assign(n + 1, ); // Normal parent[rootY] =
<iostream>
&result) 0); graph rootX;
} #include <vector>
{
cout << " ]" << adj_rev[v].push_ba #include rank[rootX]++;
endl; vis[node] = 1; // Now process ck(u); // Reversed <algorithm>
the reverse graph graph }
} result.push_back(n in the order of the using namespace
ode); finish order } std; }

for (auto for (int i = }


struct Edge {
SCC item_adj : finish_order.size() -
adj_rev[node]) 1; i >= 0; i--) // Run the int src, dest, // Comparator to
#include Kosaraju's sort edges by
weight;
{ { algorithm to find weight
<iostream>
SCCs };
#include <vector> if int curr = bool
(!vis[item_adj]) finish_order[i]; SCC(n, adj, compareEdge(Edge
#include adj_rev, a, Edge b) {
{ if (!vis[curr]) scc_result);
<algorithm> // Function to find
the root of a node return a.weight <
{ with path b.weight;
DFS_SCC(item_adj, compression
using namespace adj_rev, vis, result); vector<int> // Print the SCCs }
std; result; int
} cout << "Strongly find(vector<int>&
Connected parent, int i) {
} DFS_SCC(curr, Components void
adj_rev, vis, result); (SCCs):" << endl; kruskal(vector<Edg
// First DFS that if (parent[i] != i) {
fills the nodes into } e>& edges, int V) {
the order of their int count = 0; parent[i] =
finishing times // Main function to scc_result.push_ba find(parent, vector<int>
identify SCCs using ck(result); // Store cout << "[ "; parent[i]); // Path parent(V);
void DFS(int node, Kosaraju’s the SCC compression
vector<int> adj[], algorithm for (auto &row : vector<int>
vector<int> &vis, } scc_result) } rank(V, 0);
vector<int> void SCC(int n,
&finish_order) vector<int> adj[], } { return parent[i];
vector<int>
adj_rev[], } count++; // Initialize
{ }
vector<vector<int> parent and rank
> &scc_result) int main() cout << "{ ";
vis[node] = 1;
for (int i = 0; i <
for (auto { { for (int i = 0; i < // Function to V; i++) {
item_adj : row.size(); i++) union two sets
vector<int> vis(n cout << "Enter parent[i] = i;
adj[node]) using rank
+ 1, 0); the number of {
{ nodes and edges: "; void }
vector<int> (i == unionSets(vector<i
finish_order; // int n, e; row.size() - 1) ?
if nt>& parent,
Vector to store the cout << row.at(i) :
(!vis[item_adj]) vector<int>& rank,
order of nodes cin >> n >> e; cout << row.at(i) << // Sort edges by
int x, int y) {
based on their " , "; weight
{
finishing times int rootX =
} find(parent, x);
DFS(item_adj, adj, vector<int> adj[n sort(edges.begin(),
vis, finish_order); + 1]; cout << " }" << int rootY = edges.end(),
// Perform DFS endl; compareEdge);
find(parent, y);
to populate the vector<int>
}
finish order adj_rev[n + 1]; }
}
for (int i = 1; i <= cout << "]" << cout << "Edges in
if (rootX !=
n; i++) vector<vector<int> endl; the Minimum
rootY) {
finish_order.push_ > scc_result; Spanning Tree:\n";
back(node); // { if (rank[rootX]
Push node after > rank[rootY]) {
int mstWeight = cout << "Enter for (int i = 0; i < Knapsack = " <<
0; number of vertices: n; i++) { max_value << endl; std::vector<std::pai
"; r<int, int>> &result, int main()
int edgeCount = for (int w = W; int
0; cin >> V; w >= weight[i]; w--) *total_path_cost) {
{ return 0;
cout << "Enter int n, e;
number of edges: dp[w] = }
for (const auto& "; max(dp[w], value[i] { std::cout <<
edge : edges) { + dp[w - Prims "enter the number
cin >> E; weight[i]]); while of node and edges:
if (edgeCount #include (!stored_set.empty ";
== V - 1) break; } <iostream> ())
std::cin >> n >> e;
vector<Edge> } #include <vector> {
edges(E);
int rootSrc = #include <set> tripair node = std::vector<std::pai
find(parent, *stored_set.begin() r<int, int>> adj[n];
edge.src); return dp[W]; #include ;
cout << "Enter <algorithm> std::cout <<
int rootDest = edges (source } "enter the node---
find(parent, destination stored_set.erase(st >node-->value: " <<
edge.dest); weight):\n"; ored_set.begin()); std::endl;
#define INIFINTY
for (int i = 0; i < int main() { int weight = for (int i = 0; i < e;
1e5
E; i++) { node.weight; i++)
// If including int W, n;
this edge doesn't cin >> int parent = {
form a cycle edges[i].src >> cout << "Enter node.parent_node;
struct tripair
edges[i].dest >> the knapsack int u, v, w;
if (rootSrc != edges[i].weight; size/capacity: "; int child_node =
{
rootDest) { node.child_node; std::cin >> u >> v
} cin >> W; int weight, >> w;
cout << if
child_node,
edge.src << " -- " << (!vis[child_node]) if (u == v)
parent_node;
edge.dest << " |
Weight: " << kruskal(edges, cout << "Enter { continue;
bool
edge.weight << V); the number of operator<(const
"\n"; items: "; tripair &other) vis[child_node]
return 0; = 1;
const
mstWeight cin >> n; bool is_parallel =
+= edge.weight; } if (parent != -1) false;
{

if (this->weight { for (auto &item :


unionSets(parent, vector<int> adj[u])
!= other.weight)
rank, rootSrc, weight(n), value(n);
rootDest); result.push_back({ {
return this-
0/1 knapsack >weight < parent,
child_node}); // if (item.first ==
other.weight;
edgeCount++; cout << "Enter minimum one was v)
the weights: "; inserted.
if (this-
} #include >child_node != {
<iostream> for (int i = 0; i < other.child_node)
} n; i++) { *total_path_cost is_parallel =
+= weight; // true;
#include <vector> return this-
cin >> the minimum one's
>child_node <
weight[i]; cost item.second =
#include other.child_node;
if (edgeCount == std::min(item.seco
<algorithm>
V - 1) { } return this- } nd, w);
>parent_node <
cout << "Total for (auto &itr : break;
other.parent_node
Weight of MST: " adj[child_node])
using namespace ;
<< mstWeight << cout << "Enter }
std;
"\n"; the values: "; } {
}
} else { for (int i = 0; i < if (!vis[itr.first])
};
int knapsack(int W, n; i++) { if (!is_parallel)
cout << "MST int n, const
cannot be formed. cin >> value[i]; stored_set.insert({i {
vector<int>&
Not enough tr.second, itr.first,
weight, const void
edges." << endl; } child_node}); //
vector<int>& PrimsAlgorithm(std
{weight , adj[u].push_back({
value) { ::vector<std::pair<i
} child_nodes , `0`} v, w});
nt, int>> adj[],
vector<int>
} int max_value = } }
dp(W + 1, 0);
knapsack(W, n, std::vector<int>
weight, value); &vis, }
std::set<tripair>
int main() { // Dynamic cout << &stored_set, } is_parallel =
programming to "Maximum value in false;
int V, E; }
solve the problem
for (auto &item : << item.second << // A utility function vector<bool> } if (u >= V || v
adj[v]) std::endl; to print the sptSet(V, false); // >= V || u < 0 || v <
constructed sptSet[i] will be 0) {
{ } distance true if vertex i is
included in // Print the cout <<
if (item.first == std::cout << "total // array and total shortest path tree constructed "Invalid edge input:
u) MST cost is: " << cost or shortest distance array and vertices must be
total_path_cost; distance from src the total cost between 1 and " <<
{ void to i is finalized V << ". Please try
} printSolution(const again.\n";
is_parallel = vector<int>& dist, printSolution(dist,
true; int V) { V); i--; //
// Distance of Decrement to re-
item.second = Dijkastra int totalCost = 0; source vertex from } enter the current
std::min(item.seco // Variable to itself is always 0 invalid edge
nd, w); calculate the total // Driver's code
cost dist[src] = 0; continue;
break; #include int main() {
<iostream> // Find shortest }
} path for all vertices int V, E;
#include <vector> cout << "Vertex graph[u][v] =
} \t\t Distance from for (int count = 0; cout << "Enter w; // Store weight
#include <limits.h> Source\n"; count < V - 1; the number of of edge u->v
if (!is_parallel) count++) { vertices: ";
for (int i = 0; i < graph[v][u] =
{ V; i++) { // Pick the cin >> V; w; // Since the
using namespace minimum distance graph is undirected
std; cout << i << vertex from the set cout << "Enter
adj[v].push_back({ "\t\t\t " << dist[i] of vertices not yet the number of }
u, w}); // A utility function << endl; processed edges: ";
to find the vertex
} with minimum if (dist[i] != int u = cin >> E;
INT_MAX) { // minDistance(dist, int src;
} // distance value, Ignore infinite sptSet, V);
from the set of distances cout << "Enter
std::vector<int> vertices not yet // Dynamically the source vertex
vis(n, 0); included totalCost += allocate memory (1-based indexing):
dist[i]; // Mark the for the adjacency ";
std::set<tripair> // in the shortest picked vertex as matrix
stored_set; path tree } processed cin >> src;

int } sptSet[u] = vector<vector<int> src--; // Convert


std::vector<std::pai minDistance(vector true; > graph(V, to 0-based indexing
r<int, int>> result; <int>& dist, vector<int>(V, 0));
vector<bool>& // 2D vector for
int sptSet, int V) { cout << "\nTotal adjacency matrix
total_path_cost = Cost of shortest // Update dist // Check if the
0; // Initialize min paths from source: value of the source is valid
value " << totalCost << adjacent vertices of
std::cout << endl; the picked vertex cout << "Enter if (src >= V || src
"enter the source: int min = the edges (u v w) < 0) {
"; INT_MAX, } for (int v = 0; v one by one (1-
min_index; < V; v++) { based cout <<
int source; indexing):\n"; "Invalid source
// Update vertex.
std::cin >> source; // Function that dist[v] only if is not for (int i = 0; i < Exiting...\n";
for (int v = 0; v < implements in sptSet, there is E; i++) {
V; v++) { Dijkstra's single an edge from u to return 1;
stored_set.insert({ source v, and total weight int u, v, w;
0, source, -1}); // if (!sptSet[v] of path from src to }
{weight , && dist[v] <= min) { // shortest path v through u is cin >> u >> v
source,parent=-1} algorithm for a smaller than >> w;
min = graph represented current value of
dist[v]; using dist[v] // Convert to dijkstra(graph,
PrimsAlgorithm(adj 0-based indexing src, V);
, vis, stored_set, min_index = // adjacency matrix if (!sptSet[v]
result, v; representation && graph[u][v] != 0 u--; //
&total_path_cost); && dist[u] != Decrement for 0-
} void dijkstra(const INT_MAX && based index return 0;
std::cout << "the vector<vector<int> dist[u] +
MST is: " << } >& graph, int src, graph[u][v] < v--; // }
std::endl; int V) { dist[v]) { Decrement for 0-
based index
for (auto &item : vector<int> dist[v] =
result) return dist(V, INT_MAX); dist[u] +
min_index; // The output graph[u][v];
{ array. dist[i] will // Check if the
} hold the shortest } entered vertices
std::cout << distance from src are valid
item.first << " --> " to i }

You might also like