Sub topic 7
Counting Colorings and Selections Modulo a Prime
This chapter assumes you know the include/exclude states from the independent set chapter. It also assumes you have the root_tree helper, which returns parent, a pre-order order, and subtree sizes. You should also know that a * b % m keeps numbers small.
Optimization problems ask for the best configuration. Counting problems ask how many valid configurations exist. The tree structure stays the same. Only the way states combine changes:
| Optimization | Counting |
|---|---|
| `max` over alternatives | `+` over alternatives |
| `+` across independent children | `*` across independent children |
| Answer fits in a machine word | Answer grows exponentially, so reduce modulo a prime |
The second row is the key idea. Once the parent's state is fixed, the subtrees of different children do not interact. Every choice in one child pairs with every choice in another. So the counts multiply.
Counting Independent Sets
An independent set is a set of nodes with no two adjacent. Use the same two states as before, but have them hold counts:
take[u]: the number of independent sets in u's subtree that contain u.skip[u]: the number of independent sets in u's subtree that do not contain u.
If u is taken, every child must be skipped, so take[u] is the product of skip[v] over children v. If u is skipped, each child can go either way, so skip[u] is the product of take[v] + skip[v]. A leaf has take = skip = 1.
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, size
def count_independent_sets(n, edges):
parent, order, _ = root_tree(n, edges)
take = [1] * n
skip = [1] * n
for u in reversed(order):
p = parent[u]
if p != -1:
take[p] = take[p] * skip[u] % MOD
skip[p] = skip[p] * (take[u] + skip[u]) % MOD
return (take[0] + skip[0]) % MOD
print(count_independent_sets(3, [(0, 1), (1, 2)])) # 5The path 0–1–2 has five independent sets: the empty set, {0}, {1}, {2}, and {0, 2}. The count includes the empty set. If the problem wants only non-empty sets, subtract 1 modulo MOD.
Starting both arrays at 1 is the base case. 1 is the identity for multiplication, so a node with no children keeps the value 1. The mistake to avoid is starting at 0. That turns every product into 0.
Counting Proper Colorings with Fixed Nodes
A proper coloring with k colors gives each node a color so that adjacent nodes differ. With no constraints, the answer is simply k·(k−1)^(n−1). It gets interesting when some nodes have a fixed color. Then you need one state per color:
dp[u][c]: the number of valid colorings of u's subtree with u colored c.
A child v can use any color except c. That gives total[v] - dp[v][c] options, where total[v] is the sum of dp[v][d] over all colors d. Subtracting from the total makes each child cost O(k) instead of O(k²).
def count_colorings(n, edges, k, fixed):
# fixed[u] is a color in range(k), or -1 if u is free
parent, order, _ = root_tree(n, edges)
dp = []
for u in range(n):
if fixed[u] == -1:
dp.append([1] * k)
else:
dp.append([1 if c == fixed[u] else 0 for c in range(k)])
for u in reversed(order):
p = parent[u]
if p != -1:
total = sum(dp[u]) % MOD
for c in range(k):
dp[p][c] = dp[p][c] * ((total - dp[u][c]) % MOD) % MOD
return sum(dp[0]) % MOD
print(count_colorings(3, [(0, 1), (1, 2)], 3, [-1, -1, -1])) # 12
print(count_colorings(3, [(0, 1), (1, 2)], 3, [0, -1, 0])) # 2In the second call, both ends are color 0. The middle node can be color 1 or color 2, so the answer is 2.
Common Errors
- Reducing too late. Take the remainder after every multiplication. In Python, the code stays correct without this, but it slows down as the integers grow. In fixed-width languages, the values silently wrap around.
- Dividing. You cannot divide a residue by an ordinary integer. If a transition needs division, multiply by the modular inverse,
pow(x, MOD - 2, MOD). This works only whenMODis prime and x is not 0 moduloMOD. A count can be a multiple ofMODwithout being 0, so it is usually safer to avoid division altogether. - Counting the same thing twice. A product over children is correct only if the child choices are independent once the parent's state is fixed. If two children interact, for example through a constraint on how many of them are chosen, you need a richer state.
Exercise
A star has a center node connected to 4 leaves. How many independent sets does it have, counting the empty set?
Show answer
If the center is taken, every leaf is skipped, which gives 1 set. If the center is skipped, each leaf is independently in or out, which gives 2^4 = 16 sets. The total is 17.
Exercise
Change countindependentsets so it counts vertex covers instead. A vertex cover is a set of nodes that touches every edge.
Show answer
If u is not in the cover, every child must be: skip[p] = take[u]. If u is in the cover, children are free: take[p] = take[u] + skip[u]. The base cases stay at 1 and the answer is still take[0] + skip[0]. On the path 0–1–2 this gives 5: {1}, {0,1}, {1,2}, {0,2}, {0,1,2}.