华为OD机试D卷-最富裕的小家庭(100分) JAVA
题意:小家庭指的是当前节点和其所有直接子节点的团体
代码如下:建立树,遍历树
import java.util.*; class NodeFam { int val; List<NodeFam> children; public NodeFam(int val) { this.val = val; this.children = new ArrayList<>(); } } public class OJTest10 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); int[] wealths = new int[N]; for (int i = 0; i < wealths.length; i++) { wealths[i] = in.nextInt(); } NodeFam[] nodes = new NodeFam[N]; for (int i = 0; i < N; i++) { nodes[i] = new NodeFam(wealths[i]); } for (int i = 0; i < N - 1; i++) { int parent = in.nextInt(); int child = in.nextInt(); nodes[parent - 1].children.add(nodes[child - 1]); } int wealthCount = findMaxFamilyWealth(nodes[0]); System.out.println(wealthCount); } private static int findMaxFamilyWealth(NodeFam node) { if (node == null) { return 0; } int currentFamilyWealth = node.val; for (NodeFam child : node.children) { currentFamilyWealth += child.val; } int maxAmongChildren = 0; for (NodeFam child : node.children) { maxAmongChildren = Math.max(maxAmongChildren, findMaxFamilyWealth(child)); } return Math.max(currentFamilyWealth, maxAmongChildren); } }