簡體   English   中英

在二叉樹中找到一組“k”個標記頂點的算法,該算法最小化所有節點到標記祖先的距離

[英]Algorithm to find a set of "k" marked vertices in a binary tree that minimizes distance to marked ancestors for all nodes

這是我遇到的原始問題:

在此處輸入圖片說明

我需要設計一個如上所述的算法。
我不知道該怎么做。
我知道應該始終標記根節點,否則成本將是無限的。
我想我應該以某種方式使用動態編程。
我不確定如何將問題分解為子問題。

用三個變量創建動態狀態如下

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)

會給你最好的結果。

您可以將每個狀態的結果保存在記憶表中,以將此解決方案轉換為動態方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM