Question

# Problem Description Given a directed graph G = (V,E) with edge length l(e) > 0...

# Problem Description

Given a directed graph G = (V,E) with edge length l(e) > 0 for any e in E, and a source vertex s. Use Dijkstra’s algorithm to calculate distance(s,v) for all of the vertices v in V.
(You can implement your own priority queue or use the build-in function for C++/Python)

# Input

The graph has `n` vertices and `m` edges.
There are m + 1 lines, the first line gives three numbers `n`,`m` and `s`(1 <= s <=n), describing the number of vertices, the number of edges and the source vertex. Each of the following lines contains three integers `a`, `b` and `c`, meaning there is an edge (a,b) belong to E and the length of the edge is c. All the numbers in a line are separated by space. (`1 <= a,b <= n`)


You can assume that 1 <= n <= 1000, 1 <= m <= 5000, and the length of edge is in the range of [1, 1000].

Your code should read the input from standard input (e.g.
using functions `input()/raw_input()` in Python and `cin/scanf` in C++).

# Output

N lines, the i-th line contain a number representing the distance(s,i). If s can not reach the i-th vertex, output `-1` at the i-th line.


Your code should write the output to standard output (e.g. using functions `print` in Python and `cout/printf` in C++).

Homework Answers

Answer #1
// C++ implementation for the above approach 
#include <bits/stdc++.h> 
using namespace std; 
#define INF 0x3f3f3f3f 

// iPair ==> Integer Pair 
typedef pair<int, int> iPair; 

// This class represents a directed graph using 
// adjacency list representation 
class Graph { 
        int V; // No. of vertices 

        // In a weighted graph, we need to store vertex 
        // and weight pair for every edge 
        list<pair<int, int> >* adj; 

public: 
        Graph(int V); // Constructor 

        // function to add an reverse edge to graph 
        void addEdgeRev(int u, int v, int w); 

        // prints shortest distance from all 
        // vertex to the given destination vertex 
        void shortestPath(int s); 
}; 

// Allocates memory for adjacency list 
Graph::Graph(int V) 
{ 
        this->V = V; 
        adj = new list<iPair>[V]; 
} 

void Graph::addEdgeRev(int u, int v, int w) 
{ 

        adj[v].push_back(make_pair(u, w)); 
} 

// Prints shortest distance from all vertex to 
// the given destination vertex 
void Graph::shortestPath(int dest) 
{ 
        // Create a priority queue to store vertices that 
        // are being preprocessed. This is weird syntax in C++. 
        // Refer below link for details of this syntax 
        // https:// www.geeksforgeeks.org/implement-min-heap-using-stl/ 
        priority_queue<iPair, vector<iPair>, greater<iPair> > pq; 

        // Create a vector for distances and initialize all 
        // distances as infinite (INF) 
        vector<int> dist(V, INF); 

        // Insert destination itself in priority queue and initialize 
        // its distance as 0. 
        pq.push(make_pair(0, dest)); 
        dist[dest] = 0; 

        /* Looping till priority queue becomes empty (or all 
        distances are not finalized) */
        while (!pq.empty()) { 

                // The first vertex in pair is the minimum distance 
                // vertex, extract it from priority queue. 
                // vertex label is stored in second of pair (it 
                // has to be done this way to keep the vertices 
                // sorted distance (distance must be first item 
                // in pair) 
                int u = pq.top().second; 
                pq.pop(); 

                // 'i' is used to get all adjacent vertices of a vertex 
                list<pair<int, int> >::iterator i; 
                for (i = adj[u].begin(); i != adj[u].end(); ++i) { 

                        // Get vertex label and weight of current adjacent 
                        // of u. 
                        int v = (*i).first; 
                        int weight = (*i).second; 

                        // If there is shorted path to v through u. 
                        if (dist[v] > dist[u] + weight) { 
                                // Updating distance of v 
                                dist[v] = dist[u] + weight; 
                                pq.push(make_pair(dist[v], v)); 
                        } 
                } 
        } 

        // Print shortest distances stored in dist[] 
        printf("Destination Vertex Distance "
                "from all vertex\n"); 
        for (int i = 0; i < V; ++i) 
                printf("%d \t\t %d\n", i, dist[i]); 
} 

// Driver program to test methods of graph class 
int main() 
{ 
        // create the graph given in above figure 
        int V = 5; 
        Graph g(V); 

        // adding edges in reverse direction 
        g.addEdgeRev(0, 2, 1); 
        g.addEdgeRev(0, 4, 5); 
        g.addEdgeRev(1, 4, 1); 
        g.addEdgeRev(2, 0, 10); 
        g.addEdgeRev(2, 3, 5); 
        g.addEdgeRev(3, 1, 1); 
        g.addEdgeRev(4, 0, 5); 
        g.addEdgeRev(4, 2, 100); 
        g.addEdgeRev(4, 3, 5); 

        g.shortestPath(0); 

        return 0; 
} 
Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
You are given a directed acyclic graph G(V,E), where each vertex v that has in-degree 0...
You are given a directed acyclic graph G(V,E), where each vertex v that has in-degree 0 has a value value(v) associated with it. For every other vertex u in V, define Pred(u) to be the set of vertices that have incoming edges to u. We now define value(u) = ?v∈P red(u) value(v). Design an O(n + m) time algorithm to compute value(u) for all vertices u where n denotes the number of vertices and m denotes the number of edges...
Suppose that we generate a random graph G = (V, E) on the vertex set V...
Suppose that we generate a random graph G = (V, E) on the vertex set V = {1, 2, . . . , n} in the following way. For each pair of vertices i, j ∈ V with i < j, we flip a fair coin, and we include the edge i−j in E if and only if the coin comes up heads. How many edges should we expect G to contain? How many cycles of length 3 should we...
Problem 2. Consider a graph G = (V,E) where |V|=n. 2(a) What is the total number...
Problem 2. Consider a graph G = (V,E) where |V|=n. 2(a) What is the total number of possible paths of length k ≥ 0 in G from a given starting vertex s and ending vertex t? Hint: a path of length k is a sequence of k + 1 vertices without duplicates. 2(b) What is the total number of possible paths of any length in G from a given starting vertex s and ending vertex t? 2(c) What is the...
Given a directed acyclic graph G= (V,E), vertex s∈V, design a dynamic programming algorithm to compute...
Given a directed acyclic graph G= (V,E), vertex s∈V, design a dynamic programming algorithm to compute the number of distinct paths from s to v for any v∈V. 1. Define subproblems 2. Write recursion 3. Give the pseudo-code 4. Analyze the running time.
Let G = (V,E) be a graph with n vertices and e edges. Show that the...
Let G = (V,E) be a graph with n vertices and e edges. Show that the following statements are equivalent: 1. G is a tree 2. G is connected and n = e + 1 3. G has no cycles and n = e + 1 4. If u and v are vertices in G, then there exists a unique path connecting u and v.
Consider a minimum spanning tree for a weighted graph G= (V, E)and a new edge e,...
Consider a minimum spanning tree for a weighted graph G= (V, E)and a new edge e, connecting two existing nodes in V. Explain how to find a minimum spanning tree of the new graph in O(n)time, where n is the number of nodes in the graph. Prove correctness of the algorithm and justify the running time
10.-Construct a connected bipartite graph that is not a tree with vertices Q,R,S,T,U,V,W. What is the...
10.-Construct a connected bipartite graph that is not a tree with vertices Q,R,S,T,U,V,W. What is the edge set? Construct a bipartite graph with vertices Q,R,S,T,U,V,W such that the degree of S is 4. What is the edge set? 12.-Construct a simple graph with vertices F,G,H,I,J that has an Euler trail, the degree of F is 1 and the degree of G is 3. What is the edge set? 13.-Construct a simple graph with vertices L,M,N,O,P,Q that has an Euler circuit...
Analyze the worst-case complexity of the algorithm below when using an optimized adjacency list to store...
Analyze the worst-case complexity of the algorithm below when using an optimized adjacency list to store G. ComponentCount: Input: G = (V, E): an undirected graph with n vertices and m edges Input: n, m: the order and size of G, respectively Output: the number of connected components in G Pseudocode: comp = n uf = UnionFind(n) For v in V:     For u in N(v):         If (uf.Find(v) != uf.Find(u))             uf.Union(u, v)             comp = comp - 1...
Analyze the worst-case complexity of the algorithm below when using an optimized adjacency list to store...
Analyze the worst-case complexity of the algorithm below when using an optimized adjacency list to store G. ComponentCount: Input: G = (V, E): an undirected graph with n vertices and m edges Input: n, m: the order and size of G, respectively Output: the number of connected components in G Pseudocode: comp = n uf = UnionFind(n) For v in V:     For u in N(v):         If (uf.Find(v) != uf.Find(u))             uf.Union(u, v)             comp = comp - 1...
function [ c ] = countA( v ) c = 0; for i = 1:length(v) if...
function [ c ] = countA( v ) c = 0; for i = 1:length(v) if v(i) < 4 c = c+1; end end end Write a function countB which has the same behavior using a single line of code (3 total lines if you count the “function” line and the “end” line). Your function should not have any loops or if statements in it. You should assume v is a row vector. (Hint. Use a logical vector.) function [...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT