我不知道我是否应该在这里问这个问题,问题是算法.想象一下,你有一个无向图.边缘有不同的值.想象一下,有些顶点是“好”而有些是“坏”.现在我想确定两个好节点,以便它们之间的路径尽可能短(如果路径包含不是问题的坏节点). 最佳答案 你想要做的是一次从所有好节点开始增长路径,然后在你发现两个相遇之后不久就停止.然后你找到了最短路径.
有一个微妙的复杂性.考虑一个三角形ABC.如果A-B和B-C的权重均为2,A-C为3,则在A-C之前查看边A-B和B-C.这意味着您在A-C(重量3)之前找到路径A-B-C(重量4).但是在所有这些情况下,您会在找到第一个边缘之前看到边缘存在.
这是伪代码.
node_path_info is is a dictionary of vertex to information about the path
upcoming is priority queue of vertices to consider next, sorted on .cost
initialize node_path_info and upcoming
for node in list of good nodes:
upcoming.add( {
"node": node,
"node_from": None,
"cost": 0,
"good_node", node,
} )
best_path_cost = None
best_middle1 = None
best_middle2 = None
while upcoming:
current = upcoming.pop()
if current.node in good_node_from:
if current.good_node == good_node_from[current.node]:
pass # We found a loop
else:
cost = current.cost + node_path_info[current.node].cost
if best_path_cost is None or cost < best_path_cost < best_path_cost:
best_path_cost = cost
best_middle1 = current.node
best_middle1 = current.node_from
else:
node_path_info[current.node] = current
if best_path_cost is not None: # still looking for first path
for (next_node, weight) in get_connected_weight(current.node):
upcoming.add({
"node": next_node,
"node_from": current.node,
"cost": current.cost + weight,
"good_node", current.good_node,
})
path1 = path from best_middle1 back
path2 = path from best_middle2 back
path1 + reversed(path2) is your answer.
在最坏的情况下,您需要访问所有边缘两次.使用随机连接图和2个良好节点,您将访问连接到O(sqrt(n))顶点的所有边.