当前位置: 首页 > 面试经验 >

阿里算法笔试

优质
小牛编辑
164浏览
2023-03-28

阿里算法笔试

编程第二题想知道错在哪里,怎么都ac不了

import sys

if __name__ == "__main__":

# 读取第一行的n

h = sys.stdin.readline().strip()

n,k = map(int, h.split())

score = sys.stdin.readline().strip()

score = list(map(int, score.split()))

score = [-1000] + score

edge = [[] for _ in range(n+1)]

for i in range(n-1):

# 读取每一行

line = sys.stdin.readline().strip()

# 把每一行的数字分隔后转化成int列表

e = list(map(int, line.split()))

edge[e[0]].append(e[1])

def dfs(x):

if edge[x] == []:

return score[x]

for i in range(len(edge[x])):

score[x] += dfs(edge[x][i])

return score[x]

dfs(1)

score.sort(key=lambda x:-x)

print(score[k-1])

 类似资料: