C - Prefix Covering Editorial by evima
First, let’s consider how to find the answer when \(k\) is fixed.
We create a Trie with \(\{S_1, S_2, \dots, S_k\}\) as keys, add vertices appropriately so that every vertex has either \(0\) or \(2\) children, and rephrase this as the following binary tree problem:
Given a binary tree where every vertex has either \(0\) or \(2\) children, and a set of vertices \(T\), in how many ways can we color some vertices in \(T\) black and all other vertices white such that the following condition is satisfied?
It is impossible to reach a leaf by following only white vertices from the root
This problem can be solved with the following tree DP:
- \(dp_v =\) number of ways to color vertices in the subtree rooted at \(v\) such that it’s impossible to reach a leaf by following only white vertices from \(v\)
- Recurrence relation:
- If \(v\) is a leaf:
- If \(v\) is not in \(T\): \(dp_v = 0\)
- If \(v\) is in \(T\): \(dp_v = 1\)
- If \(v\) is not a leaf (let \(l\) and \(r\) be the two children of \(v\), and let \(C_v\) be the number of vertices in \(T\) contained in the subtree rooted at \(v\)):
- If \(v\) is not in \(T\): \(dp_v = dp_l \times dp_r\)
- If \(v\) is in \(T\): \(dp_v = dp_l \times dp_r + 2^{C_v-1}\)
- If \(v\) is a leaf:
Next, let’s consider how to solve the above problem efficiently for all \(k\). By considering updating \(dp\) and \(C\) appropriately each time a vertex is added to \(T\), we can see that these values change only for vertices on the path from \(v\) to the root. Even if we update these naively in a bottom-up manner, the time complexity is \(O(|S_k|)\), and the overall time complexity is \(O(\sum_k |S_k|)\), which is sufficiently fast. (Code)
posted:
last update: