Problem Description
Given an undirected tree with n nodes and a list of guesses (each guess suggests a parent-child relation along an edge), determine how many nodes can be chosen as the root such that at least k of Bob's guesses turn out to be correct.
Key Insights
- The tree is an undirected structure but every choice of the root produces a directed (parent-child) tree.
- Start by rooting the tree arbitrarily (e.g., at node 0) and compute the number of correct guesses.
- Use a re-rooting technique while performing DFS to efficiently compute the correct guess count for every possible root by updating the count when moving the root from a parent to one of its children.
- When re-rooting along an edge (u, v), adjust the correct guess count:
- Subtract 1 if the guess (u, v) was counted (because u was parent of v in the original rooting).
- Add 1 if the guess (v, u) becomes valid in the new rooting.
- Use a set or hash for quick lookup of guess edges.
Space and Time Complexity
Time Complexity: O(n + g) where n is the number of nodes and g is the number of guesses.
Space Complexity: O(n + g) due to the adjacency list and the guess set.
Solution
The solution involves two main DFS traversals:
- The initial DFS from an arbitrary root (node 0) calculates the number of correct guesses based on the initial parent-child relationships.
- A re-root DFS traverses from the initial root to all other nodes. When moving from node u to its child v, the count of correct guesses is updated based on:
- Removing the correct count if the guess (u, v) held in the old rooting.
- Adding the correct count if the guess (v, u) holds in the new rooting. By counting how many nodes have a correct guess count greater than or equal to k, we answer the problem.
Data structures used:
- An adjacency list for representing the undirected tree.
- A set (or equivalent) for constant time lookups of guesses.
- Recursion (DFS) for tree traversal.
This approach leverages the re-rooting trick to efficiently update the result for all possible roots in O(n) time.