![](/img/trans.png)
[英]Dynamic Programming on Binary Tree: Maximize data transmitted with limited edge capacity
[英]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]
如果您有一對相鄰的顏色為i
和j
節點,則價格為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.