0

There are [N] locations in a town labeled 1....N. You are provided a list of streets S (|S| = M) where a single street connects two locations in the town and has an associated distance. You also provided a list H of houses in the town and a list C, all the COVID-19 testing centers in the town. For each house find the shortest distance to the closest testing center. Solve the problem in O(M * log N) time.

I see that this is a graph problem and I can build an undirected graph from the list of streets because a street can be viewed as an edge where the edge-weight is the distance between the two locations.

Because the problem wanted to find the shortest distance to a testing center for all houses my thought was to run Dijkstra's algorithm for each house in H. However, this would give me a runtime of O(|H|*MlogN) and we want a runtime of O(MlognN). Are there any modifications that can be made to Dijkstra's algorithm to achieve this runtime? I have to treat each house as a source vertex to find the shortest distance and I don't see any way that can be done in the required time complexity.

ZaO Lover
  • 433
  • 2
  • 13

1 Answers1

1

Use Dijkstra initialized from each center, not house.

Mark all houses as unvisited, mark all centers with distance 0

Add all centers to PQ.

Continue with dijkstra...

Ecto
  • 1,125
  • 1
  • 7
  • 13
  • What is the reasoning behind having multiple source vertices? Also, why just the test centers as sources? The graph is undirected so couldn't you also let each house be a source? – PeraltaLearns Oct 22 '20 at 17:36
  • Well you are looking for path to *any* center, you can basically imagine all centers as 1 node. It would be possible to do this multiple times for every center separately and always choose the min value in every house, but it would be more complex (You would do it C* instead of 1*). If you let the houses in the source, you don't have properly defined "starting point" - you can't tell what is your current distance. If you wanted to include the houses, you would probably have to remember distances for every node in every node, scaling it to quadratic complexity (also memory-wise). – Ecto Oct 22 '20 at 18:00