我正在树上做这个基本的 dp(动态规划)问题(https://cses.fi/problemset/task/1674/)。给定公司的结构(层次结构是一棵树),任务是计算每个员工的下属人数。
这:
import sys
from functools import lru_cache # noqa
sys.setrecursionlimit(2 * 10 ** 9)
if __name__ == "__main__":
n: int = 200000
boss: list[int] = list(range(1, 200001))
# so in my example it will be a tree with every parent having one child
graph: list[list[int]] = [[] for _ in range(n)]
for i in range(n-1):
graph[boss[i] - 1].append(i+1) # directed so neighbours of a node are only its children
@lru_cache(None)
def dfs(v: int) -> int:
if …Run Code Online (Sandbox Code Playgroud)