Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 查找一组“的算法”;k";二叉树中的标记顶点,使所有节点到标记祖先的距离最小化_Algorithm_Binary Tree_Dynamic Programming - Fatal编程技术网

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

Algorithm 查找一组“的算法”;k";二叉树中的标记顶点,使所有节点到标记祖先的距离最小化,algorithm,binary-tree,dynamic-programming,Algorithm,Binary Tree,Dynamic Programming,这是我的原始问题: 我需要设计一个如上所述的算法。 我不知道该怎么做。 我知道应该始终标记根节点,否则成本将是无限的。 我想我应该以某种方式使用动态规划。 我不知道如何将问题分解成子问题。创建一个包含三个变量的动态状态,如下所示 func( index of node(ind), how many nodes can be colored in this subtree(k), distance to closest marked ancestor(d) ) 现在,对

这是我的原始问题:

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

我不知道如何将问题分解成子问题。

创建一个包含三个变量的动态状态,如下所示

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)
会给你最好的结果


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

请发表文章,并将实际问题显示为文本而不是屏幕截图。其他人无法从您的图像复制和粘贴。详情请参阅。谢谢。我已经用Python实现了我的答案。如果我的答案不够清楚,我也可以添加实现。@sudomakeinstall2:我认为你的答案有道理,但我仍在仔细研究细节,以确保我理解。看到你的Python实现也会对我的学习有所帮助。@Peng:我下次将使用文本,谢谢你的建议。为什么在伪代码的第一行检查节点是否是叶子?我们永远不会想要标记叶节点,对吗?“标记”或颜色。因此,伪代码的第一部分基本上是说,一旦我们到达基本情况(叶节点),如果我们留下了k个标记,则标记叶节点,使其距离为0,否则返回其距离。哦。为什么从来没有?正如代码中所述,在某些情况下,我们可以标记它们。比如N=3和K=2。在很多情况下,我们应该在一些树叶上做标记。我现在明白了,我已经仔细考虑过了。如果您不介意共享python代码的话,我也不介意看到这些代码。@flapdoodle这里是实现:,我将在后面添加实现并进行详细解释。