<?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:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Computer programming</title>
	<atom:link href="http://compprog.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://compprog.wordpress.com</link>
	<description>Just another programming weblog</description>
	<pubDate>Fri, 15 Feb 2008 12:49:07 +0000</pubDate>
	<generator>http://wordpress.org/?v=MU</generator>
	<language>en</language>
			<item>
		<title>Langton&#8217;s Ant</title>
		<link>http://compprog.wordpress.com/2008/02/15/langtons-ant/</link>
		<comments>http://compprog.wordpress.com/2008/02/15/langtons-ant/#comments</comments>
		<pubDate>Fri, 15 Feb 2008 12:42:52 +0000</pubDate>
		<dc:creator>scvalex</dc:creator>
		
		<category><![CDATA[Practical]]></category>

		<category><![CDATA[Simulation]]></category>

		<category><![CDATA[explanation]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[sourcecode]]></category>

		<category><![CDATA[langton]]></category>

		<category><![CDATA[ant]]></category>

		<category><![CDATA[langton's ant]]></category>

		<category><![CDATA[python]]></category>

		<category><![CDATA[pygame]]></category>

		<category><![CDATA[turmite]]></category>

		<category><![CDATA[turing machine]]></category>

		<guid isPermaLink="false">http://compprog.wordpress.com/?p=105</guid>
		<description><![CDATA[Langton&#8217;s Ant is a turmite governed by simple rules whose outcome is both unpredictable and intresting. The path taken by the ant generates some surprising shapes, never appearing when you would expect them to, but a seemingly random moments. This article describes the rules behind Langton&#8217;s Ant, shows some of the images formed and provides [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Langton&#8217;s Ant is a turmite governed by simple rules whose outcome is both unpredictable and intresting. The path taken by the ant generates some surprising shapes, never appearing when you would expect them to, but a seemingly random moments. This article describes the rules behind Langton&#8217;s Ant, shows some of the images formed and provides a Python programme to simulate the ant.</p>
<h4>Langton&#8217;s Ant</h4>
<p><a href="http://en.wikipedia.org/wiki/Chris_Langton">Chris Langton</a> is a biologist, and the founder of the field of artificial life. One of his simplest and most intresting creations is <a href="http://en.wikipedia.org/wiki/Langton's_ant">Langton&#8217;s</a> <a href="http://mathworld.wolfram.com/LangtonsAnt.html">Ant</a>. It is quite important theoretically, but it also has some intresting practical applications.</p>
<p>The ant&#8217;s world consists of a grid, possibly infinite, but limited in our example:<br />
<img src='http://compprog.files.wordpress.com/2008/02/step1.png' alt='Step1.png' /></p>
<p>The ant always moves through this grid one step at a time. It&#8217;s direction and it&#8217;s effect on the grid is defined by <em>3</em> simple rules:</p>
<ol>
<li>If the ant is on a black square, it turns right 90 degrees.</li>
<li>If the ant is on a white square, it turns left 90 degrees.</li>
<li>When the ant leaves a square, it inverts colour.</li>
</ol>
<p>It is fairly obvious that the ant&#8217;s movement will leave a coloured trail. When asked, most people would guess that either no patterns show or that some basic symmetric images appear. What actually happens is this.</p>
<p>For the first <em>50</em> or so steps, it just seems to move around randomly, and then at <strong>step 52</strong>, you get a heart:<br />
<img src='http://compprog.files.wordpress.com/2008/02/step53.png' alt='Step53.png' /></p>
<p>For the next <em>300</em> or so steps, the ant seems to draw random shapes, ofter erasing what it had drawn before. At about <strong>step 383</strong> you get something that looks like this:<br />
<img src='http://compprog.files.wordpress.com/2008/02/step383.png' alt='Step383.png' /></p>
<p>Next you get what&#8217;s technically known as <em>a mess</em>. The ant&#8217;s movement degenerates into chaos. No more patterns are observed:<br />
<a href='http://compprog.files.wordpress.com/2008/02/step2615.png' title='Step2615.png'><img src='http://compprog.files.wordpress.com/2008/02/step2615.thumbnail.png' alt='Step2615.png' /></a></p>
<p>By now, you are probably thinking: &#8220;Well yes. Simple rules, so at first you get simple patterns, but as the board gets more and more complex, the simple rules can&#8217;t handle it, so the ant moves randomly&#8221;. Well that&#8217;s right, up until about <strong>step 10000</strong>; that is when you start getting <em>highways</em>.</p>
<p>The highways the ant draws are intresting shapes. You can see one at the bottom of the next image. It is the diagonal bit going down and right. To build then, the ant seems to move in circles, the last row forcing it to draw the next. Thus, the ant continues to draw until something gets in its way. In this simulation, because the screen wraps around, the ant eventually gets back to <em>the mess</em>, where it starts moving randomly again.<br />
<a href='http://compprog.files.wordpress.com/2008/02/step10711.png' title='Step10711.png'><img src='http://compprog.files.wordpress.com/2008/02/step10711.thumbnail.png' alt='Step10711.png' /></a></p>
<p>What&#8217;s intresting is that, after some time, the ant starts building highways again. Actually, there is no known way to stop it. The only hindrance here is that the board is finite so it has a tendency to fill up. Anyway, here&#8217;s what the board looks like at <strong>step 97049</strong>:<br />
<a href='http://compprog.files.wordpress.com/2008/02/step97049.png' title='Step97049.png'><img src='http://compprog.files.wordpress.com/2008/02/step97049.thumbnail.png' alt='Step97049.png' /></a></p>
<h4>The Programme</h4>
<p>The following is a simple programme written in <a href="http://www.python.org/">Python</a> and using <a href="http://www.pygame.org/news.html">PyGame</a>.</p>
<p>The variables that control the display and the board are at the top of the programme. They are heavily commented so there shouldn&#8217;t be any problems.</p>
<p>Here&#8217;s the code in Python (<a href='http://compprog.files.wordpress.com/2008/02/langtonpy.txt' title='langton.py'>langton.py</a>):</p>
<pre name="code" class="python">

#************************************************
# Rules of the game
#	1. If the ant is on a black square, it turns
#		right 90 and moves forward one unit
#	2. If the ant is on a white square, it turns
# 		left 90 and moves forward one unit
#	3. When the ant leaves a square, it inverts
#		colour
#
# SEE: http://mathworld.wolfram.com/LangtonsAnt.html
#************************************************

import sys, pygame
from pygame.locals import *
import time

dirs = (
		(-1, 0),
		(0, 1),
		(1, 0),
		(0, -1)
		)

cellSize = 12 # size in pixels of the board (4 pixels are used to draw the grid)
numCells = 64 # length of the side of the board
background = 0, 0, 0 # background colour; black here
foreground = 23, 23, 23 # foreground colour; the grid&#039;s colour; dark gray here
textcol = 177, 177, 177 # the colour of the step display in the upper left of the screen
antwalk = 44, 88, 44 # the ant&#039;s trail; greenish here
antant = 222, 44, 44 # the ant&#039;s colour; red here
fps = 1.0 / 40 # time between steps; 1.0 / 40 means 40 steps per second

def main():
	pygame.init()

	size = width, height = numCells * cellSize, numCells * cellSize

	pygame.display.set_caption(&quot;Langton&#039;s Ant&quot;)

	screen = pygame.display.set_mode(size) # Screen is now an object representing the window in which we paint
	screen.fill(background)
	pygame.display.flip() # IMPORTANT: No changes are displayed until this function gets called

	for i in xrange(1, numCells):
		pygame.draw.line(screen, foreground, (i * cellSize, 1), (i * cellSize, numCells * cellSize), 2)
		pygame.draw.line(screen, foreground, (1, i * cellSize), (numCells * cellSize, i * cellSize), 2)
	pygame.display.flip() # IMPORTANT: No changes are displayed until this function gets called

	font = pygame.font.Font(None, 36)

	antx, anty = numCells / 2, numCells / 2
	antdir = 0
	board = [[False] * numCells for e in xrange(numCells)]

	step = 1
	pause = False
	while True:
		for event in pygame.event.get():
				if event.type == QUIT:
					return
				elif event.type == KEYUP:
					if event.key == 32: # If space pressed, pause or unpause
						pause = not pause
					elif event.key == 115:
						pygame.image.save(screen, &quot;Step%d.tga&quot; % (step))

		if pause:
			time.sleep(fps)
			continue

		text = font.render(&quot;%d &quot; % (step), True, textcol, background)
		screen.blit(text, (10, 10))

		if board[antx][anty]:
			board[antx][anty] = False # See rule 3
			screen.fill(background, pygame.Rect(antx * cellSize + 1, anty * cellSize + 1, cellSize - 2, cellSize - 2))
			antdir = (antdir + 1) % 4 # See rule 1
		else:
			board[antx][anty] = True # See rule 3
			screen.fill(antwalk, pygame.Rect(antx * cellSize + 1, anty * cellSize + 1, cellSize - 2, cellSize - 2))
			antdir = (antdir + 3) % 4 # See rule 2

		antx = (antx + dirs[antdir][0]) % numCells
		anty = (anty + dirs[antdir][1]) % numCells

		# The current square (i.e. the ant) is painted a different colour
		screen.fill(antant, pygame.Rect(antx * cellSize + 1, anty * cellSize + 1, cellSize -2, cellSize -2))

		pygame.display.flip() # IMPORTANT: No changes are displayed until this function gets called

		step += 1
		time.sleep(fps)

if __name__ == &quot;__main__&quot;:
	main()
</pre>
<p>It is intresting to note that although you know all the rules that govern the ant&#8217;s universe, you cannot predict its movement without resorting to simulation. This just goes to show that knowing the rules of the components at the lowest level might not help you understand the system as a whole.</p>
<p>That&#8217;s it. Have fun with the code. Always open to comments.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/compprog.wordpress.com/105/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/compprog.wordpress.com/105/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/compprog.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/compprog.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/compprog.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/compprog.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/compprog.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/compprog.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/compprog.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/compprog.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/compprog.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/compprog.wordpress.com/105/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=compprog.wordpress.com&blog=1850193&post=105&subd=compprog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://compprog.wordpress.com/2008/02/15/langtons-ant/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/scvalex-128.jpg" medium="image">
			<media:title type="html">scvalex</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2008/02/step1.png" medium="image">
			<media:title type="html">Step1.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2008/02/step53.png" medium="image">
			<media:title type="html">Step53.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2008/02/step383.png" medium="image">
			<media:title type="html">Step383.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2008/02/step2615.thumbnail.png" medium="image">
			<media:title type="html">Step2615.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2008/02/step10711.thumbnail.png" medium="image">
			<media:title type="html">Step10711.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2008/02/step97049.thumbnail.png" medium="image">
			<media:title type="html">Step97049.png</media:title>
		</media:content>
	</item>
		<item>
		<title>Finding All Paths of Minimum Length to a Node Using Dijkstra&#8217;s Algorithm</title>
		<link>http://compprog.wordpress.com/2008/01/17/finding-all-paths-of-minimum-length-to-a-node-using-dijkstras-algorithm/</link>
		<comments>http://compprog.wordpress.com/2008/01/17/finding-all-paths-of-minimum-length-to-a-node-using-dijkstras-algorithm/#comments</comments>
		<pubDate>Thu, 17 Jan 2008 17:00:44 +0000</pubDate>
		<dc:creator>scvalex</dc:creator>
		
		<category><![CDATA[Algorithms]]></category>

		<category><![CDATA[Graphs]]></category>

		<category><![CDATA[algorithm]]></category>

		<category><![CDATA[all]]></category>

		<category><![CDATA[all paths]]></category>

		<category><![CDATA[C]]></category>

		<category><![CDATA[code]]></category>

		<category><![CDATA[dijkstra]]></category>

		<category><![CDATA[dijsktra's algorithm]]></category>

		<category><![CDATA[explanation]]></category>

		<category><![CDATA[graph]]></category>

		<category><![CDATA[graph algorithms]]></category>

		<category><![CDATA[Greedy]]></category>

		<category><![CDATA[greedy algorithms]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[sourcecode]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://compprog.wordpress.com/2008/01/17/finding-all-paths-of-minimum-length-to-a-node-using-dijkstras-algorithm/</guid>
		<description><![CDATA[In this article I describe a way of modifying Dijkstra&#8217;s Alogrithm in order to find all the shortest path from a source to a node.
This article assumes you know how Dijkstra&#8217;s Algorithm works. If you don&#8217;t, see my previous post or the Wikipedia article.
The Problem
You know how to use Dijkstra&#8217;s algorithm to find the length [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this article I describe a way of modifying <a href="http://compprog.wordpress.com/2007/12/01/one-source-shortest-path-dijkstras-algorithm/">Dijkstra&#8217;s Alogrithm</a> in order to find all the shortest path from a source to a node.</p>
<p>This article assumes you know how Dijkstra&#8217;s Algorithm works. If you don&#8217;t, see my previous <a href="http://compprog.wordpress.com/2007/12/01/one-source-shortest-path-dijkstras-algorithm/">post</a> or the Wikipedia <a href="http://en.wikipedia.org/wiki/Dijkstra's_algorithm">article</a>.</p>
<h4>The Problem</h4>
<p>You know how to use Dijkstra&#8217;s algorithm to find the length of the shortest path to a node. You&#8217;ve even figured out how to record the path to each node. But you what you really <strong>need</strong> are <strong>all</strong> the shortest paths leading to a node.</p>
<h4>The Idea</h4>
<p>I can help, but to be honest, this is obvious.</p>
<p>In order to record the path to each node, I used an array to record which node comes before each other node in the shortest path. That is to say: <strong>prev[i]</strong> was the node that comes <strong>just before</strong> node <strong>i</strong> in the shortest path from the source to node <strong>i</strong>.</p>
<p>To record <strong>all</strong> the shortest paths that lead to a node, I just turned <strong>prev</strong> into a <a href="http://www.google.com/search?q=define%3Amatrix&amp;ie=UTF-8&amp;oe=UTF-8">matrix</a> with the following meaning: <strong>prev[i][0]</strong> is the number of nodes that could come before node i on a path of minimum length; <strong>prev[i][1..]</strong> are the nodes that could come before node i on path of minimum length.</p>
<h4>The Programme</h4>
<p>Here&#8217;s the code in C (<a href='http://compprog.files.wordpress.com/2008/01/dijkstraall.c' title='dijkstraAll.c'>dijkstraAll.c</a>):</p>
<pre name="code" class="cpp">

#include &lt;stdio.h&gt;

#define GRAPHSIZE 2048
#define INFINITY GRAPHSIZE*GRAPHSIZE
#define MAX(a, b) ((a &gt; b) ? (a) : (b))

int e; /* The number of nonzero edges in the graph */
int n; /* The number of nodes in the graph */
long dist[GRAPHSIZE][GRAPHSIZE]; /* dist[i][j] is the distance between node i and j; or 0 if there is no direct connection */
long d[GRAPHSIZE]; /* d[i] is the length of the shortest path between the source (s) and node i */
int prev[GRAPHSIZE][GRAPHSIZE + 1]; /* prev[i] holds the nodes that could comes right before i in the shortest path from the source to i;
		prev[i][0] is the number of nodes and prev[i][1..] are the nodes */

void printD() {
	int i;

	printf(&quot;Distances:\n&quot;);
	for (i = 1; i &lt;= n; ++i)
		printf(&quot;%10d&quot;, i);
	printf(&quot;\n&quot;);
	for (i = 1; i &lt;= n; ++i) {
		printf(&quot;%10ld&quot;, d[i]);
	}
	printf(&quot;\n&quot;);
}

/*
 * Prints the shortest path from the source to dest.
 *
 * dijkstra(int) MUST be run at least once BEFORE
 * this is called
 */
void printPath(int dest, int depth) {
	int i, j;

	printf(&quot;-%d\n&quot;, dest);
	for (i = 1; i &lt;= prev[dest][0]; ++i) {
		for (j = 0; j &lt;= depth; ++j)
			printf(&quot; |&quot;);
		printPath(prev[dest][i], depth + 1);
	}
}

void dijkstra(int s) {
	int i, k, mini;
	int visited[GRAPHSIZE];

	for (i = 1; i &lt;= n; ++i) {
		d[i] = INFINITY;
		prev[i][0] = 0; /* no path has yet been found to i */
		visited[i] = 0; /* the i-th element has not yet been visited */
	}

	d[s] = 0;

	for (k = 1; k &lt;= n; ++k) {
		mini = -1;
		for (i = 1; i &lt;= n; ++i)
			if (!visited[i] &amp;&amp; ((mini == -1) || (d[i] &lt; d[mini])))
				mini = i;

		visited[mini] = 1;

		for (i = 1; i &lt;= n; ++i)
			if (dist[mini][i]) {
				if (d[mini] + dist[mini][i] &lt; d[i]) { /* a shorter path has been found */
					d[i] = d[mini] + dist[mini][i];
					prev[i][0] = 1;
					prev[i][1] = mini;
				} else if (d[mini] + dist[mini][i] == d[i]) { /* a path of the same length has been found */
					++prev[i][0];
					prev[i][prev[i][0]] = mini;
				}
			}
	}
}

int main(int argc, char *argv[]) {
	int i, j;
	int u, v, w;

	FILE *fin = fopen(&quot;dist.txt&quot;, &quot;r&quot;);
	fscanf(fin, &quot;%d&quot;, &amp;e);
	for (i = 0; i &lt; e; ++i)
		for (j = 0; j &lt; e; ++j)
			dist[i][j] = 0;
	n = -1;
	for (i = 0; i &lt; e; ++i) {
		fscanf(fin, &quot;%d%d%d&quot;, &amp;u, &amp;v, &amp;w);
		dist[u][v] = w;
		n = MAX(u, MAX(v, n));
	}
	fclose(fin);

	dijkstra(1);

	printD();

	printf(&quot;\n&quot;);
	for (i = 1; i &lt;= n; ++i) {
		printf(&quot;Path to %d:\n&quot;, i);
		printPath(i, 0);
		printf(&quot;\n&quot;);
	}

	return 0;
}
</pre>
<p>And here&#8217;s an input file: <a href='http://compprog.files.wordpress.com/2008/01/dist.txt' title='dist.txt'>dist.txt</a>.<br />
<code>10<br />
1 2 5<br />
1 4 3<br />
2 3 1<br />
2 4 3<br />
3 5 6<br />
4 2 2<br />
4 3 9<br />
4 5 2<br />
5 1 7<br />
5 3 4<br />
</code></p>
<p>The input file describes this graph:<br />
<img src='http://compprog.files.wordpress.com/2008/01/djall.png' alt='djAll.png' /></p>
<p>As you can see, there are two paths from <strong>node 1</strong> to <strong>node 3</strong>: <strong>1 -&gt; 2 -&gt; 3</strong> and <strong>1 -&gt; 4 -&gt; 2 -&gt; 3</strong> both of length <em>6</em>. </p>
<p>Now, what does the programme output?<br />
<code>Distances:<br />
         1         2         3         4         5<br />
         0         5         6         3         5</p>
<p>Path to 1:<br />
-1</p>
<p>Path to 2:<br />
-2<br />
 |-1<br />
 |-4<br />
 | |-1</p>
<p>Path to 3:<br />
-3<br />
 |-2<br />
 | |-1<br />
 | |-4<br />
 | | |-1</p>
<p>Path to 4:<br />
-4<br />
 |-1</p>
<p>Path to 5:<br />
-5<br />
 |-4<br />
 | |-1<br />
</code></p>
<p>It first outputs the distances, and&#8230; yes! They&#8217;re correct.</p>
<p>Next, it prints those <a href="http://en.wikipedia.org/wiki/Ascii_art">ASCII art</a> drawings. They not drawings. They&#8217;re trees with the destination as root and the leafs as the source. To read a path from such a tree, start at a leaf (always <strong>1</strong>) and go left, reading the first numbers you can see above.</p>
<p>Let&#8217;s find the paths to <strong>node 3</strong>. There are two leafs, so there are two paths of minimal length. The first one is <strong>1 -&gt; 4 -&gt; 2 -&gt; 3</strong>. The second one is <strong>1 -&gt; 2 -&gt; 3</strong>. Check on the graph.</p>
<p>That&#8217;s it. If you&#8217;re up to a challenge, implement <strong>prev</strong> as an array of <a href="http://en.wikipedia.org/wiki/Linked_lists">linked lists</a>.</p>
<p>Good luck. Always open to comments.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/compprog.wordpress.com/101/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/compprog.wordpress.com/101/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/compprog.wordpress.com/101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/compprog.wordpress.com/101/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/compprog.wordpress.com/101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/compprog.wordpress.com/101/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/compprog.wordpress.com/101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/compprog.wordpress.com/101/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/compprog.wordpress.com/101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/compprog.wordpress.com/101/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/compprog.wordpress.com/101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/compprog.wordpress.com/101/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=compprog.wordpress.com&blog=1850193&post=101&subd=compprog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://compprog.wordpress.com/2008/01/17/finding-all-paths-of-minimum-length-to-a-node-using-dijkstras-algorithm/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/scvalex-128.jpg" medium="image">
			<media:title type="html">scvalex</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2008/01/djall.png" medium="image">
			<media:title type="html">djAll.png</media:title>
		</media:content>
	</item>
		<item>
		<title>Speeding up Dijkstra&#8217;s Algorithm 1</title>
		<link>http://compprog.wordpress.com/2008/01/17/speeding-up-dijkstras-algorithm-1/</link>
		<comments>http://compprog.wordpress.com/2008/01/17/speeding-up-dijkstras-algorithm-1/#comments</comments>
		<pubDate>Thu, 17 Jan 2008 15:44:24 +0000</pubDate>
		<dc:creator>scvalex</dc:creator>
		
		<category><![CDATA[Algorithms]]></category>

		<category><![CDATA[Graphs]]></category>

		<category><![CDATA[Practical]]></category>

		<category><![CDATA[algorithm]]></category>

		<category><![CDATA[code]]></category>

		<category><![CDATA[comparison]]></category>

		<category><![CDATA[dijkstra]]></category>

		<category><![CDATA[dijsktra's algorithm]]></category>

		<category><![CDATA[explanation]]></category>

		<category><![CDATA[graph]]></category>

		<category><![CDATA[graph algorithms]]></category>

		<category><![CDATA[Greedy]]></category>

		<category><![CDATA[greedy algorithms]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[queue]]></category>

		<category><![CDATA[sourcecode]]></category>

		<category><![CDATA[speeding up]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://compprog.wordpress.com/2008/01/17/speeding-up-dijkstras-algorithm-1/</guid>
		<description><![CDATA[In this article, I describe a simple (adds less than 1min of work) way to speed up Dijkstra&#8217;s Algorithm for finding the single source shortest path to every node in a graph.
In a previous post I described the simple O(n2) implementation of the algorithm. Here, I focus on a method that will probably speed up [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this article, I describe a simple (adds less than 1min of work) way to speed up Dijkstra&#8217;s Algorithm for finding the single source shortest path to every node in a graph.</p>
<p>In a previous <a href="http://compprog.wordpress.com/2007/12/01/one-source-shortest-path-dijkstras-algorithm/">post</a> I described the simple <strong>O(n<sup>2</sup>)</strong> implementation of the algorithm. Here, I focus on a method that will <strong>probably</strong> speed up the algorithm.</p>
<h4>Why Bother</h4>
<p>The previous implementation of the algorithm ran in <strong>O(n<sup>2</sup>)</strong> time, where <strong>n</strong> is the number of nodes in the graph. This means that for a graph of, say <em>100</em> nodes, it would do about <em>100 * 100 = 100000</em> calculations. Considering that computers nowadays are said to be able to do about <em>100000000</em> (a hundred million) calculations per second, we&#8217;re fine, and the programme will finish in well under a second. But what if we have a graph with <strong>100000</strong> nodes? This might take <strong>100 seconds</strong> to run. Now we&#8217;re in trouble. We need a faster algorithm.</p>
<p>The two most common ways to speed up Dijkstra&#8217;s Algorithm are to implement the finding of the closest node not yet visited as priority queues. Usually <a href="http://en.wikipedia.org/wiki/Heap_(data_structure)">heaps</a> or <a href="http://en.wikipedia.org/wiki/Fibonacci_heap">Fibonacci Heaps</a> are used for this purpose (Fibonacci Heaps were actually invented for this).</p>
<p>Heaps are somewhat difficult to implement and Fibonacci Heaps are horror to implement. Incidentally, there&#8217;s a very easy of speeding it up.</p>
<h4>Just Use Queues</h4>
<p>The idea is to simply use queues instead of priority queues. This way provides nowhere near the same level of speedup (the algorithm is still <strong>O(n<sup>2</sup>)</strong>), but <strong>it makes it run faster, on average, by a factor of <em>4</em></strong>.</p>
<p>Some bad news: a carefully crafted graph could slow this algorithm down to <strong>O(n<sup>3</sup>)</strong>. As a rule, graphs in real life are <strong>never</strong> like this, and, as the method isn&#8217;t widely known, test sets for contests are not written to catch this optimisation.</p>
<p>Now for the good news: it&#8217;s shockingly easy to write. Compare the old <strong>dijkstra1()</strong> with the new <strong>dijkstra2()</strong>.</p>
<pre name="code" class="cpp">

void dijkstra1(int s) {
	int i, k, mini;
	int visited[GRAPHSIZE];

	for (i = 1; i &lt;= n; ++i) {
		d1[i] = INFINITY;
		visited[i] = 0; /* the i-th element has not yet been visited */
	}

	d1[s] = 0;

	for (k = 1; k &lt;= n; ++k) {
		mini = -1;
		for (i = 1; i &lt;= n; ++i)
			if (!visited[i] &amp;&amp; ((mini == -1) || (d1[i] &lt; d1[mini])))
				mini = i;

		visited[mini] = 1;

		for (i = 1; i &lt;= n; ++i)
			if (dist[mini][i])
				if (d1[mini] + dist[mini][i] &lt; d1[i])
					d1[i] = d1[mini] + dist[mini][i];
	}
}

void dijkstra2(int s) {
	int queue[GRAPHSIZE];
	char inQueue[GRAPHSIZE];
	int begq = 0,
	    endq = 0;
	int i, mini;
	int visited[GRAPHSIZE];

	for (i = 1; i &lt;= n; ++i) {
		d2[i] = INFINITY;
		visited[i] = 0; /* the i-th element has not yet been visited */
		inQueue[i] = 0;
	}

	d2[s] = 0;
	queue[endq] = s;
	endq = (endq + 1) % GRAPHSIZE;

	while (begq != endq) {
		mini = queue[begq];
		begq = (begq + 1) % GRAPHSIZE;
		inQueue[mini] = 0;

		visited[mini] = 1;

		for (i = 1; i &lt;= n; ++i)
			if (dist[mini][i])
				if (d2[mini] + dist[mini][i] &lt; d2[i]) {
					d2[i] = d2[mini] + dist[mini][i];
					if (!inQueue[i]) {
						queue[endq] = i;
						endq = (endq + 1) % GRAPHSIZE;
						inQueue[i] = 1;
					}
				}
	}
}
</pre>
<p>What&#8217;s changed? First, we <strong>define several new variables</strong>. These, together, make up the queue:</p>
<pre name="code" class="cpp">

int queue[GRAPHSIZE];
char inQueue[GRAPHSIZE];
int begq = 0,
    endq = 0;
</pre>
<p>Next, during the initialisation part of the function, we <strong>mark all nodes as not being in the queue</strong>.</p>
<pre name="code" class="cpp">

for (i = 1; i &lt;= n; ++i) {
	/* OTHER INITIALISATIONS (look at the programme) */
	inQueue[i] = 0;
}
</pre>
<p>Now, add the source node to the queue.</p>
<pre name="code" class="cpp">

queue[endq] = s;
endq = (endq + 1) % GRAPHSIZE;
</pre>
<p>What does this do? The first line add <strong>s</strong> to the end of the queue. The second line moves the end of the queue one step to the right (I&#8217;ll explain a few paragraphs down). The modulo operation here is not really necessary, but I like to be consistent.</p>
<p>At this point we&#8217;ll start looping. When do we stop? The idea here is that a node is in the queue when its neighbours need to be updated (i.e. when a new shortest path might be found leading to them). So, we stop when the queue is empty. Note that this occurs when <strong>begq == endq</strong> and <strong>not</strong> when <strong>!(begq &lt; endq)</strong>. So, <strong>while (begq &lt; endq)</strong> is incorrect because, in one case, <strong>begq</strong> will be greater then <strong>endq</strong>.</p>
<p>What was the first thing we did in the loop? We were supposed to find the closest node not yet visited. Now, we merely take the first node from the queue.</p>
<pre name="code" class="cpp">

mini = queue[begq];
begq = (begq + 1) % GRAPHSIZE;
inQueue[mini] = 0;
</pre>
<p>Here, the first element is pop&#8217;d out of the queue, the head of the queue is moved one step to the right and the element is marked as not being in the queue. The problem with queues in general, and this one in particular is that the part of them that actually hold the elements tends to move around. Here, every insert moves the tail one step to the right and every pop moves the head one step to the right. Consider the following sequence of operations:</p>
<p><a href='http://compprog.files.wordpress.com/2008/01/queue.png' title='queue.png'><img src='http://compprog.files.wordpress.com/2008/01/queue.png' alt='queue.png' /></a></p>
<p>Moves <em>1</em> through <em>8</em> clearly show that, while the size of the information content of the queue changes erratically, it constantly moves to the right. What happened at <em>9</em>? The queue got to the end of available memory and wrapped around to the beginning. This is the purpose of <strong>(begq + 1) % GRAPHSIZE</strong> and <strong>(endq + 1) % GRAPHSIZE</strong>. It turns <em>7</em>, <em>8</em>, <em>9</em>, etc. into <em>1</em>, <em>2</em>, <em>3</em>, etc. But won&#8217;t <strong>endq</strong> overrun <strong>begq</strong>? No, the use of <strong>inQueue</strong> guarantees that no element will be inserted in the queue more than once. And as the queue is of size <strong>GRAPHSIZE</strong>, no overrun is possible.</p>
<p>So far, so good. One last modification: when we update the distance to a node, we add it to the queue (if it&#8217;s not already in it).</p>
<pre name="code" class="cpp">

for (i = 1; i &lt;= n; ++i)
	if (dist[mini][i])
		if (d2[mini] + dist[mini][i] &lt; d2[i]) {
			d2[i] = d2[mini] + dist[mini][i];
			if (!inQueue[i]) {
				queue[endq] = i;
				endq = (endq + 1) % GRAPHSIZE;
				inQueue[i] = 1;
			}
		}
</pre>
<h4>Comparing the speed</h4>
<p>When I first wrote this, I wanted to be able to check that it outputs correct results and I wanted to see how much faster it is. The following programme does both. The function <strong>cmpd()</strong> checks the output against that given by the simple implementation and the various <strong>clock()</strong> calls littered through the code time the two functions.</p>
<p>Here&#8217;s the code in C (<a href='http://compprog.files.wordpress.com/2008/01/dijkstra2.c' title='dijkstra2.c'>dijkstra2.c</a>):<br />
<strong>Note</strong>: Source might be mangled by WordPress, consider downloading the file.</p>
<pre name="code" class="cpp">

#include
#include 

#define GRAPHSIZE 2048
#define INFINITY GRAPHSIZE*GRAPHSIZE
#define MAX(a, b) ((a &amp;gt; b) ? (a) : (b))

int e; /* The number of nonzero edges in the graph */
int n; /* The number of nodes in the graph */
long dist[GRAPHSIZE][GRAPHSIZE]; /* dist[i][j] is the distance between node i and j; or 0 if there is no direct connection */
long d1[GRAPHSIZE], d2[GRAPHSIZE]; /* d[i] is the length of the shortest path between the source (s) and node i */

void dijkstra1(int s) {
	int i, k, mini;
	int visited[GRAPHSIZE];

	for (i = 1; i &lt;= n; ++i) {
		d1[i] = INFINITY;
		visited[i] = 0; /* the i-th element has not yet been visited */
	}

	d1[s] = 0;

	for (k = 1; k &lt;= n; ++k) {
		mini = -1;
		for (i = 1; i &lt;= n; ++i)
			if (!visited[i] &amp;&amp; ((mini == -1) || (d1[i] &lt; d1[mini])))
				mini = i;

		visited[mini] = 1;

		for (i = 1; i &lt;= n; ++i)
			if (dist[mini][i])
				if (d1[mini] + dist[mini][i] &lt; d1[i])
					d1[i] = d1[mini] + dist[mini][i];
	}
}

void dijkstra2(int s) {
	int queue[GRAPHSIZE];
	char inQueue[GRAPHSIZE];
	int begq = 0,
	    endq = 0;
	int i, mini;
	int visited[GRAPHSIZE];

	for (i = 1; i &lt;= n; ++i) {
		d2[i] = INFINITY;
		visited[i] = 0; /* the i-th element has not yet been visited */
		inQueue[i] = 0;
	}

	d2[s] = 0;
	queue[endq] = s;
	endq = (endq + 1) % GRAPHSIZE;

	while (begq != endq) {
		mini = queue[begq];
		begq = (begq + 1) % GRAPHSIZE;
		inQueue[mini] = 0;

		visited[mini] = 1;

		for (i = 1; i &lt;= n; ++i)
			if (dist[mini][i])
				if (d2[mini] + dist[mini][i] &lt; d2[i]) {
					d2[i] = d2[mini] + dist[mini][i];
					if (!inQueue[i]) {
						queue[endq] = i;
						endq = (endq + 1) % GRAPHSIZE;
						inQueue[i] = 1;
					}
				}
	}
}

int cmpd() {
	int i;

	for (i = 0; i &amp;lt; n; ++i)
		if (d1[i] != d2[i])
			return 0;

	return 1;
}

int main(int argc, char *argv[]) {
	int i, j;
	int u, v, w;
	long t1 = 0,
	     t2 = 0;

	FILE *fin = fopen(&quot;dist2.txt&quot;, &quot;r&quot;);
	fscanf(fin, &quot;%d&quot;, &amp;amp;e);
	for (i = 0; i &amp;lt; e; ++i)
		for (j = 0; j &amp;lt; e; ++j)
			dist[i][j] = 0;
	n = -1;
	for (i = 0; i &amp;lt; e; ++i) {
		fscanf(fin, &quot;%d%d%d&quot;, &amp;amp;u, &amp;amp;v, &amp;amp;w);
		dist[u][v] = w;
		n = MAX(u, MAX(v, n));
	}
	fclose(fin);

	for (i = 1; i &amp;lt;= n; ++i) {
		long aux = clock();
		dijkstra1(i);
		t1 += clock() - aux;
		aux = clock();
		dijkstra2(i);
		t2 += clock() - aux;
		if (i % 10 == 0) {
			printf(&quot;%d / %d\n&quot;, i, n);
			fflush(stdout);
		}
		if (!cmpd()) {
			printf(&quot;\nResults for %d do NOT match\n&quot;, i);
			break;
		}
	}
	printf(&quot;\n&quot;);

	printf(&quot;Dijkstra O(N^2):\t\t%ld\n&quot;, t1);
	printf(&quot;Dijkstra unstable:\t\t%ld\n&quot;, t2);
	printf(&quot;Ratio:\t\t\t\t%.2f\n&quot;, (float)t1/t2);

	/* printD(); */

	return 0;
}
</pre>
<p>And here&#8217;s a big <em>1200</em> node graph: <a href='http://compprog.files.wordpress.com/2008/01/dist2.txt' title='dist2.txt'>dist2.txt</a>.</p>
<p>Have fun and good luck. Always open to comments.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/compprog.wordpress.com/97/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/compprog.wordpress.com/97/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/compprog.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/compprog.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/compprog.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/compprog.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/compprog.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/compprog.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/compprog.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/compprog.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/compprog.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/compprog.wordpress.com/97/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=compprog.wordpress.com&blog=1850193&post=97&subd=compprog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://compprog.wordpress.com/2008/01/17/speeding-up-dijkstras-algorithm-1/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/scvalex-128.jpg" medium="image">
			<media:title type="html">scvalex</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2008/01/queue.png" medium="image">
			<media:title type="html">queue.png</media:title>
		</media:content>
	</item>
		<item>
		<title>Gaussian Elimination</title>
		<link>http://compprog.wordpress.com/2007/12/11/gaussian-elimination/</link>
		<comments>http://compprog.wordpress.com/2007/12/11/gaussian-elimination/#comments</comments>
		<pubDate>Tue, 11 Dec 2007 13:42:15 +0000</pubDate>
		<dc:creator>scvalex</dc:creator>
		
		<category><![CDATA[Algorithms]]></category>

		<category><![CDATA[Practical]]></category>

		<category><![CDATA[gauss math mathematics gaussian elimination matrix equa]]></category>

		<guid isPermaLink="false">http://compprog.wordpress.com/2007/12/11/gaussian-elimination/</guid>
		<description><![CDATA[In this article, I describe Gauss&#8217; algorithm for solving n linear equations with n unknowns. I also give a sample implementation in C.
The Problem
Let&#8217;s say you want to solve the following system of 3 equations with 3 unknowns:

Humans learn that there a two ways to solve this system. Reduction and substitution. Unfortunately, neither of these [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this article, I describe <a href="http://en.wikipedia.org/wiki/Gaussian_elimination">Gauss&#8217; algorithm</a> for solving <em>n</em> linear equations with <em>n</em> unknowns. I also give a sample implementation in C.</p>
<h4>The Problem</h4>
<p>Let&#8217;s say you want to solve the following system of <em>3</em> equations with <em>3</em> unknowns:<br />
<img src='http://compprog.files.wordpress.com/2007/12/eqset.png' alt='eqset.png' /></p>
<p>Humans learn that there a two ways to solve this <a href="http://en.wikipedia.org/wiki/System_of_linear_equations">system</a>. Reduction and substitution. Unfortunately, neither of these methods is suitable for a computer.</p>
<p>A simple algorithm (and the one used everywhere even today), was discovered by <a href="http://en.wikipedia.org/wiki/Carl_Friedrich_Gauss">Gauss</a> more than two hundred years ago. Since then, some refinements have been found, but the basic procedure remains unchanged.</p>
<h4>Gaussian Elimination</h4>
<p>Start by writing the system in matrix form:<br />
<img src='http://compprog.files.wordpress.com/2007/12/s1.png' alt='s1.png' /></p>
<p>If you recall how matrix multiplication works, you&#8217;ll see that&#8217;s true. If not, it&#8217;s enough to notice how the matrix is written: the coefficients of <em>x</em>, <em>y</em> and <em>z</em> are written, side by side, as the rows of a 3&#215;3 matrix; <em>x</em>, <em>y</em> and <em>z</em> are then written as rows of a 3&#215;1 matrix; finally, what&#8217;s left of the equality sign is written one under the other as a 3&#215;1 matrix.</p>
<p>So far, this doesn&#8217;t actually help, but it does make the following process easier to write. The goal is, through simple transformations, to reach the system, where <em>a</em>, <em>b</em> and <em>c</em> are known.<br />
<img src='http://compprog.files.wordpress.com/2007/12/s2.png' alt='s2.png' /></p>
<p>How do you transform the initial system into the above one? Here&#8217;s Gauss&#8217; idea.</p>
<p>Start with the initial system, then perform some operations to get <em>0</em>s on the first column, on every row but the first.<br />
<img src='http://compprog.files.wordpress.com/2007/12/s3.png' alt='s3.png' /></p>
<p>The operations mentioned are multiplying the first rows by <em>-3/2</em> and substracting it from the second. Then multiplying the first rows by <em>-1</em> and substracting it from the third. What is <em>-3/2</em>? It&#8217;s first element of the second row divided by the first element of the first row. And <em>-1</em>? It&#8217;s the first element of the third row divided by the first element of the first row. <strong>NOTE</strong> The changes to row 1 are never actually written back into the matrix.</p>
<p>For now we&#8217;re done with row 1, so we move on to row 2. The goal here is to get every row on the second column under row 2 to 0. We do this by multiplying the second rows by <em>4</em> (i.e. <em>2 / (1 / 2)</em>) and substracting it from the third rows.<br />
<img src='http://compprog.files.wordpress.com/2007/12/s4.png' alt='s4.png' /></p>
<p>Now it&#8217;s easy to find the value of <em>z</em>. Just multiply the third column by <em>-1</em> (i.e. <em>-1/1</em>).<br />
<img src='http://compprog.files.wordpress.com/2007/12/s5.png' alt='s5.png' /></p>
<p><strong>ERRATA</strong>: The <em>7</em> in the above matrix should be an <em>8</em>.</p>
<p>Knowing the value of <em>z</em>, we can now eliminate it from the other two equations.<br />
<img src='http://compprog.files.wordpress.com/2007/12/s6.png' alt='s6.png' /></p>
<p>Now, we can find the value of <em>y</em> and eliminate <em>y</em> from the first equation.<br />
<img src='http://compprog.files.wordpress.com/2007/12/s7.png' alt='s7.png' /></p>
<p><img src='http://compprog.files.wordpress.com/2007/12/s8.png' alt='s8.png' /></p>
<p>And, finally, the value of <em>x</em> is:<br />
<img src='http://compprog.files.wordpress.com/2007/12/s9.png' alt='s9.png' /></p>
<p>And with that, we&#8217;re done.</p>
<h4>The Programme</h4>
<p>Unfortunately, this is easier said than done. The actual computer programme has to take into account divisions by zero and numerical instabilities. This adds to the complexity of <strong>forwardSubstitution()</strong>.</p>
<p>Here&#8217;s the code in C (<a href='http://compprog.files.wordpress.com/2007/12/gauss.c' title='gauss.c'>gauss.c</a>):</p>
<pre name="code" class="cpp">

#include &lt;stdio.h&gt;

int n;
float a[10][11];

void forwardSubstitution() {
	int i, j, k, max;
	float t;
	for (i = 0; i &lt; n; ++i) {
		max = i;
		for (j = i + 1; j &lt; n; ++j)
			if (a[j][i] &gt; a[max][i])
				max = j;

		for (j = 0; j &lt; n + 1; ++j) {
			t = a[max][j];
			a[max][j] = a[i][j];
			a[i][j] = t;
		}

		for (j = n; j &gt;= i; --j)
			for (k = i + 1; k &lt; n; ++k)
				a[k][j] -= a[k][i]/a[i][i] * a[i][j];

/*		for (k = 0; k &lt; n; ++k) {
			for (j = 0; j &lt; n + 1; ++j)
				printf(&quot;%.2f\t&quot;, a[k][j]);
			printf(&quot;\n&quot;);
		}*/
	}
}

void reverseElimination() {
	int i, j;
	for (i = n - 1; i &gt;= 0; --i) {
		a[i][n] = a[i][n] / a[i][i];
		a[i][i] = 1;
		for (j = i - 1; j &gt;= 0; --j) {
			a[j][n] -= a[j][i] * a[i][n];
			a[j][i] = 0;
		}
	}
}

void gauss() {
	int i, j;

	forwardSubstitution();
	reverseElimination();

	for (i = 0; i &lt; n; ++i) {
		for (j = 0; j &lt; n + 1; ++j)
			printf(&quot;%.2f\t&quot;, a[i][j]);
		printf(&quot;\n&quot;);
	}
}

int main(int argc, char *argv[]) {
	int i, j;

	FILE *fin = fopen(&quot;gauss.in&quot;, &quot;r&quot;);
	fscanf(fin, &quot;%d&quot;, &amp;n);
	for (i = 0; i &lt; n; ++i)
		for (j = 0; j &lt; n + 1; ++j)
			fscanf(fin, &quot;%f&quot;, &amp;a[i][j]);
	fclose(fin);

	gauss();

	return 0;
}
</pre>
<p>In the above code, the first two for-s of <strong>forwardSubstitution()</strong>, just swap two rows so as to diminish the possibilities of some bad rounding errors. Also, if it exists with a division by zero error, that probably means the system cannot be solved.</p>
<p>And here&#8217;s the input file for the example (<a href='http://compprog.files.wordpress.com/2007/12/gaussin.txt' title='gauss.in'>gauss.in</a>) (save it as gauss.in):<br />
<code>3<br />
2	1	-1	8<br />
-3	-1	2	-11<br />
-2	1	2	-3<br />
</code></p>
<p>That&#8217;s it. Good luck. Always open to comments.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/compprog.wordpress.com/82/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/compprog.wordpress.com/82/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/compprog.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/compprog.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/compprog.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/compprog.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/compprog.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/compprog.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/compprog.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/compprog.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/compprog.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/compprog.wordpress.com/82/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=compprog.wordpress.com&blog=1850193&post=82&subd=compprog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://compprog.wordpress.com/2007/12/11/gaussian-elimination/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/scvalex-128.jpg" medium="image">
			<media:title type="html">scvalex</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/eqset.png" medium="image">
			<media:title type="html">eqset.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/s1.png" medium="image">
			<media:title type="html">s1.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/s2.png" medium="image">
			<media:title type="html">s2.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/s3.png" medium="image">
			<media:title type="html">s3.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/s4.png" medium="image">
			<media:title type="html">s4.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/s5.png" medium="image">
			<media:title type="html">s5.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/s6.png" medium="image">
			<media:title type="html">s6.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/s7.png" medium="image">
			<media:title type="html">s7.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/s8.png" medium="image">
			<media:title type="html">s8.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/s9.png" medium="image">
			<media:title type="html">s9.png</media:title>
		</media:content>
	</item>
		<item>
		<title>One Source Shortest Path: Dijkstra&#8217;s Algorithm</title>
		<link>http://compprog.wordpress.com/2007/12/01/one-source-shortest-path-dijkstras-algorithm/</link>
		<comments>http://compprog.wordpress.com/2007/12/01/one-source-shortest-path-dijkstras-algorithm/#comments</comments>
		<pubDate>Sat, 01 Dec 2007 19:34:20 +0000</pubDate>
		<dc:creator>scvalex</dc:creator>
		
		<category><![CDATA[Algorithms]]></category>

		<category><![CDATA[Graphs]]></category>

		<category><![CDATA[Greedy]]></category>

		<category><![CDATA[algorithm]]></category>

		<category><![CDATA[code]]></category>

		<category><![CDATA[dijkstra]]></category>

		<category><![CDATA[dijsktra's algorithm]]></category>

		<category><![CDATA[explanation]]></category>

		<category><![CDATA[graph]]></category>

		<category><![CDATA[graph algorithms]]></category>

		<category><![CDATA[greedy algorithms]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[sourcecode]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://compprog.wordpress.com/2007/12/01/one-source-shortest-path-dijkstras-algorithm/</guid>
		<description><![CDATA[In this article I describe Dijkstra&#8217;s algorithm for finding the shortest path from one source to all the other vertexes in a graph. Afterwards, I provide the source code in C of a simple implementation.
To understand this you should know what a graph is, and how to store one in memory. If in doubt check [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this article I describe Dijkstra&#8217;s algorithm for finding the shortest path from one source to all the other vertexes in a graph. Afterwards, I provide the source code in C of a simple implementation.</p>
<p>To understand this you should know what a graph is, and how to store one in memory. If in doubt check <a href="http://compprog.wordpress.com/2007/11/09/minimal-spanning-trees-prims-algorithm/">this</a> and <a href="http://en.wikipedia.org/wiki/Graph_(mathematics)">this</a>.</p>
<p>Another solution for this problem is the <a href="http://compprog.wordpress.com/2007/11/29/one-source-shortest-path-the-bellman-ford-algorithm/">Bellman-Ford algorithm</a>.</p>
<h4>The Problem</h4>
<p>Given the following graph calculate the length of the shortest path from <strong>node 1</strong> to every other node.<br />
<img src='http://compprog.files.wordpress.com/2007/11/dj1.png' alt='dj1.png' /></p>
<p>Lets take the nodes <strong>1</strong> and <strong>3</strong>. There are several paths (<strong>1 -&gt; 4 -&gt; 3</strong>, <strong>1 -&gt; 2 -&gt; 3</strong>, etc.), but the shortest of them is <strong>1 -&gt; 4 -&gt; 2 -&gt; 3</strong> of length <strong>9</strong>. Our job is to find it.</p>
<h4>The Algorithm</h4>
<p><a href="http://en.wikipedia.org/wiki/Dijkstra's_algorithm">Dijkstra&#8217;s algorithm</a> is one of the most common solutions to this problem. Even so, it only works on graphs which have <strong>no edges of negative weight</strong>, and the actual speed of the algorithm can vary from <strong>O(n*lg(lg(n)))</strong> to <strong>O(n<sup>2</sup>)</strong>.</p>
<p>The idea is somewhat simple:</p>
<p>Take the length of the shortest path to all nodes to be infinity. Mark the length of the shortest path to the source as <em>0</em>.</p>
<p><img src='http://compprog.files.wordpress.com/2007/12/dj2.png' alt='dj2.png' /></p>
<p>Now, we already know that the graph has no edges of negative weight so the a path of length <em>0</em> is the best we can come up with. The path to the source is <em>0</em>, so it&#8217;s optimal.</p>
<p>This algorithm works by making the paths to one more node optimal at each step. So, at the <em>k</em>th step, you know for sure that there are at least <em>k</em> nodes to which you know the shortest path.</p>
<p>At each step, choose the node, which is not yet optimal, but which is closest to the source; i.e. the node to which the current calculated shortest path is smallest. Then, from it, try to optimise the path to every node connected to it. Finally, mark the said node as <em>optimal</em> (visited, if you prefer). In the previous example, the node which is closest to the source and is not yet optimal is the source. From it, you can optimise the path to nodes <em>2</em> and <em>4</em>.<br />
<img src='http://compprog.files.wordpress.com/2007/12/dj3.png' alt='dj3_1.png' /></p>
<p>At this point, the only visited/optimal node is <em>0</em>. Now we have to redo this step <em>4</em> more times (to ensure that all nodes are optimal).</p>
<p>The next node to consider is <em>4</em>:<br />
<img src='http://compprog.files.wordpress.com/2007/12/dj4.png' alt='dj4.png' /></p>
<p>It&#8217;s worthwhile to note that at this step, we&#8217;ve also found a better path to node <em>2</em>.<br />
Next is node <em>2</em>:<br />
<img src='http://compprog.files.wordpress.com/2007/12/dj5.png' alt='dj5.png' /></p>
<p>Finally, we look at nodes <em>5</em> and <em>3</em> (none of which offer any optimisations):<br />
<img src='http://compprog.files.wordpress.com/2007/12/dj5.png' alt='dj5.png' /></p>
<p><img src='http://compprog.files.wordpress.com/2007/12/dj5.png' alt='dj5.png' /></p>
<p>The actual code in C looks something like this:</p>
<pre name="code" class="cpp">

void dijkstra(int s) {
        int i, k, mini;
        int visited[GRAPHSIZE];

        for (i = 1; i &lt;= n; ++i) {
                d[i] = INFINITY;
                visited[i] = 0; /* the i-th element has not yet been visited */
        }

        d[s] = 0;

        for (k = 1; k &lt;= n; ++k) {
                mini = -1;
                for (i = 1; i &lt;= n; ++i)
                        if (!visited[i] &amp;&amp; ((mini == -1) || (d[i] &lt; d[mini])))
                                mini = i;

                visited[mini] = 1;

                for (i = 1; i &lt;= n; ++i)
                        if (dist[mini][i])
                                if (d[mini] + dist[mini][i] &lt; d[i])
                                        d[i] = d[mini] + dist[mini][i];
        }
}
</pre>
<h4>The Programme</h4>
<p>Putting the above into context, we get the <strong>O(n<sup>2</sup>)</strong> implementation. This works well for most graphs (it will <strong>not</strong> work for graphs with negative weight edges), and it&#8217;s quite fast.</p>
<p>Here&#8217;s the source code in C (<a href='http://compprog.files.wordpress.com/2007/12/dijkstra.c' title='dijkstra.c'>dijkstra.c</a>):</p>
<pre name="code" class="cpp">

#include &lt;stdio.h&gt;

#define GRAPHSIZE 2048
#define INFINITY GRAPHSIZE*GRAPHSIZE
#define MAX(a, b) ((a &gt; b) ? (a) : (b))

int e; /* The number of nonzero edges in the graph */
int n; /* The number of nodes in the graph */
long dist[GRAPHSIZE][GRAPHSIZE]; /* dist[i][j] is the distance between node i and j; or 0 if there is no direct connection */
long d[GRAPHSIZE]; /* d[i] is the length of the shortest path between the source (s) and node i */

void printD() {
	int i;
	for (i = 1; i &lt;= n; ++i)
		printf(&quot;%10d&quot;, i);
	printf(&quot;\n&quot;);
	for (i = 1; i &lt;= n; ++i) {
		printf(&quot;%10ld&quot;, d[i]);
	}
	printf(&quot;\n&quot;);
}

void dijkstra(int s) {
	int i, k, mini;
	int visited[GRAPHSIZE];

	for (i = 1; i &lt;= n; ++i) {
		d[i] = INFINITY;
		visited[i] = 0; /* the i-th element has not yet been visited */
	}

	d[s] = 0;

	for (k = 1; k &lt;= n; ++k) {
		mini = -1;
		for (i = 1; i &lt;= n; ++i)
			if (!visited[i] &amp;&amp; ((mini == -1) || (d[i] &lt; d[mini])))
				mini = i;

		visited[mini] = 1;

		for (i = 1; i &lt;= n; ++i)
			if (dist[mini][i])
				if (d[mini] + dist[mini][i] &lt; d[i])
					d[i] = d[mini] + dist[mini][i];
	}
}

int main(int argc, char *argv[]) {
	int i, j;
	int u, v, w;

	FILE *fin = fopen(&quot;dist.txt&quot;, &quot;r&quot;);
	fscanf(fin, &quot;%d&quot;, &amp;e);
	for (i = 0; i &lt; e; ++i)
		for (j = 0; j &lt; e; ++j)
			dist[i][j] = 0;
	n = -1;
	for (i = 0; i &lt; e; ++i) {
		fscanf(fin, &quot;%d%d%d&quot;, &amp;u, &amp;v, &amp;w);
		dist[u][v] = w;
		n = MAX(u, MAX(v, n));
	}
	fclose(fin);

	dijkstra(1);

	printD();

	return 0;
}
</pre>
<p>And here&#8217;s a sample input file(<a href='http://compprog.files.wordpress.com/2007/12/dist.txt' title='dist.txt'>dist.txt</a>):</p>
<p><code>10<br />
1 2 10<br />
1 4 5<br />
2 3 1<br />
2 4 3<br />
3 5 6<br />
4 2 2<br />
4 3 9<br />
4 5 2<br />
5 1 7<br />
5 3 4<br />
</code></p>
<p>The graph is given as an edge list:</p>
<ul>
<li>the first line contains <em>e</em>, the number of edges</li>
<li>the following <em>e</em> lines contain <em>3</em> numbers: <em>u</em>, <em>v</em> and <em>w</em> signifying that there&#8217;s an edge from <em>u</em> to <em>v</em> of weight <em>w</em></li>
</ul>
<p>That&#8217;s it. Good luck and have fun. Always open to comments.</p>
<h4>Finding the shortest path</h4>
<p><strong>UPDATE</strong> In response to <strong>campOs</strong>&#8216; comment.</p>
<p>Now we know the distance between the source node and any other node (the distance to the ith node is remembered in <strong>d[i]</strong>). But suppose we also need the path (which nodes make up the path).</p>
<p>Look at the above code. Where is <strong>d</strong> modified? Where is the recorded distance between the source and a node modified? In two places:</p>
<p>Firstly, <strong>d[s]</strong> is initialised to be <em>0</em>.</p>
<pre name="code" class="cpp">

d[s] = 0;
</pre>
<p>And then, when a new shortest path is found, <strong>d[i]</strong> is updated accordingly:</p>
<pre name="code" class="cpp">

for (i = 1; i &lt;= n; ++i)
	if (dist[mini][i])
		if (d[mini] + dist[mini][i] &lt; d[i])
			d[i] = d[mini] + dist[mini][i];
</pre>
<p>The important thing to notice here is that <strong>when you update the shortest distance to node i, you know the previous node in the path to i</strong>. This is, of course, <strong>mini</strong>. This suggests the solution to our problem.</p>
<p>For every node <strong>i</strong> other than the source, remember not only the distance to it, but also the previous node in the path to it. Thus we have a new array, <strong>prev</strong>.</p>
<p>Now, we need to make to modifications.<br />
First, we initialise the value of <strong>prev[i]</strong> to something impossible (say <em>-1</em>) at the start of <strong>dijkstra()</strong>.</p>
<pre name="code" class="cpp">

for (i = 1; i &lt;= n; ++i) {
	d[i] = INFINITY;
	prev[i] = -1; /* no path has yet been found to i */
	visited[i] = 0; /* the i-th element has not yet been visited */
}
</pre>
<p>Secondly, we update the value of <strong>prev[i]</strong> every time a new shortest path is found to i.</p>
<pre name="code" class="cpp">

for (i = 1; i &lt;= n; ++i)
	if (dist[mini][i])
		if (d[mini] + dist[mini][i] &lt; d[i]) {
			d[i] = d[mini] + dist[mini][i];
			prev[i] = mini;
		}
</pre>
<p>Good. For every node reachable from the source we know which node is just before it in the shortest path. For the above example, we would have the following array:<br />
<code>i - prev[i]<br />
1 - -1<br />
2 - 4<br />
3 - 2<br />
4 - 1<br />
5 - 4<br />
</code></p>
<p>Using this, how do you get the path? Let&#8217;s say you want to get to <em>3</em>. Which node comes right before <em>3</em>? Node <em>2</em>. Which node comes right before node <em>2</em>? Node <em>4</em>. Which node comes before <em>4</em>? Node <em>1</em>. We&#8217;ve reached the source, so we&#8217;re done. Go through this list backwards and you get the path: <em>1 -&gt; 4 -&gt; 2 -&gt; 3</em>. This is easily implemented with <a href="http://en.wikipedia.org/wiki/Recursion">recursion</a>.</p>
<pre name="code" class="cpp">

void printPath(int dest) {
	if (prev[dest] != -1)
		printPath(prev[dest]);
	printf(&quot;%d &quot;, dest);
}
</pre>
<p>Here is the updated source: <a href='http://compprog.files.wordpress.com/2008/01/dijkstra.c' title='dijkstraWithPath.c'>dijkstraWithPath.c</a>.</p>
<p>Good luck.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/compprog.wordpress.com/36/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/compprog.wordpress.com/36/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/compprog.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/compprog.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/compprog.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/compprog.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/compprog.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/compprog.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/compprog.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/compprog.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/compprog.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/compprog.wordpress.com/36/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=compprog.wordpress.com&blog=1850193&post=36&subd=compprog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://compprog.wordpress.com/2007/12/01/one-source-shortest-path-dijkstras-algorithm/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/scvalex-128.jpg" medium="image">
			<media:title type="html">scvalex</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/dj1.png" medium="image">
			<media:title type="html">dj1.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/dj2.png" medium="image">
			<media:title type="html">dj2.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/dj3.png" medium="image">
			<media:title type="html">dj3_1.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/dj4.png" medium="image">
			<media:title type="html">dj4.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/dj5.png" medium="image">
			<media:title type="html">dj5.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/dj5.png" medium="image">
			<media:title type="html">dj5.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/12/dj5.png" medium="image">
			<media:title type="html">dj5.png</media:title>
		</media:content>
	</item>
		<item>
		<title>One Source Shortest Path: The Bellman-Ford Algorithm</title>
		<link>http://compprog.wordpress.com/2007/11/29/one-source-shortest-path-the-bellman-ford-algorithm/</link>
		<comments>http://compprog.wordpress.com/2007/11/29/one-source-shortest-path-the-bellman-ford-algorithm/#comments</comments>
		<pubDate>Thu, 29 Nov 2007 14:50:45 +0000</pubDate>
		<dc:creator>scvalex</dc:creator>
		
		<category><![CDATA[Algorithms]]></category>

		<category><![CDATA[Graphs]]></category>

		<category><![CDATA[algorithm]]></category>

		<category><![CDATA[bellman-ford]]></category>

		<category><![CDATA[C]]></category>

		<category><![CDATA[explanation]]></category>

		<category><![CDATA[graph]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[shortest path]]></category>

		<category><![CDATA[sourcecode]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://compprog.wordpress.com/2007/11/29/one-source-shortest-path-the-bellman-ford-algorithm/</guid>
		<description><![CDATA[In this article, I describe the Bellman-Ford algorithm for finding the one-source shortest paths in a graph, give an informal proof and provide the source code in C for a simple implementation.
To understand this you should know what a graph is, and how to store one in memory. If in doubt check this and this.
Another [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this article, I describe the Bellman-Ford algorithm for finding the one-source shortest paths in a graph, give an informal proof and provide the source code in C for a simple implementation.</p>
<p>To understand this you should know what a graph is, and how to store one in memory. If in doubt check <a href="http://compprog.wordpress.com/2007/11/09/minimal-spanning-trees-prims-algorithm/">this</a> and <a href="http://en.wikipedia.org/wiki/Graph_(mathematics)">this</a>.</p>
<p>Another solution to this problem is <a href="http://compprog.wordpress.com/2007/12/01/one-source-shortest-path-dijkstras-algorithm/">Dijkstra&#8217;s algorithm</a>.</p>
<h4>The Problem</h4>
<p>Given the following graph, calculate the length of the shortest path from <strong>node 1</strong> to <strong>node 2</strong>.<br />
<img src='http://compprog.files.wordpress.com/2007/11/bf1.png' alt='bf1.png' /></p>
<p>It&#8217;s obvious that there&#8217;s a direct route of length <em>6</em>, but take a look at path: <em>1 -&gt; 4 -&gt; 3 -&gt; 2</em>. The length of the path is <em>7 - 3 - 2 = 2</em>, which is less than <em>6</em>. BTW, you don&#8217;t need negative edge weights to get such a situation, but they do clarify the problem.</p>
<p>This also suggests a property of shortest path algorithms: to find the shortest path form <em>x</em> to <em>y</em>, you need to know, beforehand, the shortest paths to <em>y</em>&#8217;s neighbours. For this, you need to know the paths to <em>y</em>&#8217;s neighbours&#8217; neighbours&#8230; In the end, you must calculate the shortest path to the <a href="http://en.wikipedia.org/wiki/Connected_component_(graph_theory)">connected component</a> of the graph in which <em>x</em> and <em>y</em> are found.</p>
<p>That said, you usually calculate <strong>the shortest path to all nodes</strong> and then pick the ones you&#8217;re intrested in.</p>
<h4>The Algorithm</h4>
<p>The <a href="http://en.wikipedia.org/wiki/Bellman-ford">Bellman-Ford</a> algorithm is one of the classic solutions to this problem. It calculates the shortest path to all nodes in the graph from a single source.</p>
<p>The basic idea is simple:<br />
Start by considering that the shortest path to all nodes, less the source, is infinity. Mark the length of the path to the source as <em>0</em>:<br />
<img src='http://compprog.files.wordpress.com/2007/11/bf2.png' alt='bf2.png' /></p>
<p>Take every edge and try to <em>relax</em> it:<br />
<img src='http://compprog.files.wordpress.com/2007/11/bf3.png' alt='bf3.png' /></p>
<p><strong>Relaxing</strong> an edge means checking to see if the path to the node the edge is pointing to can&#8217;t be shortened, and if so, doing it. In the above graph, by checking the <strong>edge 1 -&gt; 2</strong> of length <em>6</em>, you find that the length of the shortest path to <strong>node 1</strong> plus the length of the <strong>edge 1 -&gt; 2</strong> is less then infinity. So, you replace infinity in <strong>node 2</strong> with <em>6</em>. The same can be said for edge <em>1 -&gt; 4</em> of length <em>7</em>. It&#8217;s also worth noting that, practically, you can&#8217;t relax the edges whose start has the shortest path of length infinity to it.</p>
<p>Now, you apply the previous step <em>n - 1</em> times, where n is the number of nodes in the graph. In this example, you have to apply it <em>4</em> times (that&#8217;s <em>3</em> more times).<br />
<img src='http://compprog.files.wordpress.com/2007/11/bf4.png' alt='bf4.png' /></p>
<p><img src='http://compprog.files.wordpress.com/2007/11/bf5.png' alt='bf5.png' /></p>
<p><img src='http://compprog.files.wordpress.com/2007/11/bf6.png' alt='bf6.png' /></p>
<p>That&#8217;s it, here&#8217;s the algorithm in a condensed form:</p>
<pre name="code" class="cpp">

void bellman_ford(int s) {
        int i, j;

        for (i = 0; i &lt; n; ++i)
                d[i] = INFINITY;

        d[s] = 0;

        for (i = 0; i &lt; n - 1; ++i)
                for (j = 0; j &lt; e; ++j)
                        if (d[edges[j].u] + edges[j].w &lt; d[edges[j].v])
                                d[edges[j].v] = d[edges[j].u] + edges[j].w;
}
</pre>
<p>Here, <strong>d[i]</strong> is the shortest path to node <strong>i</strong>, <strong>e</strong> is the number of edges and <strong>edges[i]</strong> is the <strong>i</strong>-th edge.</p>
<p>It may not be obvious why this works, but take a look at what is certain after each step. After the first step, any path made up of at most <em>2</em> nodes will be optimal. After the step <em>2</em>, any path made up of at most <em>3</em> nodes will be optimal&#8230; After the <em>(n - 1)</em>-th step, any path made up of at most <em>n</em> nodes will be optimal.</p>
<h4>The Programme</h4>
<p>The following programme just puts the <strong>bellman_ford</strong> function into context. It runs in <strong>O(VE)</strong> time, so for the example graph it will do something on the lines of <strong>5 * 9 = 45</strong> relaxations. Keep in mind that this algorithm works quite well on graphs with few edges, but is very slow for dense graphs (graphs with almost <em>n<sup>2</sup></em> edges). For graphs with lots of edges, you&#8217;re better off with <a href="http://compprog.wordpress.com/2007/12/01/one-source-shortest-path-dijkstras-algorithm/">Dijkstra&#8217;s algorithm</a>.</p>
<p>Here&#8217;s the source code in C (<a href='http://compprog.files.wordpress.com/2007/11/bellmanford.c' title='bellmanford.c'>bellmanford.c</a>):</p>
<pre name="code" class="cpp">

#include &lt;stdio.h&gt;

typedef struct {
	int u, v, w;
} Edge;

int n; /* the number of nodes */
int e; /* the number of edges */
Edge edges[1024]; /* large enough for n &lt;= 2^5=32 */
int d[32]; /* d[i] is the minimum distance from node s to node i */

#define INFINITY 10000

void printDist() {
	int i;

	printf(&quot;Distances:\n&quot;);

	for (i = 0; i &lt; n; ++i)
		printf(&quot;to %d\t&quot;, i + 1);
	printf(&quot;\n&quot;);

	for (i = 0; i &lt; n; ++i)
		printf(&quot;%d\t&quot;, d[i]);

	printf(&quot;\n\n&quot;);
}

void bellman_ford(int s) {
	int i, j;

	for (i = 0; i &lt; n; ++i)
		d[i] = INFINITY;

	d[s] = 0;

	for (i = 0; i &lt; n - 1; ++i)
		for (j = 0; j &lt; e; ++j)
			if (d[edges[j].u] + edges[j].w &lt; d[edges[j].v])
				d[edges[j].v] = d[edges[j].u] + edges[j].w;
}

int main(int argc, char *argv[]) {
	int i, j;
	int w;

	FILE *fin = fopen(&quot;dist.txt&quot;, &quot;r&quot;);
	fscanf(fin, &quot;%d&quot;, &amp;n);
	e = 0;

	for (i = 0; i &lt; n; ++i)
		for (j = 0; j &lt; n; ++j) {
			fscanf(fin, &quot;%d&quot;, &amp;w);
			if (w != 0) {
				edges[e].u = i;
				edges[e].v = j;
				edges[e].w = w;
				++e;
			}
		}
	fclose(fin);

	/* printDist(); */

	bellman_ford(0);

	printDist();

	return 0;
}
</pre>
<p>And here&#8217;s the input file used in the example (<a href='http://compprog.files.wordpress.com/2007/11/dist1.txt' title='dist.txt'>dist.txt</a>):<br />
<code>5<br />
 0  6  0  7  0<br />
 0  0  5  8 -4<br />
 0 -2  0  0  0<br />
 0  0 -3  9  0<br />
 2  0  7  0  0</code></p>
<p>That&#8217;s an <a href="http://en.wikipedia.org/wiki/Adjacency_matrix">adjacency matrix</a>.</p>
<p>That&#8217;s it. Have fun. Always open to comments.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/compprog.wordpress.com/61/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/compprog.wordpress.com/61/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/compprog.wordpress.com/61/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/compprog.wordpress.com/61/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/compprog.wordpress.com/61/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/compprog.wordpress.com/61/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/compprog.wordpress.com/61/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/compprog.wordpress.com/61/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/compprog.wordpress.com/61/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/compprog.wordpress.com/61/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/compprog.wordpress.com/61/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/compprog.wordpress.com/61/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=compprog.wordpress.com&blog=1850193&post=61&subd=compprog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://compprog.wordpress.com/2007/11/29/one-source-shortest-path-the-bellman-ford-algorithm/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/scvalex-128.jpg" medium="image">
			<media:title type="html">scvalex</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/bf1.png" medium="image">
			<media:title type="html">bf1.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/bf2.png" medium="image">
			<media:title type="html">bf2.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/bf3.png" medium="image">
			<media:title type="html">bf3.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/bf4.png" medium="image">
			<media:title type="html">bf4.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/bf5.png" medium="image">
			<media:title type="html">bf5.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/bf6.png" medium="image">
			<media:title type="html">bf6.png</media:title>
		</media:content>
	</item>
		<item>
		<title>The 0-1 Knapsack Problem</title>
		<link>http://compprog.wordpress.com/2007/11/20/the-0-1-knapsack-problem/</link>
		<comments>http://compprog.wordpress.com/2007/11/20/the-0-1-knapsack-problem/#comments</comments>
		<pubDate>Tue, 20 Nov 2007 17:14:33 +0000</pubDate>
		<dc:creator>scvalex</dc:creator>
		
		<category><![CDATA[Algorithms]]></category>

		<category><![CDATA[Dynamic Programming]]></category>

		<category><![CDATA[Problems]]></category>

		<category><![CDATA[0-1 knapsack problem]]></category>

		<category><![CDATA[algorithm]]></category>

		<category><![CDATA[discrete]]></category>

		<category><![CDATA[discrete knapsack problem]]></category>

		<category><![CDATA[explanation]]></category>

		<category><![CDATA[knapsack]]></category>

		<category><![CDATA[knapsack problem]]></category>

		<category><![CDATA[problem]]></category>

		<category><![CDATA[sourcecode]]></category>

		<guid isPermaLink="false">http://compprog.wordpress.com/2007/11/20/the-0-1-knapsack-problem/</guid>
		<description><![CDATA[The 0-1 Knapsack Problem (AKA The Discrete Knapsack Problem) is a famous problem solvable by dynamic-programming. In this article, I describe the problem, the most common algorithm used to solve it and then provide a sample implementation in C.
If you&#8217;ve never heard of the Knapsack Problems before, it will help to read this previous post.
The [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>The 0-1 Knapsack Problem (AKA The Discrete Knapsack Problem) is a famous problem solvable by dynamic-programming. In this article, I describe the problem, the most common algorithm used to solve it and then provide a sample implementation in C.</p>
<p>If you&#8217;ve never heard of the <a href="http://en.wikipedia.org/wiki/Knapsack_problem">Knapsack Problems</a> before, it will help to read this previous <a href="http://compprog.wordpress.com/2007/11/20/the-fractional-knapsack-problem/">post</a>.</p>
<h4>The Problem</h4>
<p>The Discrete (0-1) Knapsack Problem usually sounds like this:</p>
<blockquote><p>Little Red Riding Hood wants to bring grandma a basket of goodies. She has an unlimited supply of <em>n</em> types of sweets each weighting <em>c[i]</em> and having the nutritional value of <em>v[i]</em>. Her basket can hold at most <em>W</em> kilograms of sweets.</p>
<p>Given <em>n</em>, <em>c</em>, <em>v</em> and <em>W</em>, figure out which sweets and how many to take so that the nutritional value in maximal.</p></blockquote>
<p>So, for this input:<br />
<code>n = 3<br />
c = {8, 6, 4}<br />
v = {16, 10, 7}<br />
W = 10<br />
</code></p>
<p>LRRH should take one of <em>3</em> and one of <em>2</em>, amassing <em>17</em> nutritional points.</p>
<p>You’re usually dealling with a knapsack problem when you’re give the cost and the benefits of certain objects and asked to obtain the maximum benefit so that the sum of the costs is smaller than a given value. <strong>You have got the Discrete Knapsack Problem</strong> when you can only take <strong>the whole object or none at all</strong> and you have an <strong>unlimited supply of objects</strong>.</p>
<h4>The Algorithm</h4>
<p>This is a <a href="http://en.wikipedia.org/wiki/Dynamic_programming">dynamic-programming</a> algorithm.</p>
<p>The idea is to first calculate the maximum benefit for weight <em>x</em> and only after that to calculate the maximum benefit for <em>x+1</em>. So, on the whole, you first calculate the maximum benefit for <em>1</em>, then for <em>2</em>, then for <em>3</em>, &#8230;, then for <em>W-1</em> and, finally, for <em>W</em>. I store the maximum benefits in an array named <em>a</em>.</p>
<p>Start with <em>a[0] = 0</em>. Then for every <em>a</em> between <em>1 &#8230; W</em> use the formula:<br />
<code>a[i] = max{v<sub>j</sub> + a(i − c<sub>j</sub>) | c<sub>j</sub> ≤ i }</code></p>
<p>The basic idea is that to reach weight <em>x</em>, you have to add an object of weight <em>w</em> to a previous maximum benefit. More specifically, you have to add <em>w</em> to <em>x - w</em>. Now, there will probably be several ways to reach weight <em>x</em>, so you have to choose the one that maximises the benefit. That&#8217;s what the max is for.</p>
<p>Basically, the formula says: &#8220;To calculate the benefit of weight <em>x</em>, take every object (value: <em>v</em>; weight: <em>w</em>) and see if the benefit for <em>x - w</em> plus <em>v</em> is greater than the current benefit for <em>x</em>. If so, change it.&#8221;</p>
<p>So, for the example, the programme would output (and do) this:<br />
<code>Weight 0; Benefit: 0; Can't reach this exact weight.<br />
Weight 1; Benefit: 0; Can&#8217;t reach this exact weight.<br />
Weight 2; Benefit: 0; Can&#8217;t reach this exact weight.<br />
Weight 3; Benefit: 0; Can&#8217;t reach this exact weight.<br />
Weight 4; Benefit: 7; To reach this weight I added object 3 (7$ 4Kg) to weight 0.<br />
Weight 5; Benefit: 7; To reach this weight I added object 3 (7$ 4Kg) to weight 1.<br />
Weight 6; Benefit: 10; To reach this weight I added object 2 (10$ 6Kg) to weight 0.<br />
Weight 7; Benefit: 10; To reach this weight I added object 2 (10$ 6Kg) to weight 1.<br />
Weight 8; Benefit: 16; To reach this weight I added object 1 (16$ 8Kg) to weight 0.<br />
Weight 9; Benefit: 16; To reach this weight I added object 1 (16$ 8Kg) to weight 1.<br />
Weight 10; Benefit: 17; To reach this weight I added object 2 (10$ 6Kg) to weight 4.<br />
</code></p>
<h4>The Programme</h4>
<p>This programme runs in <a href="http://en.wikipedia.org/wiki/Pseudo-polynomial_time">pseudo-plynominal time</a> <strong>O(n * W)</strong>. i.e. Slow as hell for large very values of <em>W</em>. Also because it holds to arrays of at least length <em>W</em>, it&#8217;s also horribly memory inefficient. Unfortunately, there&#8217;s not much you can do.</p>
<p>Here&#8217;s the code in C (<a href='http://compprog.files.wordpress.com/2007/11/knapsack10.c' title='knapsack10.c'>knapsack10.c</a>):</p>
<pre name="code" class="cpp">

#include &lt;stdio.h&gt;

#define MAXWEIGHT 100

int n = 3; /* The number of objects */
int c[10] = {8, 6, 4}; /* c[i] is the *COST* of the ith object; i.e. what
				YOU PAY to take the object */
int v[10] = {16, 10, 7}; /* v[i] is the *VALUE* of the ith object; i.e.
				what YOU GET for taking the object */
int W = 10; /* The maximum weight you can take */ 

void fill_sack() {
	int a[MAXWEIGHT]; /* a[i] holds the maximum value that can be obtained
				using at most i weight */
	int last_added[MAXWEIGHT]; /* I use this to calculate which object were
					added */
	int i, j;
	int aux;

	for (i = 0; i &lt;= W; ++i) {
		a[i] = 0;
		last_added[i] = -1;
	}

	a[0] = 0;
	for (i = 1; i &lt;= W; ++i)
		for (j = 0; j &lt; n; ++j)
			if ((c[j] &lt;= i) &amp;&amp; (a[i] &lt; a[i - c[j]] + v[j])) {
				a[i] = a[i - c[j]] + v[j];
				last_added[i] = j;
			}

	for (i = 0; i &lt;= W; ++i)
		if (last_added[i] != -1)
			printf(&quot;Weight %d; Benefit: %d; To reach this weight I added object %d (%d$ %dKg) to weight %d.\n&quot;, i, a[i], last_added[i] + 1, v[last_added[i]], c[last_added[i]], i - c[last_added[i]]);
		else
			printf(&quot;Weight %d; Benefit: 0; Can&#039;t reach this exact weight.\n&quot;, i);

	printf(&quot;---\n&quot;);

	aux = W;
	while ((aux &gt; 0) &amp;&amp; (last_added[aux] != -1)) {
		printf(&quot;Added object %d (%d$ %dKg). Space left: %d\n&quot;, last_added[aux] + 1, v[last_added[aux]], c[last_added[aux]], aux - c[last_added[aux]]);
		aux -= c[last_added[aux]];
	}

	printf(&quot;Total value added: %d$\n&quot;, a[W]);
}

int main(int argc, char *argv[]) {
	fill_sack();

	return 0;
}
</pre>
<p>That&#8217;s it. Good luck. Always open to comments.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/compprog.wordpress.com/59/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/compprog.wordpress.com/59/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/compprog.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/compprog.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/compprog.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/compprog.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/compprog.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/compprog.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/compprog.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/compprog.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/compprog.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/compprog.wordpress.com/59/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=compprog.wordpress.com&blog=1850193&post=59&subd=compprog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://compprog.wordpress.com/2007/11/20/the-0-1-knapsack-problem/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/scvalex-128.jpg" medium="image">
			<media:title type="html">scvalex</media:title>
		</media:content>
	</item>
		<item>
		<title>The Fractional Knapsack Problem</title>
		<link>http://compprog.wordpress.com/2007/11/20/the-fractional-knapsack-problem/</link>
		<comments>http://compprog.wordpress.com/2007/11/20/the-fractional-knapsack-problem/#comments</comments>
		<pubDate>Tue, 20 Nov 2007 13:35:38 +0000</pubDate>
		<dc:creator>scvalex</dc:creator>
		
		<category><![CDATA[Algorithms]]></category>

		<category><![CDATA[Greedy]]></category>

		<category><![CDATA[Problems]]></category>

		<category><![CDATA[algorithm]]></category>

		<category><![CDATA[calssic problem]]></category>

		<category><![CDATA[explanation]]></category>

		<category><![CDATA[fractional knapsack problem]]></category>

		<category><![CDATA[greed algorithm]]></category>

		<category><![CDATA[knapsack]]></category>

		<category><![CDATA[knapsack problem]]></category>

		<category><![CDATA[problem]]></category>

		<category><![CDATA[sourcecode]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://compprog.wordpress.com/2007/11/20/the-fractional-knapsack-problem/</guid>
		<description><![CDATA[In this article, I describe the greedy algorithm for solving the Fractional Knapsack Problem and give an implementation in C.
The Problem
The Fractional Knapsack Problem usually sounds like this:
Ted Thief has just broken into the Fort Knox! He sees himself in a room with n piles of gold dust. Because the each pile has a different [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this article, I describe the greedy algorithm for solving the Fractional Knapsack Problem and give an implementation in C.</p>
<h4>The Problem</h4>
<p>The <a href="http://en.wikipedia.org/wiki/Knapsack_problem">Fractional Knapsack Problem</a> usually sounds like this:</p>
<blockquote><p>Ted Thief has just broken into the Fort Knox! He sees himself in a room with <em>n</em> piles of gold dust. Because the each pile has a different purity, each pile also has a different value (<em>v[i]</em>) and a different weight (<em>c[i]</em>). Ted has a knapsack that can only hold <em>W</em> kilograms.</p>
<p>Given <em>n</em>, <em>v</em>, <em>c</em> and <em>W</em>, calculate which piles Ted should completely put into his knapsack and which he should put only a fraction of.</p></blockquote>
<p>So, for this input:<br />
<code>n = 5<br />
c = {12, 1, 2, 1, 4}<br />
v = {4, 2, 2, 1, 10}<br />
W = 15<br />
</code></p>
<p>Ted should take piles <em>2</em>, <em>3</em>, <em>4</em> and <em>5</em> completely and about <em>58%</em> of pile <em>1</em>.</p>
<p>You&#8217;re usually dealling with a knapsack problem when you&#8217;re give the cost and the benefits of certain objects and asked to obtain the maximum benefit so that the sum of the costs is smaller than a given value. You&#8217;ve got the <strong>fractional</strong> knapsack problem when you can take fractions (as opposed to all or nothing) of the objects.</p>
<h4>The Algorithm</h4>
<p>This is a standard <a href="http://en.wikipedia.org/wiki/Greedy_algorithm">greedy</a> algorithm. In fact, it&#8217;s one of the classic examples.</p>
<p>The idea is to calculate for each object the ratio of <em>value/cost</em>, and sort them according to this ratio. Then you take the objects with the highest ratios and add them until you can&#8217;t add the next object as whole. Finally add as much as you can of the next object.</p>
<p>So, for our example:<br />
<code>v = {4, 2, 2, 1, 10}<br />
c = {12, 1, 2, 1, 4}<br />
r = {1/3, 2, 1, 1, 5/2}<br />
</code></p>
<p>From this it&#8217;s obvious that you should add the objects: 5, 2, 3, 4 and then as much as possible of 1.<br />
The output of my programme is this:<br />
<code>Added object 5 (10$, 4Kg) completly in the bag. Space left: 11.<br />
Added object 2 (2$, 1Kg) completly in the bag. Space left: 10.<br />
Added object 3 (2$, 2Kg) completly in the bag. Space left: 8.<br />
Added object 4 (1$, 1Kg) completly in the bag. Space left: 7.<br />
Added 58% (4$, 12Kg) of object 1 in the bag.<br />
Filled the bag with objects worth 15.48$.</code></p>
<h4>The Programme</h4>
<p>Now, you could implement the algorithm as stated, but for practical reasons you may wish to trade speed for simplicity. That&#8217;s what I&#8217;ve done here: instead of sorting the objects, I simply go through them every time searching for the best ratio. This modification turns an <strong>O(n*lg(n))</strong> algorithm into an <strong>O(n<sup>2</sup>)</strong> one. For small values of <strong>n</strong>, this doesn&#8217;t matter and <strong>n</strong> is usually small.</p>
<p>Here&#8217;s the code in C (<a href='http://compprog.files.wordpress.com/2007/11/fractional_knapsack.c' title='fractional_knapsack.c'>fractional_knapsack.c</a>):</p>
<pre name="code" class="cpp">

#include &lt;stdio.h&gt;

int n = 5; /* The number of objects */
int c[10] = {12, 1, 2, 1, 4}; /* c[i] is the *COST* of the ith object; i.e. what
				YOU PAY to take the object */
int v[10] = {4, 2, 2, 1, 10}; /* v[i] is the *VALUE* of the ith object; i.e.
				what YOU GET for taking the object */
int W = 15; /* The maximum weight you can take */

void simple_fill() {
	int cur_w;
	float tot_v;
	int i, maxi;
	int used[10];

	for (i = 0; i &lt; n; ++i)
		used[i] = 0; /* I have not used the ith object yet */

	cur_w = W;
	while (cur_w &gt; 0) { /* while there&#039;s still room*/
		/* Find the best object */
		maxi = -1;
		for (i = 0; i &lt; n; ++i)
			if ((used[i] == 0) &amp;&amp;
				((maxi == -1) || ((float)v[i]/c[i] &gt; (float)v[maxi]/c[maxi])))
				maxi = i;

		used[maxi] = 1; /* mark the maxi-th object as used */
		cur_w -= c[maxi]; /* with the object in the bag, I can carry less */
		tot_v += v[maxi];
		if (cur_w &gt;= 0)
			printf(&quot;Added object %d (%d$, %dKg) completly in the bag. Space left: %d.\n&quot;, maxi + 1, v[maxi], c[maxi], cur_w);
		else {
			printf(&quot;Added %d%% (%d$, %dKg) of object %d in the bag.\n&quot;, (int)((1 + (float)cur_w/c[maxi]) * 100), v[maxi], c[maxi], maxi + 1);
			tot_v -= v[maxi];
			tot_v += (1 + (float)cur_w/c[maxi]) * v[maxi];
		}
	}

	printf(&quot;Filled the bag with objects worth %.2f$.\n&quot;, tot_v);
}

int main(int argc, char *argv[]) {
	simple_fill();

	return 0;
}
</pre>
<p>That&#8217;s it. Good luck.</p>
<p>Always open to comments.</p>
<p>Update: The next article in this series is <a href="http://compprog.wordpress.com/2007/11/20/the-0-1-knapsack-problem/">The 0-1 Knapsack Problem</a>.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/compprog.wordpress.com/55/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/compprog.wordpress.com/55/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/compprog.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/compprog.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/compprog.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/compprog.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/compprog.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/compprog.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/compprog.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/compprog.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/compprog.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/compprog.wordpress.com/55/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=compprog.wordpress.com&blog=1850193&post=55&subd=compprog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://compprog.wordpress.com/2007/11/20/the-fractional-knapsack-problem/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/scvalex-128.jpg" medium="image">
			<media:title type="html">scvalex</media:title>
		</media:content>
	</item>
		<item>
		<title>All Sources Shortest Path: The Floyd-Warshall Algorithm</title>
		<link>http://compprog.wordpress.com/2007/11/15/all-sources-shortest-path-the-floyd-warshall-algorithm/</link>
		<comments>http://compprog.wordpress.com/2007/11/15/all-sources-shortest-path-the-floyd-warshall-algorithm/#comments</comments>
		<pubDate>Thu, 15 Nov 2007 16:14:03 +0000</pubDate>
		<dc:creator>scvalex</dc:creator>
		
		<category><![CDATA[Algorithms]]></category>

		<category><![CDATA[Graphs]]></category>

		<category><![CDATA[algorithm]]></category>

		<category><![CDATA[C]]></category>

		<category><![CDATA[explanation]]></category>

		<category><![CDATA[floyd-warshall]]></category>

		<category><![CDATA[graph]]></category>

		<category><![CDATA[shortest path]]></category>

		<category><![CDATA[sourcecode]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://compprog.wordpress.com/2007/11/15/all-sources-shortest-path-the-floyd-warshall-algorithm/</guid>
		<description><![CDATA[In this article I describe the Floyd-Warshall algorithm for finding the shortest path between all nodes in a graph. I give an informal proof and provide an implementation in C.
Shortest paths
The shortest path between two nodes of a graph is a sequence of connected nodes so that the sum of the edges that inter-connect them [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this article I describe the Floyd-Warshall algorithm for finding the shortest path between all nodes in a graph. I give an informal proof and provide an implementation in C.</p>
<h4>Shortest paths</h4>
<p>The <strong>shortest path</strong> between two nodes of a graph is a sequence of connected nodes so that the sum of the edges that inter-connect them is minimal.</p>
<p>Take this graph,<br />
<img src='http://compprog.files.wordpress.com/2007/11/p2.png' alt='p2.png' /></p>
<p>There are several paths between <em>A</em> and <em>E</em>:<br />
<code><strong>Path 1</strong>:    A -&gt; B -&gt; E             20<br />
<strong>Path 2</strong>:    A -&gt; D -&gt; E             25<br />
<strong>Path 3</strong>:    A -&gt; B -&gt; D -&gt; E        35<br />
<strong>Path 4</strong>:    A -&gt; D -&gt; B -&gt; E        20<br />
</code></p>
<p>There are several things to notice here:</p>
<ol>
<li> There can be more then one route between two nodes</li>
<li> The number of nodes in the route isn&#8217;t important (<strong>Path 4</strong> has <em>4</em> nodes but is shorter than <strong>Path 2</strong>, which has <em>3</em> nodes)</li>
<li> There can be more than one path of minimal length</li>
</ol>
<p>Something else that should be obvious from the graph is that any path worth considering is <a href="http://en.wikipedia.org/wiki/Path_(graph_theory)">simple</a>. That is, you only go through each node <strong>once</strong>.</p>
<p>Unfortunately, this is not always the case. The problem appears when you allow negative weight edges. This isn&#8217;t by itself bad. But if <strong>a loop of negative weight appears</strong>, then <strong>there is no shortest path</strong>. Look at this example:<br />
<img src='http://compprog.files.wordpress.com/2007/11/fw1.png' alt='A graph containing a negative weight loop' /></p>
<p>Look at the path <em>B -&gt; E -&gt; D -&gt; B</em>. This is a loop, because the starting node is the also the end. What&#8217;s the cost? It&#8217;s <em>10 - 20 + 5 = -5</em>. This means that adding this loop to a path once lowers the cost of the path by <em>5</em>. Adding it twice would lower the cost by <em>2 * 5 = 10</em>. So, whatever shortest path you may have come up with, you can make it smaller by going through the loop one more time. BTW there&#8217;s no problem with a negative cost path.</p>
<h4>The Floyd-Warshall Algorithm</h4>
<p>This algorithm calculates the length of the shortest path between all nodes of a graph in O(V<sup>3</sup>) time. Note that it doesn&#8217;t actually find the paths, only their lengths.</p>
<p>Let&#8217;s say you have the <a href="http://en.wikipedia.org/wiki/Adjacency_matrix">adjacency matrix</a> of a graph. Assuming no loop of negative values, at this point you have the minimum distance between any two nodes which are connected by an edge.<br />
<code>    A   B   C   D   E<br />
   A   0  10   0   5   0<br />
   B  10   0   5   5  10<br />
   C   0   5   0   0   0<br />
   D   5   5   0   0  20<br />
   E   0  10   0  20   0</code></p>
<p>The graph is the one shown above (the first one).</p>
<p>The idea is to try to interspace <em>A</em> between any two nodes in hopes of finding a shorter path.<br />
<code>    A   B   C   D   E<br />
   A   0  10   0   5   0<br />
   B  10   0   5   5  10<br />
   C   0   5   0   0   0<br />
   D   5   5   0   0  20<br />
   E   0  10   0  20   0</code></p>
<p>Then try to interspace <em>B</em> between any two nodes:<br />
<code>    A   B   C   D   E<br />
   A   0  10  <strong>15</strong>   5  <strong>20</strong><br />
   B  10   0   5   5  10<br />
   C  <strong>15</strong>   5   0  <strong>10</strong>  <strong>15</strong><br />
   D   5   5  <strong>10</strong>   0  <strong>15</strong><br />
   E  <strong>20</strong>  10  <strong>15</strong>  <strong>15</strong>   0</code></p>
<p>Do the same for <em>C</em>:<br />
<code>    A   B   C   D   E<br />
   A   0  10  15   5  20<br />
   B  10   0   5   5  10<br />
   C  15   5   0  10  15<br />
   D   5   5  10   0  15<br />
   E  20  10  15  15   0</code></p>
<p>Do the same for <em>D</em>:<br />
<code>    A   B   C   D   E<br />
   A   0  10  15   5  20<br />
   B  10   0   5   5  10<br />
   C  15   5   0  10  15<br />
   D   5   5  10   0  15<br />
   E  20  10  15  15   0</code></p>
<p>And for <em>E</em>:<br />
<code>    A   B   C   D   E<br />
   A   0  10  15   5  20<br />
   B  10   0   5   5  10<br />
   C  15   5   0  10  15<br />
   D   5   5  10   0  15<br />
   E  20  10  15  15   0</code></p>
<p>This is the actual algorithm:<br />
<code>
<pre>
# dist(i,j) is "best" distance so far from vertex i to vertex j 

# Start with all single edge paths.
 For i = 1 to n do
     For j = 1 to n do
         dist(i,j) = weight(i,j) 

 For k = 1 to n do # k is the `intermediate' vertex
     For i = 1 to n do
         For j = 1 to n do
             if (dist(i,k) + dist(k,j) &lt; dist(i,j)) then # shorter path?
                 dist(i,j) = dist(i,k) + dist(k,j)
</pre>
<p></code></p>
<h4>The Programme</h4>
<p>Here&#8217;s the code in C(<a href='http://compprog.files.wordpress.com/2007/11/floyd_warshall.c' title='floyd_warshall.c'>floyd_warshall.c</a>):</p>
<pre name="code" class="cpp">

#include &lt;stdio.h&gt;

int n; /* Then number of nodes */
int dist[16][16]; /* dist[i][j] is the length of the edge between i and j if
			it exists, or 0 if it does not */

void printDist() {
	int i, j;
	printf(&quot;    &quot;);
	for (i = 0; i &lt; n; ++i)
		printf(&quot;%4c&quot;, &#039;A&#039; + i);
	printf(&quot;\n&quot;);
	for (i = 0; i &lt; n; ++i) {
		printf(&quot;%4c&quot;, &#039;A&#039; + i);
		for (j = 0; j &lt; n; ++j)
			printf(&quot;%4d&quot;, dist[i][j]);
		printf(&quot;\n&quot;);
	}
	printf(&quot;\n&quot;);
}

/*
	floyd_warshall()

	after calling this function dist[i][j] will the the minimum distance
	between i and j if it exists (i.e. if there&#039;s a path between i and j)
	or 0, otherwise
*/
void floyd_warshall() {
	int i, j, k;
	for (k = 0; k &lt; n; ++k) {
		printDist();
		for (i = 0; i &lt; n; ++i)
			for (j = 0; j &lt; n; ++j)
				/* If i and j are different nodes and if
					the paths between i and k and between
					k and j exist, do */
				if ((dist[i][k] * dist[k][j] != 0) &amp;&amp; (i != j))
					/* See if you can&#039;t get a shorter path
						between i and j by interspacing
						k somewhere along the current
						path */
					if ((dist[i][k] + dist[k][j] &lt; dist[i][j]) ||
						(dist[i][j] == 0))
						dist[i][j] = dist[i][k] + dist[k][j];
	}
	printDist();
}

int main(int argc, char *argv[]) {
	FILE *fin = fopen(&quot;dist.txt&quot;, &quot;r&quot;);
	fscanf(fin, &quot;%d&quot;, &amp;n);
	int i, j;
	for (i = 0; i &lt; n; ++i)
		for (j = 0; j &lt; n; ++j)
			fscanf(fin, &quot;%d&quot;, &amp;dist[i][j]);
	fclose(fin);

	floyd_warshall();

	return 0;
}
</pre>
<p>Note that of the above programme, all the work is done by only five lines (30-48).</p>
<p>That&#8217;s it. Good luck. Always open to comments.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/compprog.wordpress.com/37/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/compprog.wordpress.com/37/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/compprog.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/compprog.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/compprog.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/compprog.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/compprog.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/compprog.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/compprog.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/compprog.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/compprog.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/compprog.wordpress.com/37/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=compprog.wordpress.com&blog=1850193&post=37&subd=compprog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://compprog.wordpress.com/2007/11/15/all-sources-shortest-path-the-floyd-warshall-algorithm/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/scvalex-128.jpg" medium="image">
			<media:title type="html">scvalex</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/p2.png" medium="image">
			<media:title type="html">p2.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/fw1.png" medium="image">
			<media:title type="html">A graph containing a negative weight loop</media:title>
		</media:content>
	</item>
		<item>
		<title>Minimum Spanning Trees: Prim&#8217;s Algorithm</title>
		<link>http://compprog.wordpress.com/2007/11/09/minimal-spanning-trees-prims-algorithm/</link>
		<comments>http://compprog.wordpress.com/2007/11/09/minimal-spanning-trees-prims-algorithm/#comments</comments>
		<pubDate>Fri, 09 Nov 2007 12:26:53 +0000</pubDate>
		<dc:creator>scvalex</dc:creator>
		
		<category><![CDATA[Algorithms]]></category>

		<category><![CDATA[Graphs]]></category>

		<category><![CDATA[algorithm]]></category>

		<category><![CDATA[C]]></category>

		<category><![CDATA[graph]]></category>

		<category><![CDATA[graph theory]]></category>

		<category><![CDATA[minimal spanning trees]]></category>

		<category><![CDATA[prim]]></category>

		<category><![CDATA[prim's algorithm]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[sourcecode]]></category>

		<category><![CDATA[tree]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://compprog.wordpress.com/2007/11/09/minimal-spanning-trees-prims-algorithm/</guid>
		<description><![CDATA[In this article I give an informal definition of a graph and of the minimum spanning tree. Afterwards I describe Prim&#8217;s algorithm and then follow its execution on an example. Finally, the code in C is provided.
Graphs
Wikipedia gives one of the common definitions of a graph:
In computer science, a graph is a kind of data [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this article I give an informal definition of a <strong>graph</strong> and of the <strong>minimum spanning tree</strong>. Afterwards I describe <strong>Prim&#8217;s algorithm</strong> and then follow its execution on an example. Finally, the code in C is provided.</p>
<h4>Graphs</h4>
<p><a href="http://en.wikipedia.org/wiki/Graph_(data_structure)">Wikipedia</a> gives one of the common definitions of a <strong>graph</strong>:</p>
<blockquote><p>In computer science, a graph is a kind of data structure, specifically an abstract data type (ADT), that consists of a set of nodes and a set of edges that establish relationships (connections) between the nodes. The graph ADT follows directly from the graph concept from mathematics.<br />
Informally, G=(V,E) consists of vertices, the elements of V, which are connected by edges, the elements of E. Formally, a graph, G, is defined as an ordered pair, G=(V,E), where V is a finite set and E is a set consisting of two element subsets of V.</p></blockquote>
<p>This is a <strong>graph</strong>:<br />
<img src='http://compprog.files.wordpress.com/2007/11/p1.png' alt='p1.png' /></p>
<p>It&#8217;s a set of nodes (A, B, C, D and E) and the edges (lines) that interconnect them.</p>
<p>An important thing to note about this graph is that the edges are bidirectional, i.e. if A is connected to B, then B is connected to A. This makes it an undirected graph.</p>
<p>A common extension is to attribute <strong>weights</strong> to the edges. This is what I&#8217;ve done with the previous graph:<br />
<img src='http://compprog.files.wordpress.com/2007/11/p2.png' alt='p2' /></p>
<h4>Minimum spanning trees</h4>
<p>Basically <a href="http://en.wikipedia.org/wiki/Minimum_spanning_tree">a minimum spanning tree</a> is a <strong>subset of the edges of the graph</strong>, so that <strong>there&#8217;s a path form any node to any other node</strong> and that <strong>the sum of the weights of the edges is minimum</strong>.</p>
<p>Here&#8217;s the minimum spanning tree of the example:<br />
<img src='http://compprog.files.wordpress.com/2007/11/g3.png' alt='g3.png' /></p>
<p>Look at the above image closely. It <strong>contains all of the initial nodes</strong> and some of the initial edges. Actually it contains <strong>exactly <em>n - 1</em> edges</strong>, where <em>n</em> is the number of nodes. It&#8217;s called a <a href="http://en.wikipedia.org/wiki/Tree_(graph_theory)">tree</a> because there are no cycles.</p>
<p>You can think of the graph as a map, with the nodes being cities, the edges passable terrain, and the weights the distance between the cities.</p>
<p>It&#8217;s worth mentioning that a graph can have several minimum spanning trees. Think of the above example, but replace all the weight with <em>1</em>. The resulting graph will have <em>6</em> minimum spanning trees.</p>
<p>Given a graph, find one of its minimum spanning trees.</p>
<h4>Prim&#8217;s Algorithm</h4>
<p>One of the classic algorithms for this problem is that found by Robert C. Prim. It&#8217;s a <strong>greedy</strong> style algorithm and it&#8217;s guaranteed to produce a correct result.</p>
<p>In the following discussion, let the distance from each node not in the tree to the tree be the edge of minimal weight between that node and some node in the tree. If there is no such edge, assume the distance is infinity (this shouldn&#8217;t happen).</p>
<p>The algorithm (greedily) builds the minimal spanning tree by iteratively adding nodes into a working tree:</p>
<ol>
<li> Start with a tree which contains only one node.</li>
<li> Identify a node (outside the tree) which is closest to the tree and add the minimum weight edge from that node to some node in the tree and incorporate the additional node as a part of the tree.</li>
<li> If there are less then <em>n - 1</em> edges in the tree, go to <strong>2</strong></li>
</ol>
<p>For the example graph, here&#8217;s how it would run:</p>
<p>Start with only node A in the tree.<br />
<img src='http://compprog.files.wordpress.com/2007/11/g4.png' alt='g4.png' /></p>
<p>Find the closest node to the tree, and add it.<br />
<img src='http://compprog.files.wordpress.com/2007/11/g5.png' alt='g5.png' /></p>
<p>Repeat until there are <em>n - 1</em> edges in the tree.<br />
<img src='http://compprog.files.wordpress.com/2007/11/g6.png' alt='g6.png' /></p>
<p><img src='http://compprog.files.wordpress.com/2007/11/g7.png' alt='g7.png' /></p>
<p><img src='http://compprog.files.wordpress.com/2007/11/g82.png' alt='g8.png' /></p>
<h4>The Programme</h4>
<p>The following programme just follows the algorithm. It runs in <strong>O(n<sup>2</sup>)</strong> time.</p>
<p>Here&#8217;s the code in C (<a href='http://compprog.files.wordpress.com/2007/11/prim.c' title='prim.c'>prim.c</a>):</p>
<pre name="code" class="cpp">

#include &lt;stdio.h&gt;

/*
	The input file (weight.txt) look something like this
		4
		0 0 0 21
		0 0 8 17
		0 8 0 16
		21 17 16 0

	The first line contains n, the number of nodes.
	Next is an nxn matrix containg the distances between the nodes
	NOTE: The distance between a node and itself should be 0
*/

int n; /* The number of nodes in the graph */

int weight[100][100]; /* weight[i][j] is the distance between node i and node j;
			if there is no path between i and j, weight[i][j] should
			be 0 */

char inTree[100]; /* inTree[i] is 1 if the node i is already in the minimum
			spanning tree; 0 otherwise*/

int d[100]; /* d[i] is the distance between node i and the minimum spanning
		tree; this is initially infinity (100000); if i is already in
		the tree, then d[i] is undefined;
		this is just a temporary variable. It&#039;s not necessary but speeds
		up execution considerably (by a factor of n) */

int whoTo[100]; /* whoTo[i] holds the index of the node i would have to be
			linked to in order to get a distance of d[i] */

/* updateDistances(int target)
	should be called immediately after target is added to the tree;
	updates d so that the values are correct (goes through target&#039;s
	neighbours making sure that the distances between them and the tree
	are indeed minimum)
*/
void updateDistances(int target) {
	int i;
	for (i = 0; i &lt; n; ++i)
		if ((weight[target][i] != 0) &amp;&amp; (d[i] &gt; weight[target][i])) {
			d[i] = weight[target][i];
			whoTo[i] = target;
		}
}

int main(int argc, char *argv[]) {
	FILE *f = fopen(&quot;dist.txt&quot;, &quot;r&quot;);
	fscanf(f, &quot;%d&quot;, &amp;n);
	int i, j;
	for (i = 0; i &lt; n; ++i)
		for (j = 0; j &lt; n; ++j)
			fscanf(f, &quot;%d&quot;, &amp;weight[i][j]);
	fclose(f);

	/* Initialise d with infinity */
	for (i = 0; i &lt; n; ++i)
		d[i] = 100000;

	/* Mark all nodes as NOT beeing in the minimum spanning tree */
	for (i = 0; i &lt; n; ++i)
		inTree[i] = 0;

	/* Add the first node to the tree */
	printf(&quot;Adding node %c\n&quot;, 0 + &#039;A&#039;);
	inTree[0] = 1;
	updateDistances(0);

	int total = 0;
	int treeSize;
	for (treeSize = 1; treeSize &lt; n; ++treeSize) {
		/* Find the node with the smallest distance to the tree */
		int min = -1;
		for (i = 0; i &lt; n; ++i)
			if (!inTree[i])
				if ((min == -1) || (d[min] &gt; d[i]))
					min = i;

		/* And add it */
		printf(&quot;Adding edge %c-%c\n&quot;, whoTo[min] + &#039;A&#039;, min + &#039;A&#039;);
		inTree[min] = 1;
		total += d[min];

		updateDistances(min);
	}

	printf(&quot;Total distance: %d\n&quot;, total);

	return 0;
}
</pre>
<p>And here&#8217;s a sample input file (<a href='http://compprog.files.wordpress.com/2007/11/dist.txt' title='dist.txt'>dist.txt</a>). It&#8217;s the example graph:<br />
<code>5<br />
0 10  0  5  0<br />
10 0  5  5 10<br />
0  5  0  0  0<br />
5  5  0  0 20<br />
0 10  0 20  0<br />
</code></p>
<p>The code&#8217;s commented and there shouldn&#8217;t be any problems.</p>
<p>Good luck. Always open to comments.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/compprog.wordpress.com/35/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/compprog.wordpress.com/35/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/compprog.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/compprog.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/compprog.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/compprog.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/compprog.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/compprog.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/compprog.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/compprog.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/compprog.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/compprog.wordpress.com/35/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=compprog.wordpress.com&blog=1850193&post=35&subd=compprog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://compprog.wordpress.com/2007/11/09/minimal-spanning-trees-prims-algorithm/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/scvalex-128.jpg" medium="image">
			<media:title type="html">scvalex</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/p1.png" medium="image">
			<media:title type="html">p1.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/p2.png" medium="image">
			<media:title type="html">p2</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/g3.png" medium="image">
			<media:title type="html">g3.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/g4.png" medium="image">
			<media:title type="html">g4.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/g5.png" medium="image">
			<media:title type="html">g5.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/g6.png" medium="image">
			<media:title type="html">g6.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/g7.png" medium="image">
			<media:title type="html">g7.png</media:title>
		</media:content>

		<media:content url="http://compprog.files.wordpress.com/2007/11/g82.png" medium="image">
			<media:title type="html">g8.png</media:title>
		</media:content>
	</item>
	</channel>
</rss>