【问题标题】:Center of tree with weighted edges (possibly negative)带加权边缘的树中心(可能为负)
【发布时间】:2015-01-11 07:42:43
【问题描述】:

对于未加权的树和具有正边缘权重的树,我之前已经看到过这个问题,但还没有看到可能具有负权重的树的解决方案。

作为参考,树的中心定义为与任何其他顶点的最大距离最小的顶点。

【问题讨论】:

    标签: algorithm graph tree graph-algorithm weighted


    【解决方案1】:

    这与具有正边权重的树的动态规划解决方案完全相同。让我们运行两次深度优先搜索(我们可以选择任意顶点作为根)。在第一阶段,我们将计算distIn(v) = the longest distance from v to a vertex from the v's subtree. 我认为这部分是微不足道的(如果需要我可以详细说明)。在第二阶段,我们将为所有v 计算不在v 子树内的最远顶点。我们称之为distOut(v)。这是它的伪代码:

    void computeDistOut(v, pathFromParent) 
        distOut(v) = pathFromParent
        childDists = empty list
        for c : children of v
            childDists.add(distIn(c) + cost(v, c))
        for c : children of v
            maxDist = max among all distances from childDists except (distIn(c) + cost(v, c))
            computeDistOut(c, max(pathFromParent, maxDist) + cost(v, c))
    

    到每个顶点的最大距离是max(distIn(v), distOut(v))。现在我们可以选择一个最小化这个值的顶点(根据定义它是一个中心)。

    关于时间复杂度:如果这个解决方案实施得当,它是线性的。我们可以只在其中存储两个最大值,而不是维护到所有孩子的距离列表(childDists 伪代码)。它允许我们获得O(1) 中的maxDist 值(它是第一个或第二个最大值)。

    【讨论】:

    • 对于第一部分,the longest distance from v to a vertex from the v's subtree 这只是一个 DFS 对吧?我也不明白the furthest vertex which is not inside the v's subtree for all v 是什么意思。
    • @1110101001 第一部分:是的,它只是一个dfs。对于固定顶点v,任何其他顶点要么在v 的子树内,要么不在。第二部分处理那些不在v的子树内的顶点(v的子树表示以v为根的子树)。
    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多