1

I’m trying to solve the following problem:

There are N planets in our galaxy. You can travel in between different planets, but not every planet is joined to another one through a safe route. Each route has a given length in light years. Your task is to establish bases on a given set of planets T(where 0

The input consists of N(number of planets), R(number of safe routes between planets), R routes in the form triples A B L, where A and B represent the stellar IDs of the planets, and L represents the distance between them in light years, T(number of planets where bases need to be established), followed by T numbers which represent the IDs of the planets where bases need to be established.

You always start with the planet with ID: 0. There may or may not be needed to establish a base on planet 0.

I tried solving the exercise and managed to get a working solution but it is too slow. I used the Floyd Warshall algorithm to get minimum paths in between any two nodes(planets) in a graph. Next I find the closest planet that needs a base to 0, and calculate that path. Then, I add this planet to a list of “visited planets”, and remove it from the list of “target” planets. I repeat this process until the end, but now I try to find the closest planet from the target planets to ANY of my visited planets(since traveling between them is free, I don’t care where I’ve been last). Then, I add the distance, remove it from targets, add it to visited and keep going until I establish every base necessary.

This provides the correct output, but it is too slow.

Any ideas for improvement? Possibly some altered version of Dijkstra’s algorithm?

user2980055
  • 179
  • 1
  • 13

1 Answers1

0

I believe you want a minimal spanning tree of the graph consisting of the nodes from T and node 0 (starting point). The distances between nodes T are given by the shortest distances you calculated. The exact path between nodes in T may go through non-T points in N, but otherwise those points are irrelevant.

There are numerous algorithms for minimal spanning tree. I suggest Kruskal's algorithm as reasonably fast and reasonably easy to implement.

Edward Doolittle
  • 4,002
  • 2
  • 14
  • 27
  • But calculating the shortest distances is what causes problems. The Floyd Warshall algorithm has a complexity of O(N^3). – user2980055 Apr 07 '15 at 10:48
  • Good heavens, yes you should use Dijkstra for the distances. There are no negative weight edges, and you don't need distances between all the planets, just between the planets in T (and planet 0). Dijkstra runs in O(|E|+N log N) which is much better than O(N^3). – Edward Doolittle Apr 07 '15 at 16:38
  • So, if I'm getting this right, I need to find the distances using Dijkstra, then find a MST using those distances as weights for the "made up" edges in between nodes in T? – user2980055 Apr 07 '15 at 17:55
  • I think so. The problem is, you never said what needs to be optimized. – Edward Doolittle Apr 07 '15 at 19:13