Tree 求最大和,使n元树中没有两个元素相邻
我希望设计一种动态规划方法,选择狮子,使其在给定标准下最大化总狩猎能力 标准:任何狮子都不能与其直系父母一起狩猎 我设计了一个算法,但该算法不能正常工作。这个算法有什么问题 树示例(左子右同级表示): 节点: 最大化方法:Tree 求最大和,使n元树中没有两个元素相邻,tree,dynamic-programming,graph-algorithm,greedy,Tree,Dynamic Programming,Graph Algorithm,Greedy,我希望设计一种动态规划方法,选择狮子,使其在给定标准下最大化总狩猎能力 标准:任何狮子都不能与其直系父母一起狩猎 我设计了一个算法,但该算法不能正常工作。这个算法有什么问题 树示例(左子右同级表示): 节点: 最大化方法: private int findParentHuntingAbility(Node root) { return root.data.getHuntingAbility(); } private int findKidsHunti
private int findParentHuntingAbility(Node root) {
return root.data.getHuntingAbility();
}
private int findKidsHuntingAbility(Node root) {
int sumOfKidsHuntingAbility = 0;
if(root.child != null) {
root = root.child;
while(root != null) {
sumOfKidsHuntingAbility += root.data.getHuntingAbility();
root = root.next;
}
}
return sumOfKidsHuntingAbility;
}
最大化狩猎能力的算法:
//Traverses tree in depth first order
public int findMaxHuntingAbility(Node root)
{
int maxHuntingAbility = 0;
if(root == null)
return 0;
while(root != null)
{
if(root.child != null)
findMaxHuntingAbility(root.child);
maxHuntingAbility += Math.max(findKidsHuntingAbility(root),findParentHuntingAbility(root));
root = root.next;
}
return maxHuntingAbility;
}
//Traverses tree in depth first order
public int findMaxHuntingAbility(Node root)
{
int maxHuntingAbility = 0;
if(root == null)
return 0;
while(root != null)
{
if(root.child != null)
findMaxHuntingAbility(root.child);
maxHuntingAbility += Math.max(findKidsHuntingAbility(root),findParentHuntingAbility(root));
root = root.next;
}
return maxHuntingAbility;
}