Sub topic 7
Counting Colorings and Selections Modulo a Prime
The earlier chapters used tree DP to optimize: each subtree reported the best value it could reach. This chapter changes the question to "how many?" How many independent sets does the tree have? How many valid colorings? How many connected groups of nodes? The traversal and the state design stay the same. What changes is how child results are combined: you multiply where you used to add, and you add where you used to take a maximum. Every operation is reduced modulo a prime so the numbers stay small.
This chapter assumes you have read the earlier chapters. You should know root_tree and the reversed pre-order traversal, and you should know the include/exclude states used for maximum-weight independent set. You also need basic modular arithmetic: what a % p means and why (a * b) % p equals ((a % p) * (b % p)) % p.
From Optimization to Counting
An optimization DP asks for the best choice in each subtree. A counting DP asks how many full configurations exist. The two rules that turn one into the other come from elementary combinatorics.
- Sum rule. If the configurations split into disjoint cases, the total is the sum of the case counts. In tree DP the cases are usually the states of the current node (taken or not taken, or color 1, 2, …, k).
- Product rule. If a configuration is built from independent parts, its count is the product of the part counts. Once a node's state is fixed, the subtrees of its children do not interact, so their counts multiply.
The independence in the product rule is the reason tree DP works for counting. When a node's state is fixed, any edge between two different child subtrees has to pass through that node, and no such edge exists. So a choice made in one child's subtree cannot restrict a choice made in another's.
The table below maps each optimization operation to its counting counterpart.
| Optimization DP | Counting DP | Why |
|---|---|---|
| `max` over the node's choices | `+` over the node's choices | the choices are disjoint cases |
| `+` across children | `*` across children | child subtrees are independent |
| identity for `max`: minus infinity | identity for `+`: 0 | an impossible state contributes nothing |
| identity for `+`: 0 | identity for `*`: 1 | a leaf with no children has exactly one way to complete |
The last two rows matter most when you initialize the arrays. Counting tables start at 1, the empty product, for states that are allowed, and at 0 for states that are forbidden.
Why Modulo a Prime
Counts on trees grow exponentially. A star with n leaves has 2^n + 1 independent sets, so even n = 200 gives a number with about 60 digits. Python handles big integers, but multiplying them over and over gets slow. In C++, Java, or Rust the values overflow without any warning. Problem statements therefore ask for the count modulo a prime p, usually 10**9 + 7 or 998244353.
Addition, subtraction, and multiplication can be reduced modulo p at every step without changing the final answer. Division cannot, as explained below. Reduce after every multiplication. Then each intermediate value stays below p², which fits in a signed 64-bit integer for both common primes.
Shared Setup
The code blocks in this chapter belong in one file. This first block repeats root_tree from the earlier chapter so the file runs on its own.
MOD = 10**9 + 7
def root_tree(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
seen = [False] * n
seen[root] = True
order = []
stack = [root]
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
stack.append(v)
size = [1] * n
for u in reversed(order):
if parent[u] != -1:
size[parent[u]] += size[u]
return parent, order, sizeEvery loop below walks reversed(order) and folds child u into its parent p. When the loop reaches u, all of u's children are already folded into it, because children appear after their parent in order. So u's value is final at the moment it is used.
Counting Independent Sets
An independent set is a set of nodes in which no two are joined by an edge. The empty set counts. The states are the same as in the maximum-weight version:
inc[u]: the number of independent sets in u's subtree that contain u.exc[u]: the number of independent sets in u's subtree that do not contain u.
The transitions follow from the sum and product rules:
- If u is included, no child can be included:
inc[u] = product over children c of exc[c]. - If u is excluded, each child is free:
exc[u] = product over children c of (inc[c] + exc[c]).
A leaf has inc = exc = 1, the empty product. The answer is inc[root] + exc[root].
def count_independent_sets(n, edges, root=0):
parent, order, _ = root_tree(n, edges, root)
inc = [1] * n
exc = [1] * n
for u in reversed(order):
p = parent[u]
if p != -1:
inc[p] = inc[p] * exc[u] % MOD
exc[p] = exc[p] * (inc[u] + exc[u]) % MOD
return (inc[root] + exc[root]) % MOD
print(count_independent_sets(4, [(0, 1), (0, 2), (1, 3)])) # 8Worked example
The tree has edges 0–1, 0–2, and 1–3, rooted at 0. It is the path 3–1–0–2.
| Node | Children | inc | exc | inc + exc |
|---|---|---|---|---|
| 3 | none | 1 | 1 | 2 |
| 2 | none | 1 | 1 | 2 |
| 1 | 3 | exc[3] = 1 | 2 = 2 | 3 |
| 0 | 1, 2 | exc[1]·exc[2] = 2·1 = 2 | 3·2 = 6 | 8 |
A path of 4 nodes has F(6) = 8 independent sets, where F is the Fibonacci sequence. The DP agrees.
Compared with the maximum-weight version, the code changes in only three places: += becomes *=, max becomes +, and the arrays start at 1 instead of at the weight and 0.
Counting Colorings With Constraints
A proper k-coloring gives each node one of k colors so that adjacent nodes get different colors. With no extra constraints, a tree has a closed-form count. The root has k choices, and every other node has k − 1 choices because it only has to differ from its parent. That gives k·(k−1)^(n−1).
The DP becomes necessary when constraints break the formula. A common version precolors some nodes. Use one state per color:
dp[u][c]: the number of proper colorings of u's subtree in which u has color c.
Child c' is compatible with u's color c whenever c' ≠ c. Let S[v] be the sum of dp[v][x] over all colors x. The number of compatible colorings of child v's subtree is then S[v] − dp[v][c]. That is a complement: you subtract the one forbidden case instead of summing the k − 1 allowed ones. The transition is:
dp[u][c] = product over children v of (S[v] − dp[v][c])
Each fold costs O(k), so the whole DP costs O(n·k). Summing the k − 1 allowed colors directly for each c would cost O(n·k²).
def count_colorings(n, edges, k, fixed, root=0):
# fixed[u] is a color in range(k), or -1 if u is free
parent, order, _ = root_tree(n, edges, root)
dp = []
for u in range(n):
if fixed[u] == -1:
dp.append([1] * k)
else:
row = [0] * k
row[fixed[u]] = 1
dp.append(row)
for u in reversed(order):
p = parent[u]
if p != -1:
total = sum(dp[u]) % MOD
row_u, row_p = dp[u], dp[p]
for c in range(k):
row_p[c] = row_p[c] * (total - row_u[c]) % MOD
return sum(dp[root]) % MOD
path = [(0, 1), (0, 2), (1, 3)]
print(count_colorings(4, path, 3, [-1, -1, -1, -1])) # 24 = 3 * 2**3
print(count_colorings(4, path, 3, [0, -1, -1, 0])) # 4In the second call, nodes 0 and 3 are both fixed to color 0. Node 1 sits between them and has 2 choices. Node 2 only has to differ from node 0 and has 2 choices. That gives 2·2 = 4.
Precoloring is handled entirely in the initial table: a forbidden color starts at 0, so it contributes nothing to any product it enters. The same idea covers per-node lists of allowed colors.
Counting Connected Selections
A connected selection is a non-empty set of nodes that induces a connected subtree. Each such set has exactly one highest node, the node closest to the root. So you can count the sets by their highest node and never count one twice.
f[u]: the number of connected sets whose highest node is u.
When u is the top node, each child v either stays out of the set (1 way) or joins through a connected set whose top is v (f[v] ways). The transition is f[u] = product over children of (1 + f[v]), and the answer is the sum of f[u] over all nodes.
def count_connected_subsets(n, edges, root=0):
parent, order, _ = root_tree(n, edges, root)
f = [1] * n
for u in reversed(order):
p = parent[u]
if p != -1:
f[p] = f[p] * (1 + f[u]) % MOD
return sum(f) % MOD
print(count_connected_subsets(4, [(0, 1), (0, 2), (1, 3)])) # 10On the example path the values are f[3] = 1, f[2] = 1, f[1] = 2, and f[0] = (1 + 2)(1 + 1) = 6, which sum to 10. A path of 4 nodes has 4·5/2 = 10 contiguous segments, so the DP agrees.
The "1 +" is the include/exclude choice folded into a single factor: 1 for leaving the child out and f[v] for taking it in. If the problem also limits the size of the set, the state needs a size index, and the fold becomes the table merge covered in the tree knapsack chapter.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| Initializing counts at 0 | every answer is 0 | allowed states start at 1, the empty product |
| Counting the empty set when the problem wants only non-empty sets | answer is off by exactly 1 | subtract 1 at the root, or use a "top node" state as in connected selections |
| Counting a structure once per node it contains | answer is too large by a factor | attribute each structure to one canonical node, such as its highest node |
| Reducing only at the end | slow in Python, overflow in other languages | reduce after every multiplication |
| Dividing to remove a child's factor | wrong answers on some inputs | use prefix and suffix products (see below) |
| Recursion on a path-shaped tree | `RecursionError` near depth 1000 | use the iterative order from `root_tree` |
The division trap
Later, in rerooting, you will want a node's product over all children except one. Dividing by that one child's factor seems natural. Modulo a prime you can divide by multiplying with the inverse pow(x, MOD - 2, MOD), which follows from Fermat's little theorem. The inverse exists only when x is not 0 modulo p. A factor can be exactly 0 modulo p, for example when a color is forbidden or when a count happens to be a multiple of p. In that case the inverse does not exist and the division gives a wrong result. The safe method is to build prefix and suffix products over a node's children list. Then "all children except child i" is prefix[i] * suffix[i + 1], and no division is needed.
Testing Against Brute Force
Counting bugs often produce numbers that look reasonable. Check small random trees against exhaustive enumeration before you trust a DP.
import random
def brute_independent_sets(n, edges):
count = 0
for mask in range(1 << n):
if all(not (mask >> u & 1 and mask >> v & 1) for u, v in edges):
count += 1
return count
def random_tree(n):
return [(i, random.randrange(i)) for i in range(1, n)]
for _ in range(300):
n = random.randint(1, 10)
edges = random_tree(n)
assert count_independent_sets(n, edges) == brute_independent_sets(n, edges) % MOD
print("all tests passed")Include n = 1 with an empty edge list. The single-node tree is where incorrect identity values show up first. For colorings, also test k = 1: the answer must be 0 for every n > 1 and 1 for n = 1.
Exercise
Count the vertex covers of a tree modulo 10**9 + 7. A vertex cover is a set of nodes that touches every edge. Give the states, the transitions, and the answer for the path 3–1–0–2.
Show answer
Let inc[u] count the covers of u's subtree that contain u, and let exc[u] count those that do not. If u is in the cover, every child is free: inc[u] = product of (inc[c] + exc[c]). If u is not in the cover, the edge to each child must be covered by the child: exc[u] = product of inc[c]. Leaves have inc = exc = 1. For the path, nodes 3 and 2 give (1, 1). Node 1 gives inc = 2 and exc = 1. Node 0 gives inc = 3·2 = 6 and exc = inc[1]·inc[2] = 2·1 = 2. The total is 8. This matches the independent-set count, because the complement of a vertex cover is an independent set.
Exercise
In count_colorings, why is the per-child factor S[v] − dp[v][c] instead of a sum over colors c' ≠ c, and how does this change the running time?
Show answer
The colorings of v's subtree split by v's color, so the compatible ones are all of them minus those where v has color c. This uses one subtraction per color instead of a sum of k − 1 terms. The work per edge falls from O(k²) to O(k), so the total falls from O(n·k²) to O(n·k).
Exercise
A student counts connected selections by setting f[u] = product of (1 + f[v]) and returns f[root]. On the path 3–1–0–2 rooted at 0, what do they get, and what did they actually count?
Show answer
They get 6. That number counts only the connected sets that contain the root. Sets that lie entirely inside a child subtree, such as {3} or {1, 3}, are missing. Summing f over all nodes counts every set exactly once, by its highest node, and gives 10.
Exercise
Why is it unsafe to reroot the independent-set count by dividing exc[p] by (inc[u] + exc[u]) modulo p, and what should you do instead?
Show answer
The modular inverse of a value exists only when that value is not 0 modulo the prime. A product can be 0 modulo the prime even though the true integer count is positive. Division then fails or gives a wrong result. Compute prefix and suffix products over each node's children, and form the "all children except u" product as prefix times suffix, with no division.