您的位置:首页 > Web前端

[2_4_shortest_path_text] BFS => Shortest Path for Graphs with many Vertices buf few Edges

2012-03-10 23:48 465 查看
If the graph is unweighted, the shortest path contains a minimal number of edges. A breadth first search (BFS) will solve the problem in this case, using a queue to visit nodes in order of their distance from the source. If there are many vertices but few edges,
this runs much faster than Dijkstra's algorithm (see Amazing Barn in Sample Problems).

If negative weight edges are allowed, Dijkstra's algorithm breaks down. Fortunately, the Floyd-Warshall algorithm isn't affected so long as there are no negative cycles in the graph (if there is a negative cycle, it can be traversed arbitrarily many times to
get ever `shorter' paths). So, graphs must be checked for them before executing a shortest path algorithm.

It is possible to add additional conditions to the definition of shortest path (for example, in the event of a tie, the path with fewer edges is shorter). So long as the distance function can be augmented along with the comparison function, the problem remains
the same. In the example above, the distance function contains two values: weight and edge count. Both values would be compared if necessary.


Amazing Barn (abridged) [USACO Competition Round 1996]


Consider a very strange barn that consists of N stalls (N < 2500). Each stall has an ID number. From each stall you can reach 4 other stalls, but you can't necessarily come back the way you came.

Given the number of stalls and a formula for adjacent stalls, find any of the `most central' stalls. A stall is `most central' if it is among the stalls that yields the lowest average distance to other stalls using best paths.

Analysis: Compute all shortest paths from each vertex to determine its average distance. Any O(N3) algorithm for computing all-pairs shortest paths would be prohibitively expensive here since N=2500. However, there are very few edges (4
per vertex), making a BFS with queue ideal. A BFS runs in O(E) time, so to compute shortest paths for all sources takes O(VE) time - about: 

2500 x 10,000 = 2.5 x 106 things, much more reasonable than 25003 = 1.56 x 1010
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息