本文共 1226 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要找到某个员工及其所有直系下属的重要度之和。我们可以将员工信息看作是一个树形结构,其中每个员工是一个结点,直系下属是子节点。我们可以使用广度优先搜索(BFS)来高效地遍历整个子树,计算所有重要度之和。
import sysfrom collections import dequedef get_importance(employees, target_id): # 创建邻接表 table = {} for employee in employees: employee_id = employee[0] importance = employee[1] subordinates = employee[2] table[employee_id] = (importance, subordinates) # 初始化队列并设置结果 queue = deque([target_id]) total_importance = 0 while queue: current_id = queue.popleft() imp, subs = table[current_id] total_importance += imp # 将下属加入队列 queue.extend(subs) return total_importanceif __name__ == "__main__": # 示例输入 input_employees = [ [1, 5, [2, 3]], [2, 3, []], [3, 3, []] ] target_id = 1 result = get_importance(input_employees, target_id) print(result) table,键为员工ID,值为一个元组包含重要度和下属列表。这种方法确保了我们能够高效地遍历整个子树,计算所有重要度之和。BFS的时间复杂度为O(N),其中N是员工数量,适用于处理较大的数据量。
转载地址:http://jscr.baihongyu.com/