我不确定是否应该在这里提出这个问题,这个问题与算法有关。想象一下你有一个无向图。边有不同的值。想象一些顶点是“好”的,一些是“坏”的。现在我想确定两个好节点,使它们之间的路径尽可能短(如果路径包括坏节点,那也没问题)。
我不确定是否应该在这里提出这个问题,这个问题与算法有关。想象一下你有一个无向图。边有不同的值。想象一些顶点是“好”的,一些是“坏”的。现在我想确定两个好节点,使它们之间的路径尽可能短(如果路径包括坏节点,那也没问题)。
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.
O(sqrt(n))
个顶点相连的所有边。