AcWing 285. 没有上司的舞会python3
原题链接
简单
作者:
xanxus1111
,
2020-07-10 13:14:35
,
所有人可见
,
阅读 567
import sys
def add(a,b):
global idx
e[idx] = b
ne[idx] = h[a]
h[a] = idx
idx += 1
def dfs(u):
f[u][1] = happy[u]
i = h[u]
while i != -1:
j = e[i]
dfs(j)
f[u][1] += f[j][0]
f[u][0] += max(f[j][0],f[j][1])
i = ne[i]
if __name__=='__main__':
#解决爆栈问题
limit = 10000
sys.setrecursionlimit(limit)
n = int(input())
N = 6010
happy = [0]*N
h, e, ne, idx = [-1]* N, [0]* N, [0]* N, 0
f = [[0]*2 for i in range(N)]
has_father = [False]*N
for i in range(1,n+1):
happy[i] = int(input())
for i in range(n-1):
a,b = map(int,input().split())
add(b,a)
has_father[a] = True
root = 1
while has_father[root]: root += 1
dfs(root)
print(max(f[root][0],f[root][1]))