LC 2581. 统计可能的树根数目

https://leetcode.cn/problems/count-number-of-possible-root-nodes/

题解 解释得非常清楚了:

"换根DP", 这个解法之前还没有听说过。

class Solution:
    def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int:
        n = len(edges) + 1
        adj = [[] for _ in range(n)]
        for x, y in edges:
            adj[x].append(y)
            adj[y].append(x)

        ss = {(x, y) for (x, y) in guesses}

        def dfs(x, p):
            r = 0
            for y in adj[x]:
                if y == p: continue
                r += ((x, y) in ss)
                r += dfs(y, x)
            return r

        base = dfs(0, -1)

        def reroot(x, p, now):
            r = 0
            if now >= k: r += 1
            for y in adj[x]:
                if y == p: continue
                r += reroot(y, x, (now - ((x, y) in ss) + ((y, x) in ss)))
            return r

        ans = reroot(0, -1, base)
        return ans