通知网络所有节点的时间最少

时间:2018-12-09 23:33:14

标签: algorithm graph

问题:输入是无方向图,边上有权重,代表计算机网络,其中边的权重意味着在两台计算机之间发送消息所需的最短时间。我们选择该图的一个顶点,然后向连接的顶点发送一条消息。当顶点接收到消息时,它将仅重新发送一次给邻居。需要花最少的时间通知图中的每个顶点。

我已经实现了蛮力算法来解决这个问题,但是它太慢了(N ^ 2)。首先,我认为这可以作为最小生成树的权重来解决,但是它上面需要一些东西。

我认为有一些解决该问题的算法...

1 个答案:

答案 0 :(得分:0)

为此目的,应该对dijkstras algorithm进行修改。但是,一旦搜索到所有节点,该算法就会终止,而不是搜索到达特定节点的最短路径。完成上述操作后,问题就减少了,从遍历图形时所建立的表中提取出距源节点最大距离的节点。

longest_path(node):
    # dijkstras algo
    path_len = map()
    queue = priority_queue()  # priority-queue sorted by distance to source-node
    visited = set() 

    path_len[node] = 0
    queue.put(node)       

    while queue not empty
        n = queue.pop()

        if n in visited
            continue

        for neighbor in n.neighbors()
            dist = path_len[n] + n.edge_length(neighbor)
            if neighbor not in path_len or path_len[neighbor] > dist
                queue.offer(neighbor)
                path_len[neighbor] = dist

         visited.add(n)

     # find the node with the maximum distance to the source-node
     max = -1
     res = NULL
     for n in path_len.keys()
         if path_len[n] > max
             max = path_len[n]
             res = n

     return res

以上算法在O(|E| + |V| log |V|)最坏的情况下有效。

相关问题