在二叉树中查找一组 "k"标记顶点的算法,该算法最小化所有节点到标记祖先的距离

标签 algorithm binary-tree dynamic-programming

这是我原来的问题:

enter image description here

我需要设计一个如上所述的算法。
我不确定该怎么做。
我知道应该始终标记根节点,否则成本将是无限的。
我想我应该以某种方式使用动态规划。
我不确定如何将问题分解为子问题。

最佳答案

如下创建一个具有三个变量的动态状态

func( index of node(ind),
      how many nodes can be colored in this subtree(k),
      distance to closest marked ancestor(d) )

现在对于每个状态,您可以像这样计算出最佳结果:

if node is leaf
    if k>0 // if we can mark this node the distance will be 0
        return 0
    return d
result = infinity

// if this node is not marked yet, and we can mark it, mark it
if d != 0 and k > 0 
    result = min(result, func(ind, k-1, 0)
for t=0 to k
    // dedicate t mark nodes to left child and k-t mark nodes to right child
    result = min(result, func(index of left_child, t, d+1) + 
                         func(index of right_child, k-t, d+1) +
                         d )
return result // sum of the distances of this node and its descendants to the closest marked node

打电话

func(0, // root index
     k,
     infinity)

会给你最好的结果。

您可以将每个状态的结果保存在内存表中,以将此解决方案转换为动态方法。

关于在二叉树中查找一组 "k"标记顶点的算法,该算法最小化所有节点到标记祖先的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39738220/

相关文章:

c++ - 时间戳组织的容器

optimization - 具有查找功能的优先队列 - 最快的实现

c - 如何在C中删除二叉树中的元素?

java - 最大子和

algorithm - 理解动态规划的好例子、文章、书籍

使用#include<algorithm> 的 C++ 编译错误

algorithm - 长度为 n 的字符串的所有子序列

algorithm - 在没有额外空间的情况下,在 N 个排序数组中查找公共(public)元素

c# - ReheapUp 和 ReheapDown 递归到迭代的转换 C#

c++ - 查找 C++ 中回文的数量