<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Directed acyclic graph &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/directed-acyclic-graph/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Topological Sort Revisited</title>
		<link>/2012/12/10/computer-algorithms-topological-sort-revisited/</link>
		<comments>/2012/12/10/computer-algorithms-topological-sort-revisited/#comments</comments>
		<pubDate>Mon, 10 Dec 2012 15:45:16 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Adjacency list]]></category>
		<category><![CDATA[Adjacency matrix]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Dijkstra's algorithm]]></category>
		<category><![CDATA[Directed acyclic graph]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[graph algorithms]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[ineffective algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[time consuming algorithm]]></category>
		<category><![CDATA[Topological sorting]]></category>
		<category><![CDATA[Vertex]]></category>

		<guid isPermaLink="false">/?p=3494</guid>
		<description><![CDATA[Introduction We already know what’s topological sort of a directed acyclic graph. So why do we need a revision of this algorithm? First of all I never mentioned its complexity, thus to understand why we do need a revision let’s get again on the algorithm. We have a directed acyclic graph (DAG). There are no &#8230; <a href="/2012/12/10/computer-algorithms-topological-sort-revisited/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Topological Sort Revisited</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/10/01/computer-algorithms-topological-sort-of-a-graph/" rel="bookmark" title="Computer Algorithms: Topological Sort of a Graph">Computer Algorithms: Topological Sort of a Graph </a></li>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" rel="bookmark" title="Computer Algorithms: Graphs and their Representation">Computer Algorithms: Graphs and their Representation </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We already know what’s topological sort of a directed acyclic graph. So why do we need a revision of this algorithm? First of all I never mentioned its complexity, thus to understand why we do need a revision let’s get again on the algorithm.</p>
<p>We have a directed acyclic graph (DAG). There are no cycles so we must go for some kind of order putting all the vertices of the graph in such an order, that if there’s a directed edge (u, v), u must precede v in that order. </p>
<figure id="attachment_3506" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/1.-Topological-Sort.png"><img src="/wp-content/uploads/2012/12/1.-Topological-Sort.png" alt="Topological Sort" title="Topological Sort" width="620" height="399" class="size-full wp-image-3506" srcset="/wp-content/uploads/2012/12/1.-Topological-Sort.png 620w, /wp-content/uploads/2012/12/1.-Topological-Sort-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>The process of putting all the vertices of the DAG in such an order is called topological sorting. It’s commonly used in task scheduling or while finding the shortest paths in a DAG.</p>
<p>The algorithm itself is pretty simple to understand and code. We must start from the vertex (vertices) that don’t have predecessors. </p>
<p><figure id="attachment_3513" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/2.-Topological-Sort-step-1.png"><img src="/wp-content/uploads/2012/12/2.-Topological-Sort-step-1.png" alt="Topological Sort - step 1" title="Topological Sort - step 1" width="620" height="399" class="size-full wp-image-3513" srcset="/wp-content/uploads/2012/12/2.-Topological-Sort-step-1.png 620w, /wp-content/uploads/2012/12/2.-Topological-Sort-step-1-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure><span id="more-3494"></span></p>
<p>We put them in our sorted list in random order. Since they don’t depend on each other we can assume they are equally sorted already. Indeed thinking of a task schedule if there are tasks that don’t have predecessors (they don’t depend on other tasks before them) and that don’t depend on each other we can put them in random order (and execute them in random order).</p>
<figure id="attachment_3512" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/3.-Topological-Sort-Order.png"><img src="/wp-content/uploads/2012/12/3.-Topological-Sort-Order.png" alt="Topological Sort - Order" title="Topological Sort - Order" width="620" height="399" class="size-full wp-image-3512" srcset="/wp-content/uploads/2012/12/3.-Topological-Sort-Order.png 620w, /wp-content/uploads/2012/12/3.-Topological-Sort-Order-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Once we have the vertices with no predecessors we must remove the edges starting from them. Then – go again with the vertices with no predecessors. </p>
<figure id="attachment_3511" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/4.-Topological-Sort-step-2.png"><img src="/wp-content/uploads/2012/12/4.-Topological-Sort-step-2.png" alt="Topological Sort - step 2" title="Topological Sort - step 2" width="620" height="399" class="size-full wp-image-3511" srcset="/wp-content/uploads/2012/12/4.-Topological-Sort-step-2.png 620w, /wp-content/uploads/2012/12/4.-Topological-Sort-step-2-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>It’s as simple as that, so why do we need a revision of this algorithm? Well, basically because of its efficiency. </p>
<h2>Overview</h2>
<p>As we know most of the graph algorithms depend on the way the graph is represented in our application. We consider as the two main representations the adjacency matrix … </p>
<figure id="attachment_3510" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/5.-Adjacency-Matrix.png"><img src="/wp-content/uploads/2012/12/5.-Adjacency-Matrix.png" alt="Adjacency Matrix" title="Adjacency Matrix" width="620" height="399" class="size-full wp-image-3510" srcset="/wp-content/uploads/2012/12/5.-Adjacency-Matrix.png 620w, /wp-content/uploads/2012/12/5.-Adjacency-Matrix-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>… and adjacency lists.</p>
<figure id="attachment_3509" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/6.-Adjacency-Lists.png"><img src="/wp-content/uploads/2012/12/6.-Adjacency-Lists.png" alt="Adjacency Lists" title="Adjacency Lists" width="620" height="399" class="size-full wp-image-3509" srcset="/wp-content/uploads/2012/12/6.-Adjacency-Lists.png 620w, /wp-content/uploads/2012/12/6.-Adjacency-Lists-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Let’s first take a look of some of the main approaches to get the topologically sorted list at the end of the algorithm. </p>
<p>What can we do in order to find the vertices with no predecessors? We can only scan the entire list of vertices. </p>
<h3>Adjacency Matrix</h3>
<p>In case we’re using adjacency matrix we need|V|^2 space to store the graph. To find the vertices with no predecessors we have to scan the entire graph, which will cost us O(|V|^2) time.  And we’ll have to do that |V| times. This will be |V|^3 time consuming algorithm and for dense graphs this will be quite an ineffective algorithm.</p>
<h3>Adjacency Lists</h3>
<p>What about the adjacency list? There we need |E| space to store a directed graph. How fast can we find a node with no predecessor? Practically we’ll need O(|E|) time.  Thus in the worst case we have again O(|V|^2) time consuming programs.</p>
<p>So what can be done in order to optimize this algorithm?</p>
<p>Practically we can start by picking up a random vertex and “go back” until we get a node with no predecessors. This approach can be very effective yet also very ineffective. First of all if we have to scan all the way back to a node with no predecessors this will cost us |V| time, but if we stuck on a node that don’t have a preceding node then we’ll have a constant speed.</p>
<p>This means that we can modify the algorithm a bit in order to improve a lot the algorithm. We just need to store both incoming and outgoing edges and slightly modify the adjacency lists.</p>
<figure id="attachment_3508" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists.png"><img src="/wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists.png" alt="Modified Adjacency Lists" title="Modified Adjacency Lists" width="620" height="399" class="size-full wp-image-3508" srcset="/wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists.png 620w, /wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>What’s the algorithm now?</p>
<p>First we easily find the nodes with no predecessors. Then, using a queue, we can keep the nodes with no predecessors and on each dequeue we can remove the edges from the node to all other nodes.</p>
<h2>Pseudo Code</h2>
<pre>
1. Represent the graph with two lists on each vertex (incoming edges and outgoing edges)
2. Make an empty queue Q;
3. Make an empty topologically sorted list T;
4. Push all items with no predecessors in Q;
5. While Q is not empty
   a. Dequeue from Q into u;
   b. Push u in T;
   c. Remove all outgoing edges from u;
6. Return T;
</pre>
<p>This approach will give us a better performance than the “brute force” approach. The running time complexity is O(|V| + |E|). The problem is that we need additional space and an operational queue, but this approach is a perfect example of how by using additional space you can get a better performing algorithm.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/10/01/computer-algorithms-topological-sort-of-a-graph/" rel="bookmark" title="Computer Algorithms: Topological Sort of a Graph">Computer Algorithms: Topological Sort of a Graph </a></li>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" rel="bookmark" title="Computer Algorithms: Graphs and their Representation">Computer Algorithms: Graphs and their Representation </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/12/10/computer-algorithms-topological-sort-revisited/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Longest Increasing Subsequence</title>
		<link>/2012/12/03/computer-algorithms-longest-increasing-subsequence/</link>
		<comments>/2012/12/03/computer-algorithms-longest-increasing-subsequence/#comments</comments>
		<pubDate>Mon, 03 Dec 2012 13:22:08 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[dynamic programming]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Bellman–Ford algorithm]]></category>
		<category><![CDATA[Directed acyclic graph]]></category>
		<category><![CDATA[Dynamic programming]]></category>
		<category><![CDATA[equal sub-solutions]]></category>
		<category><![CDATA[Facebook Inc]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[graph algorithms]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[Longest increasing subsequence]]></category>
		<category><![CDATA[Mathematical optimization]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Network theory]]></category>
		<category><![CDATA[Operations research]]></category>
		<category><![CDATA[Richard Bellman]]></category>
		<category><![CDATA[Routing algorithms]]></category>
		<category><![CDATA[Shortest path problem]]></category>
		<category><![CDATA[sub-solution]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[Yahoo! Inc.]]></category>

		<guid isPermaLink="false">/?p=3478</guid>
		<description><![CDATA[Introduction A very common problem in computer programming is finding the longest increasing (decreasing) subsequence in a sequence of numbers (usually integers). Actually this is a typical dynamic programming problem. Dynamic programming can be described as a huge area of computer science problems that can be categorized by the way they can be solved. Unlike &#8230; <a href="/2012/12/03/computer-algorithms-longest-increasing-subsequence/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Longest Increasing Subsequence</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<li><a href="/2012/12/10/computer-algorithms-topological-sort-revisited/" rel="bookmark" title="Computer Algorithms: Topological Sort Revisited">Computer Algorithms: Topological Sort Revisited </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>A very common problem in computer programming is finding the longest increasing (decreasing) subsequence in a sequence of numbers (usually integers). Actually this is a typical dynamic programming problem.</p>
<p>Dynamic programming can be described as a huge area of computer science problems that can be categorized by the way they can be solved. Unlike divide and conquer, where we were able to merge the fairly equal sub-solutions in order to receive one single solution of the problem, in dynamic programming we usually try to find an optimal sub-solution and then grow it.</p>
<p>Once we have an optimal sub-solution on each step we try to upgrade it in order to cover the whole problem. Thus a typical member of the dynamic programming class is finding the longest subsequence.</p>
<p>However this problem is interesting because it can be related to graph theory. Let’s find out how.<span id="more-3478"></span></p>
<h2>Overview</h2>
<p>We already know various ways to calculate the shortest paths in a graph. Indeed finding the single-source shortest path is a typical graph problem. To model such kind of solutions we definitely need a graph represented in our solution. </p>
<p>However the single-source shortest path isn’t a straight-forward problem. It depends on many factors. Thus for positive edges <a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">the algorithm of Edsger Dijkstra</a> can be a perfect solution, but when the graph contains negative edges his algorithm is no longer useful. </p>
<p>In the presence of negative edges the Dijkstra’s algorithm doesn’t work and we’d better use the <a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Bellman-Ford algorithm</a>. It is interesting to note, that it was exactly <a href="http://en.wikipedia.org/wiki/Richard_E._Bellman" title="Richard E. Bellman" target="_blank">Richard Bellman</a> who first introduced the term “dynamic programming” in the 1940s.</p>
<p>In fact the Bellman-Ford algorithm was able to detect negative cycles. That’s too important, because in presence of negative cycles the shortest path problem is no longer well defined. </p>
<p>In the other hand when we’re talking about <a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">shortest paths in a DAG</a> (Directed Acyclic Graph) we can find a faster (linear) solution. That’s because we’re sure that there are no cycles (not even negative cycles)! </p>
<figure id="attachment_3498" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/1.-Toplogical-Sort.png"><img src="/wp-content/uploads/2012/12/1.-Toplogical-Sort.png" alt="Toplogical Sort" title="Toplogical Sort" width="620" height="399" class="size-full wp-image-3498" srcset="/wp-content/uploads/2012/12/1.-Toplogical-Sort.png 620w, /wp-content/uploads/2012/12/1.-Toplogical-Sort-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Finding the shortest paths in a DAG is closely related to the topological sorting of the DAG. This gives us a linear representation of the vertices of the DAG and we can clearly calculate the distances from the starting node to all other nodes. Note that in a DAG we have one or more nodes that can be considered as starting nodes – which means they don’t have predecessors (incoming edges).</p>
<figure id="attachment_3497" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/2.-Toplogical-Sort-2.png"><img src="/wp-content/uploads/2012/12/2.-Toplogical-Sort-2.png" alt="Toplogical Sort 2" title="Toplogical Sort 2" width="620" height="399" class="size-full wp-image-3497" srcset="/wp-content/uploads/2012/12/2.-Toplogical-Sort-2.png 620w, /wp-content/uploads/2012/12/2.-Toplogical-Sort-2-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Following the words above is pretty hard to find what all these graph algorithms have to do with finding the longest increasing (decreasing) subsequence. Actually this problem is very closely related to the toplogical sort of the DAG and the problem of finding shortest paths in a DAG.</p>
<p>That’s because we can represent our sequence as a DAG. The only thing we must care about is to “connect” with directed edges those elements that form an increasing (decreasing) pair. </p>
<figure id="attachment_3496" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/3.-Integer-Sequence.png"><img src="/wp-content/uploads/2012/12/3.-Integer-Sequence.png" alt="Integer Sequence as a DAG" title="Integer Sequence" width="620" height="399" class="size-full wp-image-3496" srcset="/wp-content/uploads/2012/12/3.-Integer-Sequence.png 620w, /wp-content/uploads/2012/12/3.-Integer-Sequence-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Thus the sequence from our example [1, 8, 2, 7, 3, 4, 1, 6] is going to look like this.</p>
<figure id="attachment_3495" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/4.-Longest-subsequence.png"><img src="/wp-content/uploads/2012/12/4.-Longest-subsequence.png" alt="Longest subsequence" title="Longest subsequence" width="620" height="399" class="size-full wp-image-3495" srcset="/wp-content/uploads/2012/12/4.-Longest-subsequence.png 620w, /wp-content/uploads/2012/12/4.-Longest-subsequence-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Another important thing to note is that we don’t search for shortest, but for longest path, since our task is to find the longest subsequence.</p>
<h2>Pseudo Code</h2>
<p>Our pseudo code for finding the shortest paths in a DAG was something like that.</p>
<pre>
1. Get the toplogically sorted list L of the DAG;
2. The starting node is s;
3. The distance to s equals to 0;
4. All other distances are initialized to &#8734;
5. For each node (v) in L\{s} do:
5.1. If dist(v) > dist(u) + w(u, v) then
5.1.1.  dist(v) := dist(u) + w(u, v)
</pre>
<p>In the above pseudo code &#8220;u&#8221; is every predecessor of &#8220;v&#8221;!</p>
<p>Now we must “reverse” the solution above in order to find the longest increasing subsequence. Note that we don&#8217;t care any more about the weight of the edges, thus we can simply substitute them with 1.</p>
<pre>
1. Get the sequence (L) as a toplogically sorted DAG;
2. For each (i) in L do:
2.1. S(i) := 1 + max(S(j), where (i, j) is an edge from the DAG);
</pre>
<h2>Application</h2>
<p>Finding the longest increasing subsequence can be very useful not only at the Google/Yahoo/Facebook interview, but also in various fields of statistics.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<li><a href="/2012/12/10/computer-algorithms-topological-sort-revisited/" rel="bookmark" title="Computer Algorithms: Topological Sort Revisited">Computer Algorithms: Topological Sort Revisited </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/12/03/computer-algorithms-longest-increasing-subsequence/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Shortest Path in a Directed Acyclic Graph</title>
		<link>/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/</link>
		<comments>/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/#comments</comments>
		<pubDate>Sun, 28 Oct 2012 19:24:22 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Bellman–Ford algorithm]]></category>
		<category><![CDATA[Dijkstra's algorithm]]></category>
		<category><![CDATA[Directed acyclic graph]]></category>
		<category><![CDATA[Distance]]></category>
		<category><![CDATA[faster algorithm]]></category>
		<category><![CDATA[Ford Motor Company]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[Longest path problem]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Network theory]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Routing algorithms]]></category>
		<category><![CDATA[Shortest path problem]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[Topological sorting]]></category>

		<guid isPermaLink="false">/?p=3419</guid>
		<description><![CDATA[Introduction We saw how to find the shortest path in a graph with positive edges using the Dijkstra’s algorithm. We also know how to find the shortest paths from a given source node to all other nodes even when there are negative edges using the Bellman-Ford algorithm. Now we’ll see that there’s a faster algorithm &#8230; <a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Shortest Path in a Directed Acyclic Graph</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/12/03/computer-algorithms-longest-increasing-subsequence/" rel="bookmark" title="Computer Algorithms: Longest Increasing Subsequence">Computer Algorithms: Longest Increasing Subsequence </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We saw how to find the shortest path in a graph with positive edges using the <a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Dijkstra’s algorithm</a>. We also know how to find the shortest paths from a given source node to all other nodes even when there are negative edges using <a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">the Bellman-Ford algorithm</a>. Now we’ll see that there’s a faster algorithm running in linear time that can find the shortest paths from a given source node to all other reachable vertices in a directed acyclic graph, also known as a DAG.</p>
<p>Because the DAG is acyclic we don’t have to worry about negative cycles. As we already know it’s pointless to speak about shortest path in the presence of negative cycles because we can “loop” over these cycles and practically our path will become shorter and shorter.</p>
<figure id="attachment_3431" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/1.-Negative-Cycles.png"><img src="/wp-content/uploads/2012/10/1.-Negative-Cycles.png" alt="Negative Cycles" title="Negative Cycles" width="620" height="399" class="size-full wp-image-3431" srcset="/wp-content/uploads/2012/10/1.-Negative-Cycles.png 620w, /wp-content/uploads/2012/10/1.-Negative-Cycles-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The presence of a negative cycles make our atempt to find the shortest path pointless!</figcaption></figure>
<p>Thus we have two problems to overcome with Dijkstra and the Bellman-Ford algorithms. First of all we needed only positive weights and on the second place we didn’t want cycles. Well, we can handle both cases in this algorithm.<span id="more-3419"></span></p>
<h2>Overview</h2>
<p>The first thing we know about DAGs is that they can easily be topologically sorted. <a href="/2012/10/01/computer-algorithms-topological-sort-of-a-graph/" title="Computer Algorithms: Topological Sort of a Graph">Topological sort</a> can be used in many practical cases, but perhaps the mostly used one is when trying to schedule dependent tasks.</p>
<figure id="attachment_3429" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/2.-Topological-Sort.png"><img src="/wp-content/uploads/2012/10/2.-Topological-Sort.png" alt="Topological Sort" title="Topological Sort" width="620" height="399" class="size-full wp-image-3429" srcset="/wp-content/uploads/2012/10/2.-Topological-Sort.png 620w, /wp-content/uploads/2012/10/2.-Topological-Sort-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Topological sort is often used to &#8220;sort&#8221; dependent tasks!</figcaption></figure>
<p>After a topological sort we end with a list of vertices of the DAG and we’re sure that if there’s an edge (u, v), u will precede v in the topologically sorted list.</p>
<figure id="attachment_3430" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/3.-Topological-Sort-part-2.png"><img src="/wp-content/uploads/2012/10/3.-Topological-Sort-part-2.png" alt="Topological Sort (part 2)" title="Topological Sort (part 2)" width="620" height="399" class="size-full wp-image-3430" srcset="/wp-content/uploads/2012/10/3.-Topological-Sort-part-2.png 620w, /wp-content/uploads/2012/10/3.-Topological-Sort-part-2-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">If there&#8217;s an edge (u,v) then u must precede v. This results in the more general case from the image. There&#8217;s no edge between B and D, but B precedes D!</figcaption></figure>
<p>This information is precious and the only thing we need to do is to pass through this sorted list and to calculate distances for a shortest paths just like the algorithm of Dijkstra.</p>
<p>OK, so let’s summarize this algorithm:<br />
&#8211;	First we must topologically sort the DAG;<br />
&#8211;	As a second step we set the distance to the source to 0 and infinity to all other vertices;<br />
&#8211;	Then for each vertex from the list we pass through all its neighbors and we check for shortest path;</p>
<p>It’s pretty much like the Dijkstra’s algorithm with the main difference that we used a priority queue then, while this time we use the list from the topological sort.</p>
<h2>Code</h2>
<p>This time the code is actually a pseudocode. Altough all the examples so far was in PHP, perhaps pseudocode is easier to understand and doesn&#8217;t bind you in a specific language implementation. Also if you don&#8217;t feel comforatable with the given programming language it can be more difficult for you to understand the code than by reading pseudocode.</p>
<pre lang="PHP line="1">
1. Topologically sort G into L;
2. Set the distance to the source to 0;
3. Set the distances to all other vertices to infinity;
4. For each vertex u in L
5.    - Walk through all neighbors v of u;
6.    - If dist(v) > dist(u) + w(u, v) 
7.       - Set dist(v) <- dist(u) + w(u, v);
</pre>
<h2>Application</h2>
<p>It’s clear why and where we must use this algorithm. The only problem is that we must be sure that the graph doesn’t have cycles. However if we’re aware of how the graph is created we may have some additional information if there are cycles or not – then this linear time algorithm can be very applicable. </p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/12/03/computer-algorithms-longest-increasing-subsequence/" rel="bookmark" title="Computer Algorithms: Longest Increasing Subsequence">Computer Algorithms: Longest Increasing Subsequence </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Topological Sort of a Graph</title>
		<link>/2012/10/01/computer-algorithms-topological-sort-of-a-graph/</link>
		<comments>/2012/10/01/computer-algorithms-topological-sort-of-a-graph/#comments</comments>
		<pubDate>Mon, 01 Oct 2012 12:03:58 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[basic graph algorithms]]></category>
		<category><![CDATA[Directed acyclic graph]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[Graph coloring]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[L]]></category>
		<category><![CDATA[Longest path problem]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[NP-complete problems]]></category>
		<category><![CDATA[Path decomposition]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[rational solution]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[Topological sorting]]></category>
		<category><![CDATA[Tree]]></category>

		<guid isPermaLink="false">/?p=3367</guid>
		<description><![CDATA[Introduction Let’s assume we have a list of tasks to accomplish. Some of the tasks depend on others, so we must be very careful with the order of their execution. If the relationship between these tasks were simple enough we could represent them as a linked list, which would be great, and we would know &#8230; <a href="/2012/10/01/computer-algorithms-topological-sort-of-a-graph/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Topological Sort of a Graph</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/12/10/computer-algorithms-topological-sort-revisited/" rel="bookmark" title="Computer Algorithms: Topological Sort Revisited">Computer Algorithms: Topological Sort Revisited </a></li>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Let’s assume we have a list of tasks to accomplish. Some of the tasks depend on others, so we must be very careful with the order of their execution. If the relationship between these tasks were simple enough we could represent them as a linked list, which would be great, and we would know the exact order of their execution. The problem is that sometimes the relations between the different tasks are more complex and some tasks depend on two or more other tasks, which in their turn depend on one or more tasks, etc.</p>
<p>Thus we can’t model this problem using linked lists or trees. The only rational solution is to model the problem using a graph. What kind of graph do we need? Well, we definitely need a directed graph, to desribe the relations, and this graph shouldn&#8217;t have cycles. So we need the so called directed acyclic graph (DAG).</p>
<figure id="attachment_3373" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/1.-TS-Directed-Graph.png"><img class="size-full wp-image-3373" title="Topological Sort. Directed Graph." src="/wp-content/uploads/2012/10/1.-TS-Directed-Graph.png" alt="Topological Sort. Directed Graph." width="620" height="399" srcset="/wp-content/uploads/2012/10/1.-TS-Directed-Graph.png 620w, /wp-content/uploads/2012/10/1.-TS-Directed-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In order to sort a graph using topological sort we need this graph to be acyclic and directed!</figcaption></figure>
<p>Why we don’t what a cycle in the graph? The answer of this question is simple and obvious. In case of cyclic graph, we wouldn’t be able to determine the priority of task execution, thus we won’t be able to sort the tasks properly.</p>
<p>Now the solution we want is to sort the vertices of the graph in some order so for each edge (u, v) u will precede v. Then we&#8217;ll have a linear order of all tasks and by starting their execution we’ll know that everything will be OK.</p>
<figure id="attachment_3372" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/2.-TS-Sort-the-vertices.png"><img src="/wp-content/uploads/2012/10/2.-TS-Sort-the-vertices.png" alt="Topological Sort. Sort the vertices." title="Topological Sort. Sort the vertices." width="620" height="399" class="size-full wp-image-3372" srcset="/wp-content/uploads/2012/10/2.-TS-Sort-the-vertices.png 620w, /wp-content/uploads/2012/10/2.-TS-Sort-the-vertices-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The output of topological sort should be a list of vertices!</figcaption></figure>
<p>This kind of sort is also known as “topological” sort (or topsort) and it is one of the very basic graph algorithms.<span id="more-3367"></span></p>
<h2>Overview</h2>
<p>OK, so we have an acyclic directed graph, how do we proceed to get a linked list with all the vertices sorted? Since it’s an acyclic graph we know that there is at least one vertex without predecessor. Thus at first place, we can put all the vertices without predecessors into our linked list.</p>
<figure id="attachment_3371" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/3.-TS-First-Step.png"><img src="/wp-content/uploads/2012/10/3.-TS-First-Step.png" alt="Topological Sort. First Step." title="Topological Sort. First Step." width="620" height="399" class="size-full wp-image-3371" srcset="/wp-content/uploads/2012/10/3.-TS-First-Step.png 620w, /wp-content/uploads/2012/10/3.-TS-First-Step-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Initially we get only the vertices without a predecessor!</figcaption></figure>
<p>This approach answers the question – is there a possibility to have more than one valid topological sort of a graph? Indeed, the only thing we’d like to do is to put all the vertices in the correct order, but since there might be vertices with no predecessors any combination of them will be a valid topological sort for a graph.</p>
<p>As we can see from the picture above even for vertices with predecessors our topological sort can vary. Thus [9, 6, 2, 7, 4, 1] is a valid topological sorted graph, but [6, 9, 2, 7, 4, 1] is also a valid topological sort out of the same graph!</p>
<p>Now we can generalize the algorithm in some basic steps.</p>
<p>1. Make an empty list L and an empty list S;<br />
2. Put all the vertices with no predecessors in L;<br />
3. While L has items in it;<br />
    3.1. Pop an item from L – n, and push it to S;<br />
    3.2. For each vertex m adjacent to n;<br />
         3.2.1. Remove (n, m);<br />
	 3.2.2. If m has no predecessors – push it to L;</p>
<figure id="attachment_3370" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/4.-TS-Second-Step.png"><img src="/wp-content/uploads/2012/10/4.-TS-Second-Step.png" alt="Topological Sort. Second Step." title="Topological Sort. Second Step." width="620" height="399" class="size-full wp-image-3370" srcset="/wp-content/uploads/2012/10/4.-TS-Second-Step.png 620w, /wp-content/uploads/2012/10/4.-TS-Second-Step-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The image above explains step 3.2. from the algorithm!</figcaption></figure>
<h2>Code</h2>
<p>Here’s the very basic <a href="/category/php/" title="PHP on stoimen.com">PHP</a> implementation. As you can see the short implementation shows us how easy this algorithm is. However its importance to computer science and programming is enormous.</p>
<pre lang="PHP">
class G
{
    protected $_g = array(
        array(0, 1, 1, 0, 0, 0, 0),
        array(0, 0, 0, 1, 0, 0, 0),
        array(0, 0, 0, 0, 1, 0, 0),
        array(0, 0, 0, 0, 1, 0, 0),
        array(0, 0, 0, 0, 0, 0, 1),
        array(0, 0, 0, 0, 0, 0, 1),
        array(0, 0, 0, 0, 0, 0, 0),
    );
    protected $_list = array();
    protected $_ts   = array();
    protected $_len  = null;
    
    public function __construct()
    {
        $this->_len = count($this->_g);
        
        // finds the vertices with no predecessors
        $sum = 0;
        for ($i = 0; $i < $this->_len; $i++) {
            for ($j = 0; $j < $this->_len; $j++) {
                $sum += $this->_g[$j][$i];
            }
            
            if (!$sum) {
                // append to list
                array_push($this->_list, $i);
            }
            $sum = 0;
        }
    }
    
    public function topologicalSort() 
    {
        while ($this->_list) {
            $t = array_shift($this->_list);
            array_push($this->_ts, $t);
            
            foreach ($this->_g[$t] as $key => $vertex) {
                if ($vertex == 1) {
                    $this->_g[$t][$key] = 0;
                    
                    $sum = 0;
                    for ($i = 0; $i < $this->_len; $i++) {
                        $sum += $this->_g[$i][$key];
                    }
                    
                    if (!$sum) {
                        array_push($this->_list, $key);
                    }
                }
                $sum = 0;
            }
        }
        
        print_r($this->_ts);
    }
}

$g = new G();
/*
Array
(
    [0] => 0
    [1] => 5
    [2] => 1
    [3] => 2
    [4] => 3
    [5] => 4
    [6] => 6
)*/
$g->topologicalSort();
</pre>
<h2>Application</h2>
<p>As I already mentioned above this algorithm is practically used to sort the execution of different tasks that depend on each other. However this isn’t its only use. Actually any kind of objects that depend on each other can be modeled with a graph. Indeed sometimes these graphs may be a trees, but most of the cases that isn’t true.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/12/10/computer-algorithms-topological-sort-revisited/" rel="bookmark" title="Computer Algorithms: Topological Sort Revisited">Computer Algorithms: Topological Sort Revisited </a></li>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/10/01/computer-algorithms-topological-sort-of-a-graph/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
