小美的美丽树-DFS

小美的美丽树

http://www.nowcoder.com/questionTerminal/f4161b1bac304f5b803fed3e3758d4bb

DFS即可

from collections import defaultdict
N, K = map(int, input().strip().split())
tree = list(map(int, input().strip().split()))
adj = defaultdict(list)
for _ in range(N-1):
    i, j = map(int, input().strip().split())
    adj[i].append(j)
    adj[j].append(i)

def make_tree(i):
    for j in adj[i]:
        if i in adj[j]:
            adj[j].remove(i)
        make_tree(j)

root = int(input().strip())
make_tree(root)

res = -1
diff = -float('inf')
best_node = N
def dfs(node):
    global diff
    global res
    global best_node
    min_val = max_val = tree[node - 1]
    count = 1
    for i in adj[node]:
        tmin, tmax, tcount = dfs(i)
        min_val = min(tmin, min_val)
        max_val = max(tmax, max_val)
        count += tcount

    if count <= K:
        cur_diff = max_val-min_val
        if cur_diff > diff or (cur_diff == diff and best_node>node):
            res = node
            best_node = node
            diff = max_val-min_val

    return (min_val, max_val, count)

dfs(root)
print(res)
全部评论

相关推荐

10-27 17:26
东北大学 Java
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务