Question: Task 0 : #include #include #include #include using namespace std; typedef pair iPair; void addEdge ( vector > adj [ ] , int u ,

Task 0: #include
#include
#include
#include
using namespace std;
typedef pair iPair;
void addEdge(vector> adj[], int u, int v, int wt){
adj[u].push_back({v, wt});
adj[v].push_back({u, wt}); // for undirected graph
}
void shortestPath(vector> adj[], int V, int src){
// Initialize priority queue to store vertices with their distances
priority_queue, greater> pq;
// Initialize distances array to store shortest distances from source
vector dist(V, numeric_limits::max());
// Insert source vertex into priority queue with distance 0
pq.push({0, src});
dist[src]=0;
// Dijkstra's algorithm
while (!pq.empty()){
// Extract the vertex with the minimum distance from the priority queue
int u = pq.top().second;
pq.pop();
// Update distances of adjacent vertices
for (auto& edge : adj[u]){
int v = edge.first;
int weight = edge.second;
// If a shorter path is found, update the distance and insert vertex into priority queue
if (dist[u]+ weight dist[v]){
dist[v]= dist[u]+ weight;
pq.push({dist[v], v});
}
}
}
// Output shortest paths from source vertex to all other vertices
cout "Shortest paths from source vertex " src " to all other vertices:
";
for (int i =0; i V; ++i){
cout "Vertex " i ": Distance =" dist[i]"
";
}
}
int main(){
// Graph representation
vector> adj[6];
addEdge(adj,0,1,2);
addEdge(adj,0,2,4);
addEdge(adj,1,2,1);
addEdge(adj,1,3,7);
addEdge(adj,2,4,3);
addEdge(adj,3,4,2);
addEdge(adj,3,5,1);
addEdge(adj,4,5,5);
// Source vertex
int src =0;
// Number of vertices
int V =6;
// Find shortest paths from source vertex
shortestPath(adj, V, src);
return 0;
}
Task 0 : #include #include #include #include

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!