문제링크 : https://school.programmers.co.kr/learn/courses/30/lessons/76503
import sys
sys.setrecursionlimit(10 ** 8)
ans = 0
def dfs(dep, graph, visited, node, score):
global ans
for i in graph[node]:
if not visited[i]:
visited[i] = True
score[node] += dfs(dep + 1, graph, visited, i, score)
ans += abs(score[node])
return score[node]
def solution(a, edges):
if sum(a) != 0:
return -1
graph = [[] for _ in range(len(a))]
for x, y in edges:
graph[x].append(y)
graph[y].append(x)
visited = [False] * len(a)
visited[0] = True
dfs(0, graph, visited, 0, a)
return ans