题目描述:在一棵树中,每个节点代表一个家庭成员,节点的数字表示只其个人的财富值,一个节点及其直接相连的子节点被定义为一个小家庭
现给你一棵树,请计算出最富裕的小家庭的财富和。
输入描述: 第一行为一个数N,表示成员总数,成员编号1-N,1<=N<=1000第二行为N个空格分隔的数,表示编号1-N的成员的财富值。0<=财富值<=1000000接下来N-1行,每行两个空格分隔的整数(N1,N2),表示N1是N2的 父节点Q输出描述:
最富裕的小家庭的财富和
class TreeNode:
def __init__(self, wealth):
self.wealth = wealth
self.children = []
def build_tree_and_calculate_wealth(N, wealth_values, connections):
# 创建树的结构
members = [TreeNode(wealth) for wealth in wealth_values]
for parent, child in connections:
members[parent - 1].children.append(members[child - 1])
# 计算每个节点及其直接相邻子节点的财富总和
for member in members:
member.wealth += sum(child.wealth for child in member.children)
# 找到最富裕的小家庭
max_wealth = max(member.wealth for member in members)
return max_wealth
# 读取输入
N = int(input())
wealth_values = list(map(int, input().split()))
connections = [map(int, input().split()) for _ in range(N - 1)]
result = build_tree_and_calculate_wealth(N, wealth_values, connections)
print(result)