Sub topic 3
Counting Colorings and Selections Modulo a Prime
This chapter assumes you know the earlier chapters' root_tree helper and the take/skip states, and that you are comfortable with Big-O analysis. It covers counting with modular arithmetic, rerooting, tree knapsack, and small-to-large merging.
Counting Configurations
Counting problems reuse the include/exclude states. You multiply where an optimization problem would take a maximum, and you add where it would combine alternatives. The counts grow exponentially, so reduce modulo a prime such as 10^9 + 7 after every operation.
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, root=0):
parent, order, _ = root_tree(n, edges, root)
take = [1] * n # ways with u chosen
skip = [1] * n # ways with u not chosen
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[root] + skip[root]) % MOD
print(count_independent_sets(3, [(0, 1), (1, 2)])) # 5Rerooting
To get an answer for every root, first compute down[u] bottom-up from root 0. Then walk top-down and move the root across each edge. For the sum of distances, moving the root from p to child u brings the size[u] nodes in u's subtree one step closer and pushes the other n - size[u] nodes one step farther:
ans[u] = ans[p] - size[u] + (n - size[u])
Both passes are O(n), so the total is O(n). Running a separate DFS from every root would cost O(n²).
Tree Knapsack and Its Bound
dp[u][j] stores the best value of a connected set of j nodes that contains u. When a finished child table is merged into its parent's table, both tables are capped at k entries, so each merge costs at most min(a, k) · min(b, k).
| Case | Why the total cost is bounded |
|---|---|
| Both parts smaller than k | Each pair of nodes is charged once, at their lowest common ancestor. Such small parts together give O(n·k). |
| A part reaches size k | Each such merge costs O(k²), and at most n/k of them occur, which gives O(n·k). |
Without the cap, the same argument still gives O(n²) in total.
Small-to-Large Merging
Sometimes each subtree carries a set or a map, for example the distinct colors in the subtree. Keep the largest child's container and insert the smaller containers into it. Each time an element moves, the container it lands in is at least twice the size of the one it left. So each element moves O(log n) times, and the total is O(n log n) container operations.
Exercise
For a star with center 0 and leaves 1..4, what does countindependentsets return?
Show answer
17. Choosing the center allows only that one set, and skipping it allows any subset of the 4 leaves: 1 + 2^4 = 17.
Exercise
In small-to-large merging, why must you keep the larger container instead of always keeping the parent's own container?
Show answer
The doubling argument depends on moving elements only from the smaller container into the larger one. If you always keep the parent's container, a chain can move the same elements O(n) times, which costs O(n²) in total.