为什么蓝桥杯 结点选择只有70分
我用的python
是从网上抄的代码
def dfs(now,pre):
global value,table
# print('now',now)
# print('pre',pre)
for i in table.get(now):
if i !=pre:
dfs(i,now)
# print('dfs完成!',now,i)
value[now][0]+=max(value[i][0],value[i][1])
value[now][1]+=value[i][0]
# print(value[now][0],value[now][1])
n = int(input())
value = list(map(int, input().split()))
value = list(map(lambda x:[0,x],value))
value.insert(0,0)
# print(value)
table = {}
for i in range(n):
table.update({i + 1: []})
for i in range(n - 1):
father, child = list(map(int, input().split()))
table.get(father).append(child)
table.get(child).append(father)
# print(table)
dfs(3, 0)
print(max(value[3][0], value[3][1]))
你看看这行不行
def dfs(tree, pre, f):
value = 0
for child in tree[pre]:
value1 = dfs(tree, child, False)
if not f:
value2 = dfs(tree, child, True) + child
if value2 > value1:
value1 = value2
value += value1
return value
n = int(input())
value = list(map(int, input().split()))
tree = {}
sroot = [i for i in range(1,n+1)]
for i in range(n + 1):
tree.update({i: []})
for i in range(n - 1):
father, child = list(map(int, input().split()))
tree.get(father).append(child)
if child in sroot:
sroot.remove(child)
tree[0] = sroot
print(dfs(tree, 0, False))