繁体   English   中英

动态编程帮助:二叉树成本边缘

[英]Dynamic Programming Help: Binary Tree Cost Edge

给定具有n个叶子和一组C颜色的二叉树。 树的每个叶节点都从集合C中获得唯一的颜色。因此,没有叶节点具有相同的颜色。 树的内部节点是未着色的。 集合C中的每对颜色都有与之相关的成本。 因此,如果树的边缘连接了颜色为A和B的两个节点,则边缘成本为线对(A,B)的成本。 我们的目标是为树的内部节点提供颜色,从而最小化树的总边缘成本。

我已经解决了这个问题几个小时了,并没有真正想出一个有效的解决方案。 任何提示将不胜感激。

我将使用伪代码解决问题,因为我尝试编写解释,即使我自己也无法理解。 希望代码能够解决问题。 我的解决方案的复杂性不是很好-在O(C ^ 2 * N)中存储一个运行时。

我将需要几个我将在动态方法中使用的数组:
dp [N][C][C] -> dp[i][j][k]如果以颜色j绘制它的父树并以颜色着色,则可以从以节点i为根的树上获得的最高价格k
maxPrice[N][C] -> maxPrice[i][j]如果其父节点用颜色j上色,则可以从以节点i为根的树上获得的最高价格
color[leaf] - >叶片的颜色leaf
price[C][C] -> price[i][j]如果您有一对相邻的颜色为ij节点,则价格为chosenColor[N][C] -> chosenColor[i][j]应该为节点i选择获取maxPrice[i][j]

让我们假设节点是使用拓扑排序排序的 ,即我们将处理第一片叶子。 在树中进行拓扑排序非常容易。 让排序给出内部节点inner_nodes的列表

for leaf in leaves:
   for i in 0..MAX_C, j in 0..MAX_C
       dp[leaf][i][j] = (i != color[leaf]) ? 0 : price[i][j]
   for i in 0..MAX_C,
       maxPrice[leaf][i] = price[color[leaf]][i]
       chosenColor[leaf][i] = color[leaf]
for node in inner_nodes
   for i in 0..MAX_C, j in 0..MAX_C
       dp[node][i][j] = (i != root) ? price[i][j] : 0
       for descendant in node.descendants
           dp[node][i][j] += maxPrice[descendant][i]
   for i in 0...MAX_C
       for j in 0...MAX_C
         if maxPrice[node][i] < dp[node][j][i]
             maxPrice[node][i] = dp[node][j][i]
             chosenColor[node][i] = j

for node in inner_nodes (reversed)
   color[node] = (node == root) ? chosenColor[node][0] : chosenColor[node][color[parent[node]]

作为一个起点,您可以使用贪婪的解决方案,它为您提供总成本的上限:

while the root is not colored
    pick an uncolored node having colored descendants only
        choose the color that minimizes the total cost to its descendants

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM