An engineer working for a telecom company wants to design a cable network in a small nation. He can only bury the cables along main roads. Some paths are more expensive than others. It turns out that a previous employee of the company had already layed a network that is not efficient. In order to minimize costs, our engineer wants to optimize the network by removing some edges while keeping all points on the network connected.
For example, the network below can be optimized by removing the edge from to : This saves a cost of .
The engineer is given this larger network to optimize. What is the total cost saved?
Details and assumtions
The network is represented in the text file is represented in an adjacency matrix representation. Basically, the cost from node to node is represented in the matrix as (column , row ). if a path doesnt exist from to .
The example network in the picture above has the following adjacency matrix representation:
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Note that such a graph cannot have a cycle, since removing the bridge that completes the cycle still keeps the graph connected. Hence, it must be a tree.
The shortest tree that is a subset of a given graph such that it keeps all the vertices connected is called a Minimum Spanning Tree .
Given a graph, we could be using the Kruskal's greedy Algorithm to find the minimum spanning tree
Notice that this algorithm is easier (or maybe I am not smart enough) to implement with adjacency list rather than an adjacency matrix. So with Python , we start with implementing a
Graph
class:And a function to parse an adjacency matrix:
And finally the Kruskal's Algorithm:
The rest should be trivial: