progress

~/problems / Trees / Tree DP

Barn painting

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~25 min

A farm has n barns numbered 1..n, joined by n - 1 paths so that every barn is reachable (a tree). Each barn gets one of 3 colours, 1, 2 or 3, and two barns joined by a path must get different colours. Some barns are already painted and can't be changed.

Write count_colorings(n: int, edges: list[tuple[int, int]], painted: list[tuple[int, int]]) -> int: the number of valid ways to colour all barns, modulo 10**9 + 7. painted lists (barn, colour) pairs, each barn at most once.

Examples:

  • count_colorings(3, [(1, 2), (2, 3)], []) == 12: barn 2 has 3 choices, then barns 1 and 3 have 2 each.
  • count_colorings(3, [(1, 2), (2, 3)], [(1, 1), (3, 2)]) == 1: barn 2 must be colour 3.
  • count_colorings(2, [(1, 2)], [(1, 3), (2, 3)]) == 0

Constraints: 1 <= n <= 100_000.

⭐ Bonus: a speed test with a 100,000-barn path earns a star in O(n). Recursion that deep hits Python's limit, so don't recurse along the path.

Show hint

Root the tree anywhere. For each barn, count the valid colourings of its subtree separately for each colour the barn itself could take.

Topic: Tree DP. Post-order: each node returns a small tuple of states to its parent.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc