[英]maximum independent set weight
我正在嘗試解決此先前提出的問題中概述的問題:
在二叉樹中找到最大獨立集的大小-為什么錯誤的“解決方案”不起作用?
給定一個具有n個整數的數組A,其索引從0開始(即A [0],A [1],…,A [n-1])。 我們可以將A解釋為二叉樹,其中A [i]的兩個子元素分別是A [2i + 1]和A [2i + 2],每個元素的值是樹的節點權重。 在這棵樹中,我們說如果一組頂點不包含任何父子對,則它們是“獨立的”。 獨立集合的權重只是其元素所有權重的總和。 開發一種算法來計算任何獨立集合的最大權重。
但是,我正在嘗試用Java解決此問題。 我已經在鏈接的問題中查看了python解決方案,但是這一行對我來說沒有意義:
with_root = sum(map(find_max_independent, grandkids))+ max(true_root[root_i],0)
有與該解決方案等效的Java嗎?
當然有Java等效項。 雖然可能取決於您所說的“等效”。 我不會精通當前的Java,因此我只為您講解這句話。
sum(map(find_max_independent, grandkids))
意思是:
find_max_independent(grandkids[0]) + find_max_independent(grandkids[1]) + ...
max(true_root[root_i], 0)
如果不是負數,則僅是當前節點的權重,否則為零(請注意,權重已知為“整數”,因此它們可能為負數)。 雖然,實際上沒有必要進行檢查,因為使用零意味着不包括不包含在節點中的節點,而該節點已經被without_root
覆蓋。
該算法不是所要求的O(n),我已經在此處寫過評論。 這實際上是一個,也更簡單:
def max_independant_weight(weights):
def with_and_without(i):
if i >= len(weights):
return 0, 0
left = with_and_without(2*i + 1)
right = with_and_without(2*i + 2)
return (weights[i] + left[1] + right[1],
max(left) + max(right))
return max(with_and_without(0))
正如Stefan所說的那樣,我的解決方案沒有用。 所以我將他翻譯成Java。 我制作了靜態方法,但是可以隨心所欲地做任何事情。
public static void main(String[] args)
{
int[] tree = new int[] { 3, 2, 2 };
System.out.println(max_independant_weight(tree));
}
private static int max(int[] array)
{
int max = Integer.MIN_VALUE;
for (int i : array)
{
if (i > max)
{
max = i;
}
}
return max;
}
private static int max_independant_weight(int[] weights)
{
return max(with_and_without(weights, 0));
}
private static int[] with_and_without(int[] weights, int i)
{
if (i >= weights.length)
{
return new int[] { 0, 0 };
}
int[] left = with_and_without(weights, (2 * i) + 1);
int[] right = with_and_without(weights, (2 * i) + 2);
return new int[] { weights[i] + left[1] + right[1], max(left) + max(right) };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.