{"id":26017,"date":"2017-10-26T09:32:15","date_gmt":"2017-10-26T04:02:15","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26017"},"modified":"2017-10-26T09:32:15","modified_gmt":"2017-10-26T04:02:15","slug":"longest-path-directed-acyclic-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/longest-path-directed-acyclic-graph\/","title":{"rendered":"Longest Path in a Directed Acyclic Graph"},"content":{"rendered":"<p>Given a Weighted <strong>D<\/strong>irected <strong>A<\/strong>cyclic <strong>G<\/strong>raph (DAG) and a source vertex s in it, find the longest distances from s to all other vertices in the given graph.<span id=\"more-123086\"><\/span><\/p>\n<p>The longest path problem for a general graph is not as easy as the shortest path problem because the longest path problem doesn\u2019t have optimal substructure property. In fact, the Longest Path problem is NP-Hard for a general graph. However, the longest path problem has a linear time solution for directed acyclic graphs. The idea is similar to linear time solution for shortest path in a directed acyclic graph., we use Tological Sorting.<\/p>\n<p>We initialize distances to all vertices as minus infinite and distance to source as 0, then we find a topological sorting of the graph. Topological Sorting of a graph represents a linear ordering of the graph (See below, figure (b) is a linear representation of figure (a) ). Once we have topological order (or linear representation), we one by one process all vertices in topological order. For every vertex being processed, we update distances of its adjacent using distance of current vertex.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Following figure shows step by step process of finding longest paths.<\/p>\n<p>Following is complete algorithm for finding longest distances.<br \/>\n<strong>1)<\/strong> Initialize dist[] = {NINF, NINF, \u2026.} and dist[s] = 0 where s is the source vertex. Here NINF means negative infinite.<br \/>\n<strong>2)<\/strong> Create a toplogical order of all vertices.<br \/>\n<strong>3)<\/strong> Do following for every vertex u in topological order.<br \/>\n\u2026\u2026\u2026..Do following for every adjacent vertex v of u<br \/>\n\u2026\u2026\u2026\u2026\u2026\u2026if (dist[v] &lt; dist[u] + weight(u, v))<br \/>\n\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026\u2026dist[v] = dist[u] + weight(u, v)<\/p>\n<p>Following is C++ implementation of the above algorithm.<\/p>\n<div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ A C++ program to find single source longest distances in a DAG<br\/>#include &lt;iostream&gt;<br\/>#include &lt;list&gt;<br\/>#include &lt;stack&gt;<br\/>#include &lt;limits.h&gt;<br\/>#define NINF INT_MIN<br\/>using namespace std;<br\/>#inc<br\/>\/\/ Graph is represented using adjacency list. Every node of adjacency list<br\/>\/\/ contains vertex number of the vertex to which edge connects. It also<br\/>\/\/ contains weight of the edge<br\/>class AdjListNode<br\/>{<br\/>    int v;<br\/>    int weight;<br\/>public:<br\/>    AdjListNode(int _v, int _w)  { v = _v;  weight = _w;}<br\/>    int getV()       {  return v;  }<br\/>    int getWeight()  {  return weight; }<br\/>};<br\/> <br\/>\/\/ Class to represent a graph using adjacency list representation<br\/>class Graph<br\/>{<br\/>    int V;    \/\/ No. of vertices&#039;<br\/> <br\/>    \/\/ Pointer to an array containing adjacency lists<br\/>    list&lt;AdjListNode&gt; *adj;<br\/> <br\/>    \/\/ A function used by longestPath<br\/>    void topologicalSortUtil(int v, bool visited[], stack&lt;int&gt; &amp;Stack);<br\/>public:<br\/>    Graph(int V);   \/\/ Constructor<br\/> <br\/>    \/\/ function to add an edge to graph<br\/>    void addEdge(int u, int v, int weight);<br\/> <br\/>    \/\/ Finds longest distances from given source vertex<br\/>    void longestPath(int s);<br\/>};<br\/> <br\/>Graph::Graph(int V) \/\/ Constructor<br\/>{<br\/>    this-&gt;V = V;<br\/>    adj = new list&lt;AdjListNode&gt;[V];<br\/>}<br\/> <br\/>void Graph::addEdge(int u, int v, int weight)<br\/>{<br\/>    AdjListNode node(v, weight);<br\/>    adj[u].push_back(node); \/\/ Add v to u&#039;s list<br\/>}<br\/> <br\/>\/\/ A recursive function used by longestPath. See below link for details<br\/>\/\/ http:\/\/www.geeksforgeeks.org\/topological-sorting\/<br\/>void Graph::topologicalSortUtil(int v, bool visited[], stack&lt;int&gt; &amp;Stack)<br\/>{<br\/>    \/\/ Mark the current node as visited<br\/>    visited[v] = true;<br\/> <br\/>    \/\/ Recur for all the vertices adjacent to this vertex<br\/>    list&lt;AdjListNode&gt;::iterator i;<br\/>    for (i = adj[v].begin(); i != adj[v].end(); ++i)<br\/>    {<br\/>        AdjListNode node = *i;<br\/>        if (!visited[node.getV()])<br\/>            topologicalSortUtil(node.getV(), visited, Stack);<br\/>    }<br\/> <br\/>    \/\/ Push current vertex to stack which stores topological sort<br\/>    Stack.push(v);<br\/>}<br\/> <br\/>\/\/ The function to find longest distances from a given vertex. It uses<br\/>\/\/ recursive topologicalSortUtil() to get topological sorting.<br\/>void Graph::longestPath(int s)<br\/>{<br\/>    stack&lt;int&gt; Stack;<br\/>    int dist[V];<br\/> <br\/>    \/\/ Mark all the vertices as not visited<br\/>    bool *visited = new bool[V];<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        visited[i] = false;<br\/> <br\/>    \/\/ Call the recursive helper function to store Topological Sort<br\/>    \/\/ starting from all vertices one by one<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        if (visited[i] == false)<br\/>            topologicalSortUtil(i, visited, Stack);<br\/> <br\/>    \/\/ Initialize distances to all vertices as infinite and distance<br\/>    \/\/ to source as 0<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        dist[i] = NINF;<br\/>    dist[s] = 0;<br\/> <br\/>    \/\/ Process vertices in topological order<br\/>    while (Stack.empty() == false)<br\/>    {<br\/>        \/\/ Get the next vertex from topological order<br\/>        int u = Stack.top();<br\/>        Stack.pop();<br\/> <br\/>        \/\/ Update distances of all adjacent vertices<br\/>        list&lt;AdjListNode&gt;::iterator i;<br\/>        if (dist[u] != NINF)<br\/>        {<br\/>          for (i = adj[u].begin(); i != adj[u].end(); ++i)<br\/>             if (dist[i-&gt;getV()] &lt; dist[u] + i-&gt;getWeight())<br\/>                dist[i-&gt;getV()] = dist[u] + i-&gt;getWeight();<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ Print the calculated longest distances<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        (dist[i] == NINF)? cout &lt;&lt; &quot;INF &quot;: cout &lt;&lt; dist[i] &lt;&lt; &quot; &quot;;<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    \/\/ Create a graph given in the above diagram.  Here vertex numbers are<br\/>    \/\/ 0, 1, 2, 3, 4, 5 with following mappings:<br\/>    \/\/ 0=r, 1=s, 2=t, 3=x, 4=y, 5=z<br\/>    Graph g(6);<br\/>    g.addEdge(0, 1, 5);<br\/>    g.addEdge(0, 2, 3);<br\/>    g.addEdge(1, 3, 6);<br\/>    g.addEdge(1, 2, 2);<br\/>    g.addEdge(2, 4, 4);<br\/>    g.addEdge(2, 5, 2);<br\/>    g.addEdge(2, 3, 7);<br\/>    g.addEdge(3, 5, 1);<br\/>    g.addEdge(3, 4, -1);<br\/>    g.addEdge(4, 5, -2);<br\/> <br\/>    int s = 1;<br\/>    cout &lt;&lt; &quot;Following are longest distances from source vertex &quot; &lt;&lt; s &lt;&lt;&quot; \\n&quot;;<br\/>    g.longestPath(s);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Following are longest distances from source vertex 1\r\nINF 0 2 9 8 10<\/pre>\n<p><strong>Time Complexity:<\/strong> Time complexity of topological sorting is O(V+E). After finding topological order, the algorithm process all vertices and for every vertex, it runs a loop for all adjacent vertices. Total adjacent vertices in a graph is O(E). So the inner loop runs O(V+E) times. Therefore, overall time complexity of this algorithm is O(V+E).<\/p>\n[ad type=&#8221;banner&#8221;]\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Longest Path in a Directed Acyclic Graph &#8211; Graph Algorithms &#8211; Given a Weighted Directed Acyclic Graph (DAG) and a source vertex s in it.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[74168,83583,73906],"tags":[76584,76585,76586,76580,76587,76582,76581,76583],"class_list":["post-26017","post","type-post","status-publish","format-standard","hentry","category-dfs-and-bfs","category-directed-acyclic-graph","category-graph-algorithms","tag-longest-path-algorithm-dijkstra","tag-longest-path-between-two-nodes-in-a-graph","tag-longest-path-in-a-tree","tag-longest-path-in-a-undirected-graph","tag-longest-path-in-directed-cyclic-graph","tag-longest-path-in-undirected-acyclic-graph","tag-longest-path-in-unweighted-graph","tag-longest-path-in-weighted-undirected-graph"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26017","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26017"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26017\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26017"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26017"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26017"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}