标签:add print 它的 his tree party 指南 max 程序员
一棵多叉树代表员工的上下级关系,孩子节点是父节点的直接下级。节点代表员工,属性包括快乐值和孩子节点列表。
大家参加了party,要求一个员工去了则它的所有直接下级都不能去,问参加party能得到的最大快乐值是多少。
package Tree;
import java.util.ArrayList;
class Employee{
int happyVal;
ArrayList<Employee> list=new ArrayList<>();
public Employee(int happyVal,ArrayList<Employee> list) {
this.happyVal=happyVal;
this.list=list;
}
}
class HappyReturnType{
int withoutRoot;
int withRoot;
public HappyReturnType(int withoutRoot,int withRoot) {
this.withoutRoot=withoutRoot;
this.withRoot=withRoot;
}
}
public class Main {
public static void main(String args[]) {
//test
Employee e1=new Employee(100,null);//level3
ArrayList<Employee> e2ChildList=new ArrayList<Employee>();
e2ChildList.add(e1);
Employee e2=new Employee(500,e2ChildList);//level2
Employee e3=new Employee(400,null);//level2
ArrayList<Employee> e4ChildList=new ArrayList<Employee>();
e4ChildList.add(e2);
e4ChildList.add(e3);
Employee e4=new Employee(200,e4ChildList);//level1
//compute
HappyReturnType r=maxHappyVal(e4);
int maxHappyVal=Math.max(r.withoutRoot, r.withRoot);
System.out.println(maxHappyVal);
}
public static HappyReturnType maxHappyVal(Employee node) {
int withoutRoot=0;
int withRoot=node.happyVal;
if(node.list==null) {
return new HappyReturnType(0,node.happyVal);
}
for(Employee childNode:node.list) {
HappyReturnType r=maxHappyVal(childNode);
int happyVal=Math.max(r.withoutRoot,r.withRoot);
withoutRoot+=happyVal;
withRoot+=r.withoutRoot;
}
return new HappyReturnType(withoutRoot,withRoot);
}
}
标签:add print 它的 his tree party 指南 max 程序员
原文地址:https://www.cnblogs.com/coding-gaga/p/11080111.html