import java.util.ArrayList; import java.util.List; public class test22 { //派对的最大快乐值问题 //1.如果某个员工来了,那么这个员工的所有下级都不来 //2.派对的整体快乐值为所有到场员工的累加 //3.要使派对的快乐值尽可能大 //给一棵多叉树的头节点head,返回派对最大的快乐值 public static class Employee{ public int happy; public List<Employee> nexts; public Employee(int h){ happy = h; nexts = new ArrayList<>(); } } public static int maxHappy1(Employee boss){ if(boss ==null){ return 0; } Info all = process1(boss); return Math.max(all.yes , all.no); } public static class Info{ //yes为头节点来到时候的最大快乐值 //no为头节点不来的时候的最大快乐值 public int yes; public int no; public Info(int y ,int n){ yes = y; no = n; } } public static Info process1(Employee x){ if(x.nexts.isEmpty()){ return new Info(x.happy , 0); } int yes = x.happy; int no = 0; //对每个员工都调用递归得到信息 for (Employee next : x.nexts){ Info nextInfo = process1(next); yes += nextInfo.no; no += Math.max(nextInfo.yes , nextInfo.no); } return new Info(yes ,no); } }
派对最大快乐值问题(动态规划)
最新推荐文章于 2024-09-05 11:00:53 发布