Algorithm for finding a spanning tree with weights of 1 and 2 only

混江龙づ霸主 提交于 2020-01-01 17:04:11

问题


Given a weighted, connected, simple undirected graph G with weights of only 1 and 2 on each edge, find the MST of G in O(V+E). Any ideas?

Sorry for the phrasing of the question, I tried translating it as best as I could.


回答1:


In Prim's algorithm you need a way of storing active edges such that you can access and delete the edge with lowest weight.

Normally there are a wide range of weights and some kind of heap data structure is used to store the edges.

However, in this case, the weights are either 1 or 2, and so you can simply store the edges in 2 separate lists, one for edges with weight 1, and the second for edges with weight 2.

To find the edge with lowest weight you simply take one from the first list, unless it is empty, in which case you take an edge from the second list.

Accessing and deleting an element from a list is O(1) so Prim's algorithm will run in O(V+E).




回答2:


Prim's algorithm computes a minimum spanning tree when edges have arbitrary weights.

Prim's algorithm works by doing a sort of breadth-first search, starting from some arbitrary node, and keeping the edges in a priority queue. It keeps extracting the lowest-weight edge and either discarding it without expanding the search (if the edge leads to a node already in the tree) or adding it to the result, marking its opposite node as in the tree, and expanding the search.

Done in the naive way I just explained, Prim's algorithm is dominated by the cost of enqueueing and dequeueing |E| edges into/outof the priority queue. Each enqueue/dequeue takes O(log |E|) time, so the total asymptotic cost is O(|E| log |E|) time or, more properly, O(|E| log |E| + |V|).

If we had some way to do those enqueues and dequeues in constant time, the total running time would be O(|E| + |V|)...



来源:https://stackoverflow.com/questions/17495374/algorithm-for-finding-a-spanning-tree-with-weights-of-1-and-2-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!